@nice2dev/ui-ai 1.0.29 → 1.1.5

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,47 +1,21 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),o=require("react");class Ue{constructor(a={},r){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1,this.config={maxRequestsPerMinute:a.maxRequestsPerMinute??30,maxTokensPerSession:a.maxTokensPerSession??1e4,warnThresholdPercent:a.warnThresholdPercent??80},this.onWarning=r}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,r=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||r>=this.config.warnThresholdPercent}}reset(){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1}pruneOldTimestamps(){const a=Date.now()-6e4;this.timestamps=this.timestamps.filter(r=>r>a)}checkWarning(){var r;if(this.warningEmitted)return;this.getStatus().isWarning&&(this.warningEmitted=!0,(r=this.onWarning)==null||r.call(this))}}const We=o.createContext(null);function Ha({config:i,rateLimits:a,enabled:r=!0,onRateLimitWarning:t,children:n}){const s=o.useRef(null);s.current||(s.current=new Ue(a,t));const c=o.useCallback(()=>s.current.getStatus(),[]),d=o.useMemo(()=>({config:i,enabled:r,rateLimiter:s.current,getRateLimitStatus:c}),[i,r,c]);return e.jsx(We.Provider,{value:d,children:n})}function ee(){return o.useContext(We)}async function*Ge(i,a){var s,c,d,m,f,g,y,k,M;const r=(s=i.body)==null?void 0:s.getReader();if(!r)throw new Error("Response body is not readable");const t=new TextDecoder;let n="";try{for(;!(a!=null&&a.aborted);){const{done:T,value:j}=await r.read();if(T)break;n+=t.decode(j,{stream:!0});const A=n.split(`
2
- `);n=A.pop()??"";for(const _ of A){const l=_.trim();if(!(!l||l===":")){if(l.startsWith("data:")){const N=l.slice(5).trim();if(N==="[DONE]"){yield{token:"",done:!0};return}try{const w=JSON.parse(N),p=((m=(d=(c=w.choices)==null?void 0:c[0])==null?void 0:d.delta)==null?void 0:m.content)??"",x=((g=(f=w.choices)==null?void 0:f[0])==null?void 0:g.finish_reason)==="stop";(p||x)&&(yield{token:p,done:x,usage:w.usage})}catch{N&&(yield{token:N,done:!1})}continue}try{const N=JSON.parse(l),w=N.text??N.content??N.token??"";w&&(yield{token:w,done:!1})}catch{l&&(yield{token:l,done:!1})}}}}if(n.trim()){const T=n.trim();if(T.startsWith("data:")){const j=T.slice(5).trim();if(j&&j!=="[DONE]")try{const _=((M=(k=(y=JSON.parse(j).choices)==null?void 0:y[0])==null?void 0:k.delta)==null?void 0:M.content)??"";_&&(yield{token:_,done:!0})}catch{yield{token:j,done:!0}}}}}finally{r.releaseLock()}}async function Ke(i){var r,t,n,s;const a=await i.json();if((n=(t=(r=a.choices)==null?void 0:r[0])==null?void 0:t.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 ce=new Map;function He(i,a){const r=a?{...i,fieldValue:void 0,formContext:void 0}:i;return JSON.stringify(r)}function Ea(i,a){const r=[],t=a.systemPrompt??"You are a helpful assistant providing concise contextual hints for form fields. Keep responses short (1-3 sentences). Be specific and actionable.";r.push({role:"system",content:t});const n=[];if(i.fieldLabel&&n.push(`Field: "${i.fieldLabel}"`),i.fieldType&&n.push(`Type: ${i.fieldType}`),!a.privacyMode&&i.fieldValue!==void 0){const c=typeof i.fieldValue=="string"?i.fieldValue:JSON.stringify(i.fieldValue);n.push(`Current value: ${c}`)}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:
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),d=require("react"),L=require("@nice2dev/ui-core"),ka=require("@nice2dev/ui");class Fe{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 Je=d.createContext(null);function Na({config:t,rateLimits:a,enabled:i=!0,onRateLimitWarning:r,children:n}){const s=d.useRef(null);s.current||(s.current=new Fe(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(Je.Provider,{value:l,children:n})}function Q(){return d.useContext(Je)}async function*qe(t,a){var s,c,l,m,g,x,w,N,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:R,value:j}=await i.read();if(R)break;n+=r.decode(j,{stream:!0});const I=n.split(`
2
+ `);n=I.pop()??"";for(const _ of I){const o=_.trim();if(!(!o||o===":")){if(o.startsWith("data:")){const k=o.slice(5).trim();if(k==="[DONE]"){yield{token:"",done:!0};return}try{const y=JSON.parse(k),p=((m=(l=(c=y.choices)==null?void 0:c[0])==null?void 0:l.delta)==null?void 0:m.content)??"",b=((x=(g=y.choices)==null?void 0:g[0])==null?void 0:x.finish_reason)==="stop";(p||b)&&(yield{token:p,done:b,usage:y.usage})}catch{k&&(yield{token:k,done:!1})}continue}try{const k=JSON.parse(o),y=k.text??k.content??k.token??"";y&&(yield{token:y,done:!1})}catch{o&&(yield{token:o,done:!1})}}}}if(n.trim()){const R=n.trim();if(R.startsWith("data:")){const j=R.slice(5).trim();if(j&&j!=="[DONE]")try{const _=((S=(N=(w=JSON.parse(j).choices)==null?void 0:w[0])==null?void 0:N.delta)==null?void 0:S.content)??"";_&&(yield{token:_,done:!0})}catch{yield{token:j,done:!0}}}}}finally{i.releaseLock()}}async function Ue(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 re=new Map;function Le(t,a){const i=a?{...t,fieldValue:void 0,formContext:void 0}:t;return JSON.stringify(i)}function Ca(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:
3
3
  ${n.join(`
4
- `)}`:"Provide a helpful suggestion.";return r.push({role:"user",content:s}),r}function Q(i={},a={}){i=i??{},a=a??{};const{debounceMs:r=500,disabled:t=!1}=a,n=ee(),[s,c]=o.useState(""),[d,m]=o.useState(!1),[f,g]=o.useState(null),[y,k]=o.useState(!1),M=o.useRef(null),T=o.useRef(0),j=o.useCallback(async()=>{var h,I,H;if(!n||!n.enabled||t)return;const{config:l,rateLimiter:N}=n;if(!N.recordRequest()){g("Rate limit exceeded. Please wait before requesting another hint.");return}const w=He(i,l.privacyMode??!1),p=ce.get(w);if(p){c(p),m(!1),g(null),k(!1);return}(h=M.current)==null||h.abort();const x=new AbortController;M.current=x,m(!0),g(null),c(""),k(!1);const v=Ea(i,l),u=l.stream!==!1;try{const C={"Content-Type":"application/json",...l.headers};l.apiKey&&(C.Authorization=`Bearer ${l.apiKey}`);const z=JSON.stringify({model:l.model??"gpt-3.5-turbo",messages:v,temperature:l.temperature??.7,max_tokens:l.maxTokens??256,stream:u}),O=await fetch(l.endpoint,{method:"POST",headers:C,body:z,signal:x.signal});if(!O.ok){const B=await O.text().catch(()=>O.statusText);throw new Error(`AI request failed (${O.status}): ${B}`)}if(u){k(!0);let B="";for await(const b of Ge(O,x.signal))if(x.signal.aborted||(B+=b.token,c(B),(I=b.usage)!=null&&I.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)}ce.set(w,B)}else{const B=await Ke(O);c(B.text),ce.set(w,B.text),(H=B.usage)!=null&&H.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{x.signal.aborted||(m(!1),k(!1))}},[n,i,t]);o.useEffect(()=>{if(!n||!n.enabled||t)return;const l=setTimeout(j,r);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,r,t,n==null?void 0:n.enabled,T.current]),o.useEffect(()=>()=>{var l;(l=M.current)==null||l.abort()},[]);const A=o.useCallback(()=>{var l;(l=M.current)==null||l.abort(),m(!1),k(!1)},[]),_=o.useCallback(()=>{if(n){const l=He(i,n.config.privacyMode??!1);ce.delete(l)}T.current+=1,j()},[n,i,j]);return!n||!n.enabled?{text:"",loading:!1,error:null,streaming:!1,abort:()=>{},refresh:()=>{},hint:null,fetchHint:async()=>{}}:{text:s,loading:d,error:f,streaming:y,abort:A,refresh:_,hint:s?{content:s}:null,fetchHint:async()=>{await j()}}}const Da=(i,a)=>a,Ba=o.createContext(Da);function Ye(){return{t:o.useContext(Ba)}}o.createContext({dir:"ltr",isRTL:!1,flip:i=>i,value:i=>i.ltr});o.createContext(null);o.createContext(null);const Fa={radius:"md",shadow:"md",fill:"solid",buttonStyle:"flat",inputStyle:"bordered",cardStyle:"elevated",badgeStyle:"solid",tabStyle:"underline",toggleStyle:"default",tooltipStyle:"dark",modalStyle:"default",tableStyle:"default",menuStyle:"default",animation:"normal",density:"normal"};o.createContext({displayStyle:"default",variantConfig:Fa,setDisplayStyle:()=>{}});const Va={"chevron-down":"M6 9l6 6 6-6","chevron-up":"M18 15l-6-6-6 6","chevron-left":"M15 18l-6-6 6-6","chevron-right":"M9 6l6 6-6 6","arrow-left":"M19 12H5m0 0l7 7m-7-7l7-7","arrow-right":"M5 12h14m0 0l-7-7m7 7l-7 7","arrow-up":"M12 19V5m0 0l-7 7m7-7l7 7","arrow-down":"M12 5v14m0 0l7-7m-7 7l-7-7",close:"M18 6L6 18M6 6l12 12",plus:"M12 5v14m-7-7h14",minus:"M5 12h14",check:"M5 13l4 4L19 7",edit:"M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7M18.5 2.5a2.121 2.121 0 113 3L12 15l-4 1 1-4 9.5-9.5z",trash:"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",copy:"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",download:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4",upload:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12",refresh:"M4 4v5h5M20 20v-5h-5M20.49 9A9 9 0 005.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 013.51 15",search:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z",filter:"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","sort-asc":"M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12","sort-desc":"M3 4h13M3 8h9m-9 4h9m5-4v12m0 0l-4-4m4 4l4-4",menu:"M4 6h16M4 12h16M4 18h16","more-vertical":"M12 5v.01M12 12v.01M12 19v.01","more-horizontal":"M5 12h.01M12 12h.01M19 12h.01",settings:"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.066 2.573c1.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.573 1.066c-.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.066-2.573c-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",eye:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z M15 12a3 3 0 11-6 0 3 3 0 016 0z","eye-off":"M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24 M1 1l22 22",lock:"M19 11H5a2 2 0 00-2 2v7a2 2 0 002 2h14a2 2 0 002-2v-7a2 2 0 00-2-2zm-3-4a4 4 0 10-8 0v4h8V7z",info:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",warning:"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",error:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z",success:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z",help:"M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z",calendar:"M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z",clock:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z",file:"M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z",folder:"M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z",image:"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",link:"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",mail:"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",phone:"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",user:"M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z",users:"M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z",home:"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",star:"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",heart:"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",bell:"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",grip:"M4 6h2m4 0h2m4 0h2M4 12h2m4 0h2m4 0h2M4 18h2m4 0h2m4 0h2",hash:"M4 9h16M4 15h16M10 3L8 21M16 3l-2 18",list:"M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01",circle:"M12 21a9 9 0 100-18 9 9 0 000 18z",box:"M21 8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16V8z M3.27 6.96L12 12.01l8.73-5.05 M12 22.08V12",tabs:"M3 9h18v10H3z M7 9V5h6v4",columns:"M4 4h7v16H4z M13 4h7v16h-7z",grid:"M3 3h7v7H3z M14 3h7v7h-7z M14 14h7v7h-7z M3 14h7v7H3z",table:"M3 5h18v14H3z M3 10h18M3 15h18M9 5v14M15 5v14",heading:"M6 4v16M18 4v16M6 12h12",type:"M4 7V4h16v3M9 20h6M12 4v16","align-left":"M3 6h18M3 12h12M3 18h15",input:"M4 9h16a1 1 0 011 1v4a1 1 0 01-1 1H4a1 1 0 01-1-1v-4a1 1 0 011-1z M7 12h5",button:"M5 9h14a2 2 0 012 2v2a2 2 0 01-2 2H5a2 2 0 01-2-2v-2a2 2 0 012-2z",select:"M4 6h16a1 1 0 011 1v10a1 1 0 01-1 1H4a1 1 0 01-1-1V7a1 1 0 011-1z M15 11l-3 3-3-3","check-square":"M9 11l3 3L22 4 M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11",video:"M23 7l-7 5 7 5V7z M16 5H3a2 2 0 00-2 2v10a2 2 0 002 2h13a2 2 0 002-2V7a2 2 0 00-2-2z",card:"M3 5h18a1 1 0 011 1v12a1 1 0 01-1 1H3a1 1 0 01-1-1V6a1 1 0 011-1z M3 10h18","bar-chart":"M6 20v-6M12 20V4M18 20v-10",globe:"M12 3a9 9 0 100 18 9 9 0 000-18z M3 12h18 M12 3a14 14 0 010 18 M12 3a14 14 0 000 18",monitor:"M3 4h18a1 1 0 011 1v11a1 1 0 01-1 1H3a1 1 0 01-1-1V5a1 1 0 011-1z M8 21h8 M12 17v4",camera:"M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h3l2-3h6l2 3h3a2 2 0 012 2z M12 17a4 4 0 100-8 4 4 0 000 8z",plug:"M9 2v5 M15 2v5 M7 7h10v3a5 5 0 01-10 0V7z M12 15v7",save:"M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z M17 21v-8H7v8 M7 3v5h8",tag:"M20.59 13.41l-7.17 7.17a2 2 0 01-2.83 0L2 12V2h10l8.59 8.59a2 2 0 010 2.82z M7 7h.01",palette:"M12 2a10 10 0 000 20 2 2 0 002-2c0-.5-.2-1-.5-1.3a2 2 0 01-.5-1.2 2 2 0 012-2H17a5 5 0 005-5c0-5-4.5-9-10-9z M6.5 11.5h.01 M9.5 7.5h.01 M14.5 7.5h.01",book:"M4 19.5A2.5 2.5 0 016.5 17H20 M6.5 2H20v20H6.5A2.5 2.5 0 014 19.5v-15A2.5 2.5 0 016.5 2z",cloud:"M18 10h-1.26A8 8 0 109 20h9a5 5 0 000-10z",target:"M12 3a9 9 0 100 18 9 9 0 000-18z M12 7a5 5 0 100 10 5 5 0 000-10z M12 11a1 1 0 100 2 1 1 0 000-2z",message:"M21 11.5a8.5 8.5 0 01-8.5 8.5 8.4 8.4 0 01-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 01-.9-3.8A8.5 8.5 0 0112.5 3 8.5 8.5 0 0121 11.5z",flask:"M9 2h6 M10 2v6.5L4.5 19a1 1 0 00.9 1.5h13.2a1 1 0 00.9-1.5L14 8.5V2 M7 15h10",rocket:"M12 15l-3-3a22 22 0 012-3.95A12.88 12.88 0 0122 2c0 2.72-.78 7.5-6 11a22 22 0 01-3.95 2z M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0 M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5 M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 00-2.91-.09z",music:"M9 18V5l12-2v13 M9 18a3 3 0 11-6 0 3 3 0 016 0z M21 16a3 3 0 11-6 0 3 3 0 016 0z",wifi:"M5 12.55a11 11 0 0114 0 M8.5 16.11a6 6 0 017 0 M12 20h.01 M2 8.82a15 15 0 0120 0",database:"M12 8c4.97 0 9-1.34 9-3s-4.03-3-9-3-9 1.34-9 3 4.03 3 9 3z M21 5v6c0 1.66-4.03 3-9 3s-9-1.34-9-3V5 M21 11v6c0 1.66-4.03 3-9 3s-9-1.34-9-3v-6",slash:"M12 3a9 9 0 100 18 9 9 0 000-18z M5.6 5.6l12.8 12.8",puzzle:"M19.4 13.6a1.6 1.6 0 10.2-3.2H19V7a2 2 0 00-2-2h-3.4v-.4a1.6 1.6 0 10-3.2 0V5H7a2 2 0 00-2 2v3.4h.4a1.6 1.6 0 100 3.2H5V17a2 2 0 002 2h3.4v.4a1.6 1.6 0 103.2 0V19H17a2 2 0 002-2v-3.4z",dollar:"M12 1v22 M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6",printer:"M6 9V2h12v7 M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2 M6 14h12v8H6z",scale:"M12 3v18 M5 21h14 M5 7l7-2 7 2 M2 13a3 3 0 006 0L5 7zm14 0a3 3 0 006 0L19 7z",accessibility:"M12 3a9 9 0 100 18 9 9 0 000-18z M12 9a1.5 1.5 0 100-3 1.5 1.5 0 000 3z M7.5 10.5l4.5 1 4.5-1 M12 11.5v3.5l-2 3.5 M12 15l2 3.5",window:"M3 4h18a1 1 0 011 1v14a1 1 0 01-1 1H3a1 1 0 01-1-1V5a1 1 0 011-1z M2 9h20 M6 6.5h.01 M9 6.5h.01","map-pin":"M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z M12 13a3 3 0 100-6 3 3 0 000 6z",cursor:"M5 3l14 7-6 2-2 6-6-15z",shuffle:"M16 3h5v5 M4 20L21 3 M21 16v5h-5 M15 15l6 6 M4 4l5 5",lightbulb:"M9 18h6 M10 22h4 M12 2a7 7 0 00-4 12.7c.6.5 1 1.3 1 2.1V18h6v-1.2c0-.8.4-1.6 1-2.1A7 7 0 0012 2z",server:"M3 4h18a1 1 0 011 1v4a1 1 0 01-1 1H3a1 1 0 01-1-1V5a1 1 0 011-1z M3 14h18a1 1 0 011 1v4a1 1 0 01-1 1H3a1 1 0 01-1-1v-4a1 1 0 011-1z M7 7h.01 M7 17h.01",terminal:"M4 17l6-6-6-6 M12 19h8",send:"M22 2L11 13 M22 2l-7 20-4-9-9-4 20-7z",play:"M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z M21 12a9 9 0 11-18 0 9 9 0 0118 0z",pause:"M10 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z",stop:"M21 12a9 9 0 11-18 0 9 9 0 0118 0z M9 10a1 1 0 011-1h4a1 1 0 011 1v4a1 1 0 01-1 1h-4a1 1 0 01-1-1v-4z",mic:"M12 1a3 3 0 00-3 3v8a3 3 0 006 0V4a3 3 0 00-3-3zM19 10v2a7 7 0 01-14 0v-2M12 19v4M8 23h8",expand:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4",collapse:"M9 9V5m0 4H5m4 0L4 4m11 5h4m-4 0V5m0 4l5-5M9 15v4m0-4H5m4 0l-5 5m15-5h-4m4 0v4m0-4l-5 5","external-link":"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14",briefcase:"M20 7H4a2 2 0 00-2 2v9a2 2 0 002 2h16a2 2 0 002-2V9a2 2 0 00-2-2zM16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2M2 12h20",building:"M4 22V4a2 2 0 012-2h12a2 2 0 012 2v18M4 22h16M9 22v-4h6v4M9 6h.01M15 6h.01M9 10h.01M15 10h.01M9 14h.01M15 14h.01",medal:"M15.477 12.89L17 22l-5-3-5 3 1.523-9.11M12 15a6 6 0 100-12 6 6 0 000 12z",clipboard:"M9 2h6a1 1 0 011 1v1a1 1 0 01-1 1H9a1 1 0 01-1-1V3a1 1 0 011-1zM16 4h2a2 2 0 012 2v14a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2h2","skip-forward":"M5 4l10 8-10 8V4zM19 5v14","at-sign":"M12 16a4 4 0 100-8 4 4 0 000 8zM16 12v1.5a2.5 2.5 0 005 0V12a9 9 0 10-3.5 7.14",gift:"M20 12v10H4V12M2 7h20v5H2zM12 22V7M12 7H7.5a2.5 2.5 0 010-5C11 2 12 7 12 7zM12 7h4.5a2.5 2.5 0 000-5C13 2 12 7 12 7z",archive:"M21 8v13H3V8M1 3h22v5H1zM10 12h4",reply:"M9 17l-5-5 5-5M4 12h11a4 4 0 014 4v2",forward:"M15 17l5-5-5-5M20 12H9a4 4 0 00-4 4v2",paperclip:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48",zap:"M13 2L3 14h9l-1 8 10-12h-9l1-8z",square:"M4 4h16v16H4z",triangle:"M12 4L3 20h18z",hexagon:"M7.5 3h9l4.5 9-4.5 9h-9L3 12z",line:"M5 19L19 5",pen:"M12 19l7-7 3 3-7 7-3-3z M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z M11 11a2 2 0 100-4 2 2 0 000 4z",brush:"M9.06 11.9l8.07-8.06a2.85 2.85 0 114.03 4.03l-8.06 8.08 M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 00-3-3.02z",droplet:"M12 2.69l5.66 5.66a8 8 0 11-11.31 0z",bucket:"M5 8h14l-1.5 11a2 2 0 01-2 1.8H8.5a2 2 0 01-2-1.8L5 8z M5 8l2-4h10l2 4",scissors:"M6 9a3 3 0 100-6 3 3 0 000 6z M6 21a3 3 0 100-6 3 3 0 000 6z M20 4L8.12 15.88 M14.47 14.48L20 20 M8.12 8.12L12 12",layers:"M12 2l9 5-9 5-9-5 9-5z M3 12l9 5 9-5 M3 17l9 5 9-5",crop:"M6 2v14a2 2 0 002 2h14 M2 6h14a2 2 0 012 2v14",eyedropper:"M2 22l1-1h3l9-9 M3 21v-3l9-9 M15 6l3.5-3.5a2.12 2.12 0 013 3L18 9l-3-3z",ruler:"M21.3 8.7l-6-6a1 1 0 00-1.4 0L2.7 13.9a1 1 0 000 1.4l6 6a1 1 0 001.4 0L21.3 10.1a1 1 0 000-1.4z M7.5 10.5l2 2 M11 7l2 2 M14.5 3.5l2 2",wand:"M15 4V2 M15 16v-2 M8 9h2 M20 9h2 M3 21l9-9 M12.2 6.2L11 5 M17.8 6.2L19 5 M17.8 11.8L19 13",move:"M5 9l-3 3 3 3 M9 5l3-3 3 3 M15 19l-3 3-3-3 M19 9l3 3-3 3 M2 12h20 M12 2v20",gamepad:"M6 12h4 M8 10v4 M15 13h.01 M18 11h.01 M2 12a4 4 0 014-4h12a4 4 0 014 4l-1.5 6a2 2 0 01-2 1.5H5.5a2 2 0 01-2-1.5L2 12z",eraser:"M7 21l-4.3-4.3a1 1 0 010-1.4l9.6-9.6a2 2 0 012.8 0l4.6 4.6a2 2 0 010 2.8L13 21H7z M22 21H7 M5 12l5 5",thermometer:"M14 14.76V3.5a2.5 2.5 0 00-5 0v11.26a4.5 4.5 0 105 0z",door:"M18 20V5a1 1 0 00-1-1H7a1 1 0 00-1 1v15 M3 20h18 M13 11.5h.01",stairs:"M3 20h3v-3h3v-3h3v-3h3v-3h3",elevator:"M5 3h14a1 1 0 011 1v16a1 1 0 01-1 1H5a1 1 0 01-1-1V4a1 1 0 011-1z M9.5 9L12 6.5 14.5 9 M9.5 15l2.5 2.5 2.5-2.5",bed:"M2 4v16 M2 8h18a2 2 0 012 2v10 M22 17H2 M6 8v4 M2 12h4",sofa:"M3 9V7a2 2 0 012-2h14a2 2 0 012 2v2 M21 9a2 2 0 00-2 2v3H5v-3a2 2 0 00-2-2 2 2 0 00-2 2v4a1 1 0 001 1h18a1 1 0 001-1v-4a2 2 0 00-2-2 M5 18v2 M19 18v2",chair:"M6 11V5a2 2 0 012-2h8a2 2 0 012 2v6 M5 11h14 M6 11l-1 8h14l-1-8 M6 19v2 M18 19v2",utensils:"M3 2v7a2 2 0 002 2 2 2 0 002-2V2 M5 2v20 M21 2v9c0 1-1 1.8-2 1.8h-1V20 M18 2v9",mountain:"M8 3l4 8 5-5 5 15H2L8 3z",tree:"M12 2L7 11h10L12 2z M9 11l3 5 3-5 M12 16v6",sun:"M12 17a5 5 0 100-10 5 5 0 000 10z M12 1v2 M12 21v2 M4.22 4.22l1.42 1.42 M18.36 18.36l1.42 1.42 M1 12h2 M21 12h2 M4.22 19.78l1.42-1.42 M18.36 5.64l1.42-1.42",moon:"M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"},Ja={xs:12,sm:16,md:20,lg:24,xl:32},qa=o.createContext({});function Ua({path:i,size:a,className:r,style:t,color:n,title:s,onClick:c}){return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:a,height:a,viewBox:"0 0 24 24",fill:"none",stroke:n||"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:`nice-icon ${r||""}`,style:t,role:s?"img":"presentation","aria-label":s,"aria-hidden":!s,onClick:c,children:[s&&e.jsx("title",{children:s}),e.jsx("path",{d:i})]})}const $=({name:i,size:a="md",className:r,style:t,color:n,title:s,onClick:c})=>{const{resolver:d}=o.useContext(qa),m=typeof a=="number"?a:Ja[a];if(d){const g=d(i,m);if(g)return e.jsx("span",{className:`nice-icon-wrap ${r||""}`,style:t,onClick:c,children:g})}const f=Va[i];return f?e.jsx(Ua,{path:f,size:m,className:r,style:t,color:n,title:s,onClick:c}):null};o.createContext({direction:"ltr",isRTL:!1,flip:i=>i,flipStyle:(i,a)=>({[i]:a})});o.createContext({permissions:{},getAccessMode:()=>"full"});o.createContext(null);const Wa=process.env.NODE_ENV==="development";let Xe={enabled:Wa,slowRenderThreshold:16};const Ze=[],Se=new Map,Qe=new Map;function Ga(){Ze.length=0,Se.clear(),Qe.clear()}function Ka(i){const a=Xe.slowRenderThreshold;return Ze.filter(r=>r.actualDuration>a)}function te(i){return i<1?`${(i*1e3).toFixed(0)}μs`:i<1e3?`${i.toFixed(2)}ms`:`${(i/1e3).toFixed(2)}s`}function Ya(){const i=Array.from(Se.values()),a=Ka(),r=i.reduce((s,c)=>s+c.renderCount,0),t=i.length>0?i.reduce((s,c)=>s+c.avgRenderTime,0)/i.length:0,n=Array.from(Qe.values());return{stats:i,slowRenders:a,totalRenders:r,avgRenderTime:t,marks:n}}function Xa(){const i=Ya();console.group("%c[Nice2Dev Performance Report]","color: var(--nice-info, #6366f1); font-weight: bold; font-size: 14px"),console.log(`Total renders: ${i.totalRenders}`),console.log(`Average render time: ${te(i.avgRenderTime)}`),console.log(`Slow renders: ${i.slowRenders.length}`),console.group("Component Stats"),console.table(i.stats.sort((a,r)=>r.totalRenderTime-a.totalRenderTime).map(a=>({Name:a.componentName,Renders:a.renderCount,"Avg Time":te(a.avgRenderTime),"Max Time":te(a.maxRenderTime),"Total Time":te(a.totalRenderTime),"Slow Renders":a.slowRenderCount}))),console.groupEnd(),i.slowRenders.length>0&&(console.group("Slow Renders (last 10)"),console.table(i.slowRenders.slice(-10).map(a=>({Component:a.componentName,Phase:a.phase,Duration:te(a.actualDuration),Time:new Date(a.timestamp).toLocaleTimeString()}))),console.groupEnd()),i.marks.length>0&&(console.group("Custom Marks"),console.table(i.marks.filter(a=>a.duration).map(a=>({Name:a.name,Duration:te(a.duration)}))),console.groupEnd()),console.groupEnd()}const Za=o.memo(({position:i="bottom-right",defaultCollapsed:a=!0})=>{const[r,t]=o.useState(a),[n,s]=o.useState([]),[c,d]=o.useState({used:0,total:0});if(o.useEffect(()=>{const f=()=>{const y=Array.from(Se.values());s(y.sort((M,T)=>T.totalRenderTime-M.totalRenderTime).slice(0,10));const k=window.performance;k.memory&&d({used:k.memory.usedJSHeapSize/1024/1024,total:k.memory.totalJSHeapSize/1024/1024})};f();const g=setInterval(f,2e3);return()=>clearInterval(g)},[]),!Xe.enabled)return null;const m={position:"fixed",zIndex:99999,...i.includes("top")?{top:8}:{bottom:8},...i.includes("left")?{left:8}:{right:8}};return e.jsxs("div",{style:{...m,background:"var(--nice-overlay-85, rgba(0, 0, 0, 0.85))",color:"var(--bg-primary, #fff)",borderRadius:8,fontSize:11,fontFamily:"Monaco, Consolas, monospace",padding:r?"4px 8px":8,maxWidth:r?"auto":300,maxHeight:r?"auto":400,overflow:"auto"},children:[e.jsxs("div",{style:{cursor:"pointer",display:"flex",alignItems:"center",gap:8},onClick:()=>t(f=>!f),children:[e.jsx("span",{style:{color:"var(--color-success, #22c55e)"},children:"●"}),e.jsx("span",{children:"Profiler"}),c.used>0&&e.jsxs("span",{style:{color:c.used>100?"var(--color-warning, #f59e0b)":"var(--text-muted, #64748b)"},children:[c.used.toFixed(0),"MB"]}),e.jsx("span",{style:{marginLeft:"auto",opacity:.5},children:r?"▼":"▲"})]}),!r&&e.jsxs("div",{style:{marginTop:8},children:[e.jsx("div",{style:{borderBottom:"1px solid var(--border-color, #333)",paddingBottom:4,marginBottom:8},children:e.jsx("strong",{children:"Top Components"})}),n.map(f=>e.jsxs("div",{style:{marginBottom:4,display:"flex",gap:8},children:[e.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:f.componentName}),e.jsx("span",{style:{color:f.avgRenderTime>16?"var(--color-warning, #f59e0b)":"var(--color-success, #22c55e)"},children:te(f.avgRenderTime)}),e.jsxs("span",{style:{color:"var(--text-muted, #64748b)",minWidth:30,textAlign:"right"},children:["x",f.renderCount]})]},f.componentName)),e.jsxs("div",{style:{marginTop:8,display:"flex",gap:8},children:[e.jsx("button",{onClick:Xa,style:{flex:1,padding:"4px 8px",background:"var(--bg-tertiary, #333)",border:"none",borderRadius:4,color:"var(--bg-primary, #fff)",cursor:"pointer",fontSize:10},children:"Print Report"}),e.jsx("button",{onClick:Ga,style:{flex:1,padding:"4px 8px",background:"var(--bg-tertiary, #333)",border:"none",borderRadius:4,color:"var(--bg-primary, #fff)",cursor:"pointer",fontSize:10},children:"Clear"})]})]})]})});Za.displayName="ProfilerOverlay";process.env.NODE_ENV;o.createContext(null);const Qa=o.createContext({enabled:!0,active:!1,run:()=>{}});function er(){return o.useContext(Qa)}function ar(i,a){if(!i)return null;if(i===!0)return a&&a.length>0?a:null;if(Array.isArray(i))return i.length>0?i:null;const r=i.steps??a;return r&&r.length>0?r:null}function rr(i,a){return i.map(r=>({target:r.target,title:r.titleKey?a(r.titleKey,r.title??""):r.title??"",content:r.contentKey?a(r.contentKey,r.content??""):r.content??"",placement:r.placement,highlightPadding:r.highlightPadding,showArrow:r.showArrow,scrollIntoView:r.scrollIntoView,disableInteraction:r.disableInteraction}))}const ir=({steps:i,autoStart:a,label:r,size:t="md",className:n,style:s,"data-testid":c})=>{const{enabled:d,run:m}=er(),{t:f}=Ye();if(!d||!i||i.length===0)return null;const g=r??f("tutorial.startAria","Start tutorial");return e.jsx("button",{type:"button",className:`nice-tutorial-button nice-tutorial-button--${t}`+(n?` ${n}`:""),style:s,"data-testid":c,"aria-label":g,title:g,onClick:()=>m(rr(i,f),{autoStart:a}),children:"?"})},Ee="nice-tutorial-button-styles";if(typeof document<"u"&&!document.getElementById(Ee)){const i=document.createElement("style");i.id=Ee,i.textContent=`
5
- .nice-tutorial-button {
6
- display: inline-flex;
7
- align-items: center;
8
- justify-content: center;
9
- border: 1px solid var(--nice-border, #cbd5e1);
10
- background: var(--nice-bg, #fff);
11
- color: var(--nice-text-secondary, #475569);
12
- border-radius: var(--nice-radius-full, 9999px);
13
- cursor: help;
14
- font-weight: 700;
15
- line-height: 1;
16
- padding: 0;
17
- transition: background var(--nice-transition, 200ms ease), color var(--nice-transition, 200ms ease), border-color var(--nice-transition, 200ms ease);
18
- }
19
- .nice-tutorial-button:hover {
20
- background: var(--nice-primary, #2563eb);
21
- border-color: var(--nice-primary, #2563eb);
22
- color: var(--nice-text-inverse, #fff);
23
- }
24
- .nice-tutorial-button:focus-visible {
25
- outline: none;
26
- box-shadow: 0 0 0 2px var(--nice-bg, #fff), 0 0 0 4px var(--nice-primary, #2563eb);
27
- }
28
- .nice-tutorial-button--sm { width: 16px; height: 16px; font-size: 11px; }
29
- .nice-tutorial-button--md { width: 20px; height: 20px; font-size: 12px; }
30
- `,document.head.appendChild(i)}o.createContext(null);o.createContext(null);o.createContext(null);const ea={space1:"4px",space2:"8px",space3:"12px",space4:"16px",space5:"20px",space6:"24px",space8:"32px"},aa={fontFamily:"'Inter', system-ui, -apple-system, sans-serif",fontSizeXs:"0.75rem",fontSizeSm:"0.8125rem",fontSizeMd:"0.875rem",fontSizeLg:"1rem",fontSizeXl:"1.125rem",fontWeightNormal:400,fontWeightMedium:500,fontWeightSemibold:600,fontWeightBold:700,lineHeight:1.5},ra={fast:"120ms ease",normal:"200ms ease",slow:"300ms ease"},ia=i=>({color:i,radiusSm:"4px",radiusMd:"6px",radiusLg:"8px",radiusXl:"12px",radiusFull:"9999px"}),tr={sm:"0 1px 2px rgba(0,0,0,0.05)",md:"0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -2px rgba(0,0,0,0.1)",lg:"0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -4px rgba(0,0,0,0.1)",xl:"0 20px 25px -5px rgba(0,0,0,0.1), 0 8px 10px -6px rgba(0,0,0,0.1)"},nr={sm:"0 1px 2px rgba(0,0,0,0.3)",md:"0 4px 6px -1px rgba(0,0,0,0.4)",lg:"0 10px 15px -3px rgba(0,0,0,0.4)",xl:"0 20px 25px -5px rgba(0,0,0,0.4)"};function D(i,a,r,t,n){return{name:i,darkMode:"light",colors:{...a,surface:a.surface??r.primary,surfaceHover:a.surfaceHover??r.secondary},backgrounds:{...r,elevated:r.elevated??r.primary,inset:r.inset??r.tertiary,canvas:r.canvas??r.primary},text:{...t,inverse:t.inverse??"#ffffff"},borders:ia(n),shadows:tr,spacing:ea,typography:aa,transitions:ra}}function Y(i,a,r,t,n){return{name:i,darkMode:"dark",colors:{...a,surface:a.surface??r.secondary,surfaceHover:a.surfaceHover??r.tertiary},backgrounds:{...r,elevated:r.elevated??r.secondary,inset:r.inset??r.primary,canvas:r.canvas??r.primary},text:{...t,inverse:t.inverse??"#0f172a"},borders:ia(n),shadows:nr,spacing:ea,typography:aa,transitions:ra}}D("Slate",{primary:"#64748b",primaryHover:"#475569",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#f8fafc",secondary:"#f1f5f9",tertiary:"#e2e8f0",hover:"#e2e8f0"},{primary:"#1e293b",secondary:"#475569",muted:"#94a3b8"},"#cbd5e1");D("Zinc",{primary:"#71717a",primaryHover:"#52525b",success:"#22c55e",warning:"#eab308",error:"#ef4444",info:"#06b6d4"},{primary:"#fafafa",secondary:"#f4f4f5",tertiary:"#e4e4e7",hover:"#e4e4e7"},{primary:"#18181b",secondary:"#3f3f46",muted:"#a1a1aa"},"#d4d4d8");D("Stone",{primary:"#78716c",primaryHover:"#57534e",success:"#16a34a",warning:"#ca8a04",error:"#dc2626",info:"#0891b2"},{primary:"#fafaf9",secondary:"#f5f5f4",tertiary:"#e7e5e4",hover:"#e7e5e4"},{primary:"#1c1917",secondary:"#44403c",muted:"#a8a29e"},"#d6d3d1");D("Cool Gray",{primary:"#6b7280",primaryHover:"#4b5563",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#3b82f6"},{primary:"#f9fafb",secondary:"#f3f4f6",tertiary:"#e5e7eb",hover:"#e5e7eb"},{primary:"#111827",secondary:"#374151",muted:"#9ca3af"},"#d1d5db");D("Warm Gray",{primary:"#7c7568",primaryHover:"#5c564c",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#faf9f7",secondary:"#f5f4f0",tertiary:"#e8e6e1",hover:"#e8e6e1"},{primary:"#1f1d19",secondary:"#4a463d",muted:"#a09888"},"#d4d0c8");D("Silver",{primary:"#94a3b8",primaryHover:"#64748b",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#38bdf8"},{primary:"#f8fafc",secondary:"#f1f5f9",tertiary:"#e2e8f0",hover:"#e2e8f0"},{primary:"#334155",secondary:"#64748b",muted:"#94a3b8"},"#cbd5e1");D("Charcoal",{primary:"#374151",primaryHover:"#1f2937",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0284c7"},{primary:"#f9fafb",secondary:"#f3f4f6",tertiary:"#e5e7eb",hover:"#e5e7eb"},{primary:"#111827",secondary:"#374151",muted:"#6b7280"},"#d1d5db");D("Ivory",{primary:"#92876d",primaryHover:"#7a6f55",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#fffef7",secondary:"#faf6eb",tertiary:"#f0ead6",hover:"#f0ead6"},{primary:"#2b2517",secondary:"#5c5340",muted:"#9c9280"},"#ddd8c4");D("Rose",{primary:"#e11d48",primaryHover:"#be123c",success:"#16a34a",warning:"#ea580c",error:"#dc2626",info:"#0891b2"},{primary:"#fff1f2",secondary:"#ffe4e6",tertiary:"#fecdd3",hover:"#ffe4e6"},{primary:"#4c0519",secondary:"#881337",muted:"#f43f5e"},"#fda4af");D("Emerald",{primary:"#059669",primaryHover:"#047857",success:"#16a34a",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#ecfdf5",secondary:"#d1fae5",tertiary:"#a7f3d0",hover:"#d1fae5"},{primary:"#064e3b",secondary:"#065f46",muted:"#34d399"},"#6ee7b7");D("Amber",{primary:"#d97706",primaryHover:"#b45309",success:"#16a34a",warning:"#ca8a04",error:"#dc2626",info:"#0284c7"},{primary:"#fffbeb",secondary:"#fef3c7",tertiary:"#fde68a",hover:"#fef3c7"},{primary:"#451a03",secondary:"#78350f",muted:"#f59e0b"},"#fcd34d");D("Violet",{primary:"#7c3aed",primaryHover:"#6d28d9",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#f5f3ff",secondary:"#ede9fe",tertiary:"#ddd6fe",hover:"#ede9fe"},{primary:"#2e1065",secondary:"#4c1d95",muted:"#a78bfa"},"#c4b5fd");D("Teal",{primary:"#0d9488",primaryHover:"#0f766e",success:"#16a34a",warning:"#d97706",error:"#dc2626",info:"#0284c7"},{primary:"#f0fdfa",secondary:"#ccfbf1",tertiary:"#99f6e4",hover:"#ccfbf1"},{primary:"#134e4a",secondary:"#115e59",muted:"#2dd4bf"},"#5eead4");D("Indigo",{primary:"#4f46e5",primaryHover:"#4338ca",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#eef2ff",secondary:"#e0e7ff",tertiary:"#c7d2fe",hover:"#e0e7ff"},{primary:"#1e1b4b",secondary:"#312e81",muted:"#818cf8"},"#a5b4fc");D("Cyan",{primary:"#0891b2",primaryHover:"#0e7490",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#0284c7"},{primary:"#ecfeff",secondary:"#cffafe",tertiary:"#a5f3fc",hover:"#cffafe"},{primary:"#164e63",secondary:"#155e75",muted:"#22d3ee"},"#67e8f9");D("Lime",{primary:"#65a30d",primaryHover:"#4d7c0f",success:"#16a34a",warning:"#ca8a04",error:"#dc2626",info:"#0891b2"},{primary:"#f7fee7",secondary:"#ecfccb",tertiary:"#d9f99d",hover:"#ecfccb"},{primary:"#1a2e05",secondary:"#365314",muted:"#84cc16"},"#bef264");D("Pink",{primary:"#db2777",primaryHover:"#be185d",success:"#10b981",warning:"#f59e0b",error:"#dc2626",info:"#06b6d4"},{primary:"#fdf2f8",secondary:"#fce7f3",tertiary:"#fbcfe8",hover:"#fce7f3"},{primary:"#500724",secondary:"#831843",muted:"#f472b6"},"#f9a8d4");D("Orange",{primary:"#ea580c",primaryHover:"#c2410c",success:"#16a34a",warning:"#ca8a04",error:"#dc2626",info:"#0891b2"},{primary:"#fff7ed",secondary:"#ffedd5",tertiary:"#fed7aa",hover:"#ffedd5"},{primary:"#431407",secondary:"#7c2d12",muted:"#fb923c"},"#fdba74");D("Fuchsia",{primary:"#c026d3",primaryHover:"#a21caf",success:"#10b981",warning:"#eab308",error:"#ef4444",info:"#06b6d4"},{primary:"#fdf4ff",secondary:"#fae8ff",tertiary:"#f5d0fe",hover:"#fae8ff"},{primary:"#4a044e",secondary:"#701a75",muted:"#d946ef"},"#e879f9");D("Sky",{primary:"#0284c7",primaryHover:"#0369a1",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#f0f9ff",secondary:"#e0f2fe",tertiary:"#bae6fd",hover:"#e0f2fe"},{primary:"#0c4a6e",secondary:"#075985",muted:"#38bdf8"},"#7dd3fc");D("Ruby",{primary:"#be123c",primaryHover:"#9f1239",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0284c7"},{primary:"#fff1f2",secondary:"#ffe4e6",tertiary:"#fecdd3",hover:"#ffe4e6"},{primary:"#4c0519",secondary:"#881337",muted:"#fb7185"},"#fda4af");D("Coral",{primary:"#f97316",primaryHover:"#ea580c",success:"#10b981",warning:"#eab308",error:"#ef4444",info:"#06b6d4"},{primary:"#fff7ed",secondary:"#ffedd5",tertiary:"#fed7aa",hover:"#ffedd5"},{primary:"#431407",secondary:"#9a3412",muted:"#fb923c"},"#fdba74");Y("Midnight",{primary:"#818cf8",primaryHover:"#6366f1",success:"#34d399",warning:"#fbbf24",error:"#f87171",info:"#22d3ee"},{primary:"#020617",secondary:"#0f172a",tertiary:"#1e293b",hover:"#1e293b"},{primary:"#f1f5f9",secondary:"#94a3b8",muted:"#475569"},"#1e293b");Y("Obsidian",{primary:"#a78bfa",primaryHover:"#8b5cf6",success:"#4ade80",warning:"#facc15",error:"#fb7185",info:"#38bdf8"},{primary:"#09090b",secondary:"#18181b",tertiary:"#27272a",hover:"#27272a"},{primary:"#fafafa",secondary:"#a1a1aa",muted:"#52525b"},"#3f3f46");Y("Eclipse",{primary:"#c084fc",primaryHover:"#a855f7",success:"#34d399",warning:"#fbbf24",error:"#f87171",info:"#67e8f9"},{primary:"#0c0a1d",secondary:"#1a1533",tertiary:"#2a2248",hover:"#2a2248"},{primary:"#f5f3ff",secondary:"#a78bfa",muted:"#6d5eac"},"#3b3266");Y("Onyx",{primary:"#60a5fa",primaryHover:"#3b82f6",success:"#4ade80",warning:"#fbbf24",error:"#f87171",info:"#22d3ee"},{primary:"#000000",secondary:"#0a0a0a",tertiary:"#171717",hover:"#171717"},{primary:"#ffffff",secondary:"#a3a3a3",muted:"#525252"},"#262626");Y("Carbon",{primary:"#38bdf8",primaryHover:"#0ea5e9",success:"#4ade80",warning:"#facc15",error:"#f87171",info:"#67e8f9"},{primary:"#161616",secondary:"#262626",tertiary:"#393939",hover:"#393939"},{primary:"#f4f4f4",secondary:"#c6c6c6",muted:"#6f6f6f"},"#525252");Y("Cosmos",{primary:"#6366f1",primaryHover:"#4f46e5",success:"#34d399",warning:"#fbbf24",error:"#f87171",info:"#22d3ee"},{primary:"#030712",secondary:"#111827",tertiary:"#1f2937",hover:"#1f2937"},{primary:"#e5e7eb",secondary:"#9ca3af",muted:"#4b5563"},"#374151");Y("Nebula",{primary:"#e879f9",primaryHover:"#d946ef",success:"#4ade80",warning:"#fbbf24",error:"#fb7185",info:"#67e8f9"},{primary:"#0d0117",secondary:"#1a0533",tertiary:"#2d0a52",hover:"#2d0a52"},{primary:"#fae8ff",secondary:"#d8b4fe",muted:"#7c3aed"},"#581c87");Y("Abyss",{primary:"#22d3ee",primaryHover:"#06b6d4",success:"#34d399",warning:"#fbbf24",error:"#f87171",info:"#38bdf8"},{primary:"#001219",secondary:"#002a3a",tertiary:"#003e54",hover:"#003e54"},{primary:"#e0f2fe",secondary:"#7dd3fc",muted:"#0369a1"},"#075985");Y("Shadow",{primary:"#a3a3a3",primaryHover:"#737373",success:"#4ade80",warning:"#facc15",error:"#f87171",info:"#38bdf8"},{primary:"#171717",secondary:"#1f1f1f",tertiary:"#2a2a2a",hover:"#2a2a2a"},{primary:"#e5e5e5",secondary:"#a3a3a3",muted:"#525252"},"#404040");Y("Emerald Dark",{primary:"#34d399",primaryHover:"#10b981",success:"#4ade80",warning:"#fbbf24",error:"#f87171",info:"#22d3ee"},{primary:"#022c22",secondary:"#064e3b",tertiary:"#065f46",hover:"#065f46"},{primary:"#ecfdf5",secondary:"#6ee7b7",muted:"#047857"},"#047857");D("Forest",{primary:"#166534",primaryHover:"#14532d",success:"#22c55e",warning:"#ca8a04",error:"#dc2626",info:"#0891b2"},{primary:"#f0fdf4",secondary:"#dcfce7",tertiary:"#bbf7d0",hover:"#dcfce7"},{primary:"#052e16",secondary:"#166534",muted:"#4ade80"},"#86efac");D("Ocean",{primary:"#0369a1",primaryHover:"#075985",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0284c7"},{primary:"#f0f9ff",secondary:"#e0f2fe",tertiary:"#bae6fd",hover:"#e0f2fe"},{primary:"#0c4a6e",secondary:"#0369a1",muted:"#38bdf8"},"#7dd3fc");D("Desert",{primary:"#b45309",primaryHover:"#92400e",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#fefce8",secondary:"#fef9c3",tertiary:"#fef08a",hover:"#fef9c3"},{primary:"#422006",secondary:"#713f12",muted:"#ca8a04"},"#fde047");D("Sunset",{primary:"#ea580c",primaryHover:"#c2410c",success:"#16a34a",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#fff7ed",secondary:"#ffedd5",tertiary:"#fed7aa",hover:"#ffedd5"},{primary:"#431407",secondary:"#9a3412",muted:"#f97316"},"#fdba74");D("Aurora",{primary:"#0d9488",primaryHover:"#0f766e",success:"#22c55e",warning:"#eab308",error:"#ef4444",info:"#06b6d4"},{primary:"#f0fdfa",secondary:"#ccfbf1",tertiary:"#99f6e4",hover:"#ccfbf1"},{primary:"#134e4a",secondary:"#115e59",muted:"#2dd4bf"},"#5eead4");D("Lavender",{primary:"#7e22ce",primaryHover:"#6b21a8",success:"#16a34a",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#faf5ff",secondary:"#f3e8ff",tertiary:"#e9d5ff",hover:"#f3e8ff"},{primary:"#3b0764",secondary:"#581c87",muted:"#a855f7"},"#d8b4fe");D("Autumn",{primary:"#c2410c",primaryHover:"#9a3412",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#fef2f2",secondary:"#fee2e2",tertiary:"#fecaca",hover:"#fee2e2"},{primary:"#450a0a",secondary:"#7f1d1d",muted:"#f87171"},"#fca5a5");D("Spring",{primary:"#16a34a",primaryHover:"#15803d",success:"#22c55e",warning:"#eab308",error:"#ef4444",info:"#06b6d4"},{primary:"#f0fdf4",secondary:"#dcfce7",tertiary:"#bbf7d0",hover:"#dcfce7"},{primary:"#14532d",secondary:"#166534",muted:"#4ade80"},"#86efac");D("Arctic",{primary:"#0ea5e9",primaryHover:"#0284c7",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#f0f9ff",secondary:"#e0f2fe",tertiary:"#bae6fd",hover:"#e0f2fe"},{primary:"#0c4a6e",secondary:"#0369a1",muted:"#7dd3fc"},"#bae6fd");D("Tropical",{primary:"#0d9488",primaryHover:"#0f766e",success:"#16a34a",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#ecfdf5",secondary:"#d1fae5",tertiary:"#a7f3d0",hover:"#d1fae5"},{primary:"#064e3b",secondary:"#065f46",muted:"#6ee7b7"},"#a7f3d0");D("Pastel Rose",{primary:"#f472b6",primaryHover:"#ec4899",success:"#4ade80",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#fdf2f8",secondary:"#fce7f3",tertiary:"#fbcfe8",hover:"#fce7f3"},{primary:"#831843",secondary:"#9d174d",muted:"#f9a8d4"},"#f9a8d4");D("Pastel Sky",{primary:"#38bdf8",primaryHover:"#0ea5e9",success:"#4ade80",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#f0f9ff",secondary:"#e0f2fe",tertiary:"#bae6fd",hover:"#e0f2fe"},{primary:"#075985",secondary:"#0369a1",muted:"#7dd3fc"},"#bae6fd");D("Pastel Mint",{primary:"#34d399",primaryHover:"#10b981",success:"#4ade80",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#ecfdf5",secondary:"#d1fae5",tertiary:"#a7f3d0",hover:"#d1fae5"},{primary:"#065f46",secondary:"#047857",muted:"#6ee7b7"},"#a7f3d0");D("Pastel Peach",{primary:"#fb923c",primaryHover:"#f97316",success:"#4ade80",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#fff7ed",secondary:"#ffedd5",tertiary:"#fed7aa",hover:"#ffedd5"},{primary:"#7c2d12",secondary:"#9a3412",muted:"#fdba74"},"#fed7aa");D("Pastel Lavender",{primary:"#a78bfa",primaryHover:"#8b5cf6",success:"#4ade80",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#f5f3ff",secondary:"#ede9fe",tertiary:"#ddd6fe",hover:"#ede9fe"},{primary:"#4c1d95",secondary:"#5b21b6",muted:"#c4b5fd"},"#ddd6fe");D("Pastel Lemon",{primary:"#facc15",primaryHover:"#eab308",success:"#4ade80",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#fefce8",secondary:"#fef9c3",tertiary:"#fef08a",hover:"#fef9c3"},{primary:"#713f12",secondary:"#854d0e",muted:"#fde047"},"#fef08a");D("Pastel Sage",{primary:"#86efac",primaryHover:"#4ade80",success:"#22c55e",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#f0fdf4",secondary:"#dcfce7",tertiary:"#bbf7d0",hover:"#dcfce7"},{primary:"#166534",secondary:"#15803d",muted:"#86efac"},"#bbf7d0");D("Pastel Coral",{primary:"#fb7185",primaryHover:"#f43f5e",success:"#4ade80",warning:"#fcd34d",error:"#ef4444",info:"#67e8f9"},{primary:"#fff1f2",secondary:"#ffe4e6",tertiary:"#fecdd3",hover:"#ffe4e6"},{primary:"#881337",secondary:"#9f1239",muted:"#fda4af"},"#fecdd3");D("Banking",{primary:"#1e3a5f",primaryHover:"#152c4a",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#f8fafc",secondary:"#f1f5f9",tertiary:"#e2e8f0",hover:"#e2e8f0"},{primary:"#0f172a",secondary:"#334155",muted:"#94a3b8"},"#cbd5e1");D("Healthcare",{primary:"#0891b2",primaryHover:"#0e7490",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0284c7"},{primary:"#f0fdfa",secondary:"#e0f7fa",tertiary:"#b2ebf2",hover:"#e0f7fa"},{primary:"#134e4a",secondary:"#1a6b6a",muted:"#80cbc4"},"#b2dfdb");D("Legal",{primary:"#1e293b",primaryHover:"#0f172a",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0284c7"},{primary:"#fafaf9",secondary:"#f5f5f4",tertiary:"#e7e5e4",hover:"#e7e5e4"},{primary:"#0f172a",secondary:"#44403c",muted:"#a8a29e"},"#d6d3d1");D("Tech Startup",{primary:"#7c3aed",primaryHover:"#6d28d9",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#faf5ff",secondary:"#f3e8ff",tertiary:"#e9d5ff",hover:"#f3e8ff"},{primary:"#1e1b4b",secondary:"#4c1d95",muted:"#a78bfa"},"#c4b5fd");D("Enterprise",{primary:"#1e40af",primaryHover:"#1e3a8a",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#eff6ff",secondary:"#dbeafe",tertiary:"#bfdbfe",hover:"#dbeafe"},{primary:"#1e3a5f",secondary:"#1e40af",muted:"#60a5fa"},"#93c5fd");D("Government",{primary:"#1d4ed8",primaryHover:"#1e40af",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#f8fafc",secondary:"#f1f5f9",tertiary:"#e2e8f0",hover:"#e2e8f0"},{primary:"#0f172a",secondary:"#1e293b",muted:"#64748b"},"#cbd5e1");D("Education",{primary:"#059669",primaryHover:"#047857",success:"#16a34a",warning:"#f59e0b",error:"#ef4444",info:"#0891b2"},{primary:"#f0fdf9",secondary:"#d1fae5",tertiary:"#a7f3d0",hover:"#d1fae5"},{primary:"#064e3b",secondary:"#065f46",muted:"#6ee7b7"},"#a7f3d0");D("Real Estate",{primary:"#92400e",primaryHover:"#78350f",success:"#059669",warning:"#b45309",error:"#dc2626",info:"#0891b2"},{primary:"#fffbeb",secondary:"#fef3c7",tertiary:"#fde68a",hover:"#fef3c7"},{primary:"#422006",secondary:"#713f12",muted:"#d97706"},"#fcd34d");D("Nord",{primary:"#5e81ac",primaryHover:"#4c6b90",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",info:"#88c0d0"},{primary:"#eceff4",secondary:"#e5e9f0",tertiary:"#d8dee9",hover:"#d8dee9"},{primary:"#2e3440",secondary:"#3b4252",muted:"#4c566a"},"#d8dee9");Y("Dracula",{primary:"#bd93f9",primaryHover:"#9d79d9",success:"#50fa7b",warning:"#f1fa8c",error:"#ff5555",info:"#8be9fd"},{primary:"#282a36",secondary:"#343746",tertiary:"#44475a",hover:"#44475a"},{primary:"#f8f8f2",secondary:"#c0c0c0",muted:"#6272a4"},"#44475a");D("Solarized Light",{primary:"#268bd2",primaryHover:"#1a6da0",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#2aa198"},{primary:"#fdf6e3",secondary:"#eee8d5",tertiary:"#e0dbc7",hover:"#eee8d5"},{primary:"#073642",secondary:"#586e75",muted:"#93a1a1"},"#eee8d5");Y("Solarized Dark",{primary:"#268bd2",primaryHover:"#3d98db",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#2aa198"},{primary:"#002b36",secondary:"#073642",tertiary:"#0a4858",hover:"#073642"},{primary:"#eee8d5",secondary:"#93a1a1",muted:"#586e75"},"#073642");Y("Monokai",{primary:"#66d9ef",primaryHover:"#45c0d6",success:"#a6e22e",warning:"#e6db74",error:"#f92672",info:"#66d9ef"},{primary:"#272822",secondary:"#34352e",tertiary:"#3e3d32",hover:"#3e3d32"},{primary:"#f8f8f2",secondary:"#cfcfc2",muted:"#75715e"},"#3e3d32");Y("One Dark",{primary:"#61afef",primaryHover:"#4b9ee0",success:"#98c379",warning:"#e5c07b",error:"#e06c75",info:"#56b6c2"},{primary:"#282c34",secondary:"#2c313a",tertiary:"#353b45",hover:"#353b45"},{primary:"#abb2bf",secondary:"#828997",muted:"#545862"},"#3e4452");Y("Synthwave",{primary:"#ff7edb",primaryHover:"#e660c2",success:"#72f1b8",warning:"#fede5d",error:"#fe4450",info:"#36f9f6"},{primary:"#241b2f",secondary:"#2d2140",tertiary:"#362a50",hover:"#362a50"},{primary:"#f0e4fc",secondary:"#b4a0cc",muted:"#6c5c84"},"#4a3866");D("Vaporwave",{primary:"#ff71ce",primaryHover:"#e655b5",success:"#78dcca",warning:"#ffb86c",error:"#ff5555",info:"#76e8fc"},{primary:"#fce4f7",secondary:"#e8d0f4",tertiary:"#d4bcf0",hover:"#e8d0f4"},{primary:"#4a1a4e",secondary:"#7b3f7d",muted:"#c080c0"},"#d8a8e8");Y("Terminal Green",{primary:"#00ff41",primaryHover:"#00cc34",success:"#00ff41",warning:"#ffff00",error:"#ff0000",info:"#00ffff"},{primary:"#0a0a0a",secondary:"#0d1a0d",tertiary:"#1a2e1a",hover:"#1a2e1a"},{primary:"#00ff41",secondary:"#00cc33",muted:"#008822"},"#003300");D("Sepia",{primary:"#8b6914",primaryHover:"#704f10",success:"#6b8e23",warning:"#cd853f",error:"#b22222",info:"#5f9ea0"},{primary:"#faf0e6",secondary:"#f5e6d3",tertiary:"#eddcc7",hover:"#f5e6d3"},{primary:"#3e2723",secondary:"#5d4037",muted:"#a1887f"},"#d7ccc8");D("Vintage",{primary:"#8d6e63",primaryHover:"#6d4c41",success:"#66bb6a",warning:"#ffb300",error:"#e53935",info:"#29b6f6"},{primary:"#efebe9",secondary:"#d7ccc8",tertiary:"#bcaaa4",hover:"#d7ccc8"},{primary:"#3e2723",secondary:"#5d4037",muted:"#a1887f"},"#bcaaa4");Y("Cyberpunk",{primary:"#00f0ff",primaryHover:"#00c8d4",success:"#39ff14",warning:"#ffff00",error:"#ff003c",info:"#bf00ff"},{primary:"#0a0e17",secondary:"#131824",tertiary:"#1c2333",hover:"#1c2333"},{primary:"#e0fbfc",secondary:"#80d4dd",muted:"#3a6b72"},"#1c3a44");Y("Neon",{primary:"#ff00ff",primaryHover:"#cc00cc",success:"#00ff00",warning:"#ffff00",error:"#ff0000",info:"#00ffff"},{primary:"#0d0d0d",secondary:"#1a1a1a",tertiary:"#262626",hover:"#262626"},{primary:"#ffffff",secondary:"#cccccc",muted:"#666666"},"#333333");Y("Retrowave",{primary:"#f77fbe",primaryHover:"#e462a3",success:"#72f1b8",warning:"#ffe261",error:"#ff4444",info:"#79e8fb"},{primary:"#1b0a2e",secondary:"#261440",tertiary:"#321e52",hover:"#321e52"},{primary:"#ffe6f7",secondary:"#c9a0c9",muted:"#6b4c7a"},"#4a2d66");D("Christmas",{primary:"#c41e3a",primaryHover:"#a01830",success:"#228b22",warning:"#ffd700",error:"#dc2626",info:"#0891b2"},{primary:"#fef2f2",secondary:"#fde8e8",tertiary:"#f8d0d0",hover:"#fde8e8"},{primary:"#3b0a0a",secondary:"#7f1d1d",muted:"#dc6868"},"#e8a0a0");Y("Halloween",{primary:"#ff6600",primaryHover:"#e05500",success:"#4ade80",warning:"#fbbf24",error:"#ff0000",info:"#9333ea"},{primary:"#1a0a00",secondary:"#2d1500",tertiary:"#402000",hover:"#402000"},{primary:"#ffedd5",secondary:"#fdba74",muted:"#9a5c28"},"#5c3400");D("Valentine",{primary:"#e11d48",primaryHover:"#be123c",success:"#10b981",warning:"#f59e0b",error:"#dc2626",info:"#ec4899"},{primary:"#fff1f2",secondary:"#ffe4e6",tertiary:"#fecdd3",hover:"#ffe4e6"},{primary:"#4c0519",secondary:"#881337",muted:"#f9a8d4"},"#fda4af");D("Easter",{primary:"#a78bfa",primaryHover:"#8b5cf6",success:"#4ade80",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#fef9ff",secondary:"#f3e8ff",tertiary:"#e8d5ff",hover:"#f3e8ff"},{primary:"#581c87",secondary:"#6d28d9",muted:"#c4b5fd"},"#ddd6fe");D("Summer Beach",{primary:"#0ea5e9",primaryHover:"#0284c7",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#fffbeb",secondary:"#fef3c7",tertiary:"#fde68a",hover:"#fef3c7"},{primary:"#0c4a6e",secondary:"#0369a1",muted:"#7dd3fc"},"#fcd34d");D("Winter Frost",{primary:"#3b82f6",primaryHover:"#2563eb",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#f0f9ff",secondary:"#e0f2fe",tertiary:"#bae6fd",hover:"#e0f2fe"},{primary:"#1e3a5f",secondary:"#1e40af",muted:"#93c5fd"},"#bfdbfe");D("Cherry Blossom",{primary:"#ec4899",primaryHover:"#db2777",success:"#10b981",warning:"#f59e0b",error:"#ef4444",info:"#06b6d4"},{primary:"#fdf2f8",secondary:"#fce7f3",tertiary:"#fbcfe8",hover:"#fce7f3"},{primary:"#831843",secondary:"#9d174d",muted:"#f9a8d4"},"#fbcfe8");D("Harvest",{primary:"#b45309",primaryHover:"#92400e",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#fffbeb",secondary:"#fef3c7",tertiary:"#fde68a",hover:"#fef3c7"},{primary:"#451a03",secondary:"#78350f",muted:"#d97706"},"#fcd34d");D("Japanese Zen",{primary:"#6b7280",primaryHover:"#4b5563",success:"#6b8e23",warning:"#d4a017",error:"#c0392b",info:"#5f9ea0"},{primary:"#faf9f6",secondary:"#f0ece3",tertiary:"#e6e0d4",hover:"#f0ece3"},{primary:"#2c2c2c",secondary:"#5c5c5c",muted:"#a0998a"},"#d5cec0");D("Moroccan",{primary:"#c2410c",primaryHover:"#9a3412",success:"#15803d",warning:"#ca8a04",error:"#b91c1c",info:"#0e7490"},{primary:"#fffbf0",secondary:"#fef3e0",tertiary:"#fde6c4",hover:"#fef3e0"},{primary:"#3a1a00",secondary:"#7c2d12",muted:"#d97706"},"#f5d0a0");D("Scandinavian",{primary:"#4b5563",primaryHover:"#374151",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#ffffff",secondary:"#f9fafb",tertiary:"#f3f4f6",hover:"#f3f4f6"},{primary:"#111827",secondary:"#374151",muted:"#9ca3af"},"#e5e7eb");D("Mediterranean",{primary:"#1e40af",primaryHover:"#1e3a8a",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#eff6ff",secondary:"#dbeafe",tertiary:"#bfdbfe",hover:"#dbeafe"},{primary:"#1e3a5f",secondary:"#2563eb",muted:"#93c5fd"},"#bfdbfe");D("Chinese New Year",{primary:"#dc2626",primaryHover:"#b91c1c",success:"#16a34a",warning:"#d4a017",error:"#ef4444",info:"#0891b2"},{primary:"#fef2f2",secondary:"#fee2e2",tertiary:"#fecaca",hover:"#fee2e2"},{primary:"#450a0a",secondary:"#991b1b",muted:"#f87171"},"#fca5a5");D("Indian Festive",{primary:"#d97706",primaryHover:"#b45309",success:"#16a34a",warning:"#ca8a04",error:"#dc2626",info:"#7c3aed"},{primary:"#fffbeb",secondary:"#fef3c7",tertiary:"#fde68a",hover:"#fef3c7"},{primary:"#451a03",secondary:"#92400e",muted:"#f59e0b"},"#fcd34d");D("Brazilian Carnival",{primary:"#16a34a",primaryHover:"#15803d",success:"#22c55e",warning:"#facc15",error:"#ef4444",info:"#0ea5e9"},{primary:"#f0fdf4",secondary:"#dcfce7",tertiary:"#bbf7d0",hover:"#dcfce7"},{primary:"#052e16",secondary:"#166534",muted:"#4ade80"},"#86efac");D("African Earth",{primary:"#92400e",primaryHover:"#78350f",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#faf5f0",secondary:"#f0e6d6",tertiary:"#e6d5bb",hover:"#f0e6d6"},{primary:"#2b1a0e",secondary:"#5c3d1e",muted:"#a08060"},"#d4b896");Y("High Contrast Dark",{primary:"#ffff00",primaryHover:"#cccc00",success:"#00ff00",warning:"#ff8c00",error:"#ff0000",info:"#00ffff"},{primary:"#000000",secondary:"#1a1a1a",tertiary:"#333333",hover:"#333333"},{primary:"#ffffff",secondary:"#ffffff",muted:"#cccccc"},"#ffffff");D("Monochrome",{primary:"#404040",primaryHover:"#262626",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#fafafa",secondary:"#f0f0f0",tertiary:"#e0e0e0",hover:"#e0e0e0"},{primary:"#1a1a1a",secondary:"#404040",muted:"#808080"},"#c0c0c0");D("Enhanced Contrast",{primary:"#0050b3",primaryHover:"#003d8c",success:"#006400",warning:"#cc7000",error:"#cc0000",info:"#006680"},{primary:"#ffffff",secondary:"#f5f5f5",tertiary:"#ebebeb",hover:"#ebebeb"},{primary:"#000000",secondary:"#1a1a1a",muted:"#595959"},"#8c8c8c");D("Minimalist",{primary:"#18181b",primaryHover:"#27272a",success:"#22c55e",warning:"#eab308",error:"#ef4444",info:"#3b82f6"},{primary:"#ffffff",secondary:"#fafafa",tertiary:"#f5f5f5",hover:"#f5f5f5"},{primary:"#0a0a0a",secondary:"#404040",muted:"#a3a3a3"},"#e5e5e5");Y("Warm Dark",{primary:"#f59e0b",primaryHover:"#d97706",success:"#10b981",warning:"#fbbf24",error:"#f87171",info:"#38bdf8"},{primary:"#1c1917",secondary:"#292524",tertiary:"#44403c",hover:"#44403c"},{primary:"#fafaf9",secondary:"#d6d3d1",muted:"#78716c"},"#57534e");Y("Soft Dark",{primary:"#a78bfa",primaryHover:"#8b5cf6",success:"#34d399",warning:"#fcd34d",error:"#fb7185",info:"#67e8f9"},{primary:"#1e1e2e",secondary:"#262637",tertiary:"#313147",hover:"#313147"},{primary:"#e8e8f0",secondary:"#a0a0b8",muted:"#5c5c74"},"#3e3e58");D("Coffee",{primary:"#6f4e37",primaryHover:"#5c3d28",success:"#4d7c0f",warning:"#a16207",error:"#b91c1c",info:"#0e7490"},{primary:"#faf6f1",secondary:"#f0e8dc",tertiary:"#e6d8c6",hover:"#f0e8dc"},{primary:"#2c1a0e",secondary:"#5c3d28",muted:"#a08868"},"#d4c4a8");D("Wine",{primary:"#7f1d1d",primaryHover:"#641717",success:"#059669",warning:"#d97706",error:"#dc2626",info:"#0891b2"},{primary:"#fef2f2",secondary:"#fde8e8",tertiary:"#f8d0d0",hover:"#fde8e8"},{primary:"#3b0a0a",secondary:"#7f1d1d",muted:"#dc6868"},"#e8a0a0");o.createContext(null);o.createContext(null);function sr(i,a){if(i!=="auto"||!a)return i==="auto"?"top":i;const r=a.top,t=window.innerHeight-a.bottom,n=a.left,s=window.innerWidth-a.right,c=Math.max(r,t,n,s);return c===r?"top":c===t?"bottom":c===s?"right":"left"}function cr(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 ze=o.forwardRef(({context:i,position:a="auto",debounceMs:r=500,showOnHover:t=!1,triggerIcon:n,className:s,style:c},d)=>{var w;const m=ee(),[f,g]=o.useState(!1),[y,k]=o.useState(!1),M=o.useRef(null),T=o.useRef(null),j=Q(i,{debounceMs:r,disabled:!y});o.useEffect(()=>{if(!f)return;const p=x=>{var u,h;const v=x.target;(u=M.current)!=null&&u.contains(v)||(h=T.current)!=null&&h.contains(v)||(g(!1),k(!1))};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[f]),o.useEffect(()=>{if(!f)return;const p=x=>{x.key==="Escape"&&(g(!1),k(!1),j.abort())};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[f,j]);const A=o.useCallback(p=>{if(p.stopPropagation(),t)return;const x=!f;g(x),k(x)},[f,t]),_=o.useCallback(()=>{t&&(g(!0),k(!0))},[t]),l=o.useCallback(()=>{t&&(g(!1),k(!1))},[t]);if(!m||!m.enabled)return null;const N=sr(a,((w=M.current)==null?void 0:w.getBoundingClientRect())??null);return e.jsxs("span",{ref:d,className:s,style:{position:"relative",display:"inline-flex",...c},onMouseEnter:_,onMouseLeave:l,children:[e.jsx("button",{ref:M,type:"button",onClick:A,"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($,{name:"wand",size:16})}),f&&e.jsxs("div",{ref:T,role:"tooltip",className:"ntd-ai-popover",style:cr(N),children:[j.loading&&!j.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..."})]}),j.text&&e.jsxs("div",{className:"ntd-ai-content",children:[j.text,j.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"}})]}),j.error&&e.jsx("div",{className:"ntd-ai-error",style:{color:"var(--ntd-ai-error, #f38ba8)"},children:j.error}),j.text&&!j.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:()=>j.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($,{name:"refresh",size:12})," Refresh"]}),e.jsxs("button",{type:"button",onClick:()=>{var p;(p=navigator.clipboard)==null||p.writeText(j.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($,{name:"copy",size:12})," Copy"]})]})]})]})});ze.displayName="NiceAIHintBubble";function Te(i,a,r){return{fieldLabel:i,fieldType:"text",fieldValue:a,validationRules:{...(r==null?void 0:r.maxLength)!=null?{maxLength:r.maxLength}:{},...r!=null&&r.pattern?{pattern:r.pattern}:{}},customPrompt:r!=null&&r.placeholder?`Placeholder: "${r.placeholder}". Suggest content or correct grammar.`:"Suggest content, correct grammar, or auto-complete the text."}}function Ae(i,a,r){return{fieldLabel:i,fieldType:"number",fieldValue:a,validationRules:{...(r==null?void 0:r.min)!=null?{min:r.min}:{},...(r==null?void 0:r.max)!=null?{max:r.max}:{},...(r==null?void 0:r.step)!=null?{step:r.step}:{}},customPrompt:r!=null&&r.unit?`Unit: ${r.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(i,a,r){return{fieldLabel:i,fieldType:r!=null&&r.multiple?"multi-select":"select",fieldValue:a,schema:r!=null&&r.options?{availableOptions:r.options.slice(0,20).map(t=>t.label)}:{},customPrompt:"Suggest the most likely selection. Explain why this option is recommended."}}function Le(i,a,r){const t=a instanceof Date?a.toISOString().split("T")[0]:a;return{fieldLabel:i,fieldType:"date",fieldValue:t,validationRules:{...r!=null&&r.min?{min:r.min}:{},...r!=null&&r.max?{max:r.max}:{},...r!=null&&r.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,r){return{fieldLabel:i,fieldType:"color",fieldValue:a,schema:r!=null&&r.palette?{currentPalette:r.palette}:{},customPrompt:r!=null&&r.industry?`Industry: ${r.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 or(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 lr(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 ta(i,a){return{fieldLabel:"Form auto-fill",fieldType:"form",schema:{fields:a},customPrompt:`User description: "${i}"
31
- Parse this description and return suggested values for each field as JSON: { ${a.map(r=>`"${r.label}": "value"`).join(", ")} }`}}function na(i,a,r,t,n){return{fieldLabel:i,fieldType:a,fieldValue:r,validationRules:n==null?void 0:n.rules,customPrompt:`Current validation error: "${t}". 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 dr(i,a,r){const t=o.useMemo(()=>Te(i,a,r),[i,a,r==null?void 0:r.placeholder,r==null?void 0:r.maxLength,r==null?void 0:r.pattern]);return Q(t,r)}function ur(i,a,r){const t=o.useMemo(()=>Ae(i,a,r),[i,a,r==null?void 0:r.min,r==null?void 0:r.max,r==null?void 0:r.step,r==null?void 0:r.unit]);return Q(t,r)}function pr(i,a,r){const t=o.useMemo(()=>Re(i,a,r),[i,a,r==null?void 0:r.multiple]);return Q(t,r)}function mr(i,a,r){const t=o.useMemo(()=>Le(i,a,r),[i,a,r==null?void 0:r.min,r==null?void 0:r.max,r==null?void 0:r.disableWeekends]);return Q(t,r)}function fr(i,a,r){const t=o.useMemo(()=>Pe(i,a,r),[i,a,r==null?void 0:r.industry]);return Q(t,r)}function hr(i,a,r,t,n){const s=o.useMemo(()=>t?na(i,a,r,t,n):{fieldLabel:i,fieldType:a},[i,a,r,t]);return Q(s,{...n,disabled:!t||(n==null?void 0:n.disabled)})}function gr(i,a,r){const t=o.useMemo(()=>i?ta(i,a):{fieldLabel:"Form"},[i,a]);return Q(t,{...r,disabled:!i||(r==null?void 0:r.disabled)})}function sa(i,a,r){const n=(a==null?void 0:a.split(`
32
- `))??[],s=(r==null?void 0:r.cursorLine)!=null?n.slice(Math.max(0,r.cursorLine-8),r.cursorLine+3).join(`
33
- `):n.slice(0,8*2).join(`
34
- `);return{fieldLabel:`Code editor (${i})`,fieldType:"code-editor",fieldValue:s||a,schema:{language:i,...r!=null&&r.framework?{framework:r.framework}:{},...(r==null?void 0:r.cursorLine)!=null?{cursorLine:r.cursorLine,cursorCol:r.cursorCol}:{}},customPrompt:`Language: ${i}${r!=null&&r.framework?`, framework: ${r.framework}`:""}.
35
- Provide a concise inline completion or improvement hint for the code near the cursor. Limit response to ${(r==null?void 0:r.maxSuggestLines)??5} lines of code. If unsure, suggest the most idiomatic approach for this language/framework.`}}function ca(i,a,r){var s;const t=(r==null?void 0:r.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:t,...(s=r==null?void 0:r.targetKeywords)!=null&&s.length?{targetKeywords:r.targetKeywords}:{},...r!=null&&r.locale?{locale:r.locale}:{}},customPrompt:n[t]}}function oa(i,a){const r=(a==null?void 0:a.mode)??"tag",t=`"${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: ${t}. Suggest genre tags, mood descriptors and playlist categories. Return as JSON array of strings.`,bpm:`Audio: ${t}. Suggest likely BPM range and musical key based on metadata. Return as JSON: { bpm: number, key: string }.`,mix:`Track: ${t}. 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:r,...(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[r]}}function la(i,a){var s;const r=(a==null?void 0:a.mode)??"material",t=(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: ${t}. Identify budget issues and suggest LOD levels, mesh merging, and texture atlas strategy.`,lighting:`Scene "${i}", target: ${t}. 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:r,...(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[r]}}function da(i,a){const r=(a==null?void 0:a.mode)??"palette",t=(a==null?void 0:a.width)!=null?`${a.width}×${a.height??"?"}px`:"unknown dimensions",n={filter:`Image "${i}" (${t}). 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 ${t}. 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:r,...(a==null?void 0:a.width)!=null?{width:a.width,height:a.height}:{},...a!=null&&a.targetStyle?{targetStyle:a.targetStyle}:{}},customPrompt:n[r]}}function ua(i,a){var r;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}:{},...(r=a==null?void 0:a.availableIcons)!=null&&r.length?{sampleIcons:a.availableIcons.slice(0,30)}:{}},customPrompt:`User query: "${i}"
36
- 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 yr(i,a,r){const t=o.useMemo(()=>sa(i,a,r),[i,a,r==null?void 0:r.cursorLine,r==null?void 0:r.cursorCol,r==null?void 0:r.framework]);return Q(t,r)}function br(i,a,r){const t=o.useMemo(()=>ca(i,a,r),[i,a,r==null?void 0:r.mode,r==null?void 0:r.locale]);return Q(t,r)}function xr(i,a){const r=o.useMemo(()=>oa(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 Q(r,a)}function vr(i,a){const r=o.useMemo(()=>la(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 Q(r,a)}function _r(i,a){const r=o.useMemo(()=>da(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 Q(r,a)}function wr(i,a){const r=o.useMemo(()=>ua(i,a),[i,a==null?void 0:a.limit,a==null?void 0:a.style]);return Q(r,{...a,disabled:!i||(a==null?void 0:a.disabled)})}function pa(i,a){var s;const r=(a==null?void 0:a.mode)??"npc-decision",t=(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 ${t} 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 ${t} 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 ${t} 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 ${t} 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:${r}`,fieldValue:a==null?void 0:a.gameState,customPrompt:n[r],schema:{genre:t,mode:r,btNodes:(s=a==null?void 0:a.btStatus)==null?void 0:s.map(c=>c.node)}}}function jr(i,a){const r=o.useMemo(()=>pa(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 Q(r,a)}function ma(i,a,r){const t=(r==null?void 0:r.mode)??"layout",n=(r==null?void 0:r.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 }] }`},c=i.map(m=>{var f;return{id:m.id,type:m.type,label:(f=m.label)==null?void 0:f.slice(0,30),pos:[Math.round(m.x),Math.round(m.y)]}}),d=a.map(m=>({id:m.id,src:m.source,tgt:m.target}));return{fieldLabel:`Diagram (${n})`,fieldType:`diagram:${t}`,fieldValue:JSON.stringify({nodes:c,edges:d}),schema:{diagramType:n,mode:t,nodeCount:i.length,edgeCount:a.length,containerSize:r==null?void 0:r.containerSize},customPrompt:s[t]}}function kr(i,a,r){const t=o.useMemo(()=>ma(i,a,r),[JSON.stringify(i),JSON.stringify(a),r==null?void 0:r.mode,r==null?void 0:r.diagramType]);return Q(t,{...r,disabled:i.length===0||(r==null?void 0:r.disabled)})}function fa(i,a){const r=(a==null?void 0:a.mode)??"generate",t=(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 ${t} 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 (${t})`,fieldType:`presentation:${r}`,fieldValue:i,schema:{presentationType:t,mode:r,duration:n,slideCount:s,audience:a==null?void 0:a.audience,hasData:(a==null?void 0:a.dataContext)!=null},customPrompt:c[r]}}function Nr(i,a){const r=o.useMemo(()=>fa(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 Q(r,{...a,disabled:!i||(a==null?void 0:a.disabled)})}function ha(i,a){var n;const r=(a==null?void 0:a.mode)??"all",t={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:${r}`,fieldValue:JSON.stringify(i),schema:{mode:r,hasElements:(((n=i.elements)==null?void 0:n.length)??0)>0,layout:i.layout,brandColors:a==null?void 0:a.brandColors},customPrompt:t[r]}}function Cr(i,a){const r=o.useMemo(()=>ha(i,a),[JSON.stringify(i),a==null?void 0:a.mode,JSON.stringify(a==null?void 0:a.brandColors)]);return Q(r,a)}function Mr(i,a,r){const t=o.forwardRef((n,s)=>{const{aiEnabled:c=!0,aiPosition:d="right",aiPrompt:m,aiDebounceMs:f=500,aiShowOnHover:g=!1,aiTriggerIcon:y,...k}=n,M=o.useMemo(()=>{const T=a(k);return m&&(T.customPrompt=m),T},[k,m]);return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(i,{...k,ref:s}),c&&e.jsx(ze,{context:M,position:d,debounceMs:f,showOnHover:g,triggerIcon:y})]})});return t.displayName=r??`withAIHint(${i.displayName??i.name??"Component"})`,t}function Sr(i){return Te(i.label??"Text",i.value,{placeholder:i.placeholder,maxLength:i.maxLength})}function zr(i){return Ae(i.label??"Number",i.value,{min:i.min,max:i.max,step:i.step})}function Tr(i){return Re(i.label??"Select",i.value,{options:i.options,multiple:i.multiple})}function Ar(i){return Le(i.label??"Date",i.value,{min:i.min,max:i.max})}function Rr(i){return Pe(i.label??"Color",i.value)}const ga=o.forwardRef(({menubar:i,toolbar:a,sidebar:r,sidebarWidth:t=220,rightSidebar:n,rightSidebarWidth:s=280,children:c,bottomPanel:d,bottomPanelHeight:m,statusBar:f,height:g="100%",flush:y=!1,className:k,style:M,id:T,"data-testid":j},A)=>{const _=`nice-app-shell__sidebar${y?" nice-app-shell__sidebar--flush":""}`;return e.jsxs("div",{ref:A,id:T,"data-testid":j,className:`nice-app-shell${k?` ${k}`:""}`,style:{height:g,...M},children:[i!=null&&e.jsx("div",{className:`nice-app-shell__menubar${y?" nice-app-shell__chrome--flush":""}`,children:i}),a!=null&&e.jsx("div",{className:`nice-app-shell__toolbar${y?" nice-app-shell__chrome--flush":""}`,children:a}),e.jsxs("div",{className:"nice-app-shell__body",children:[r!=null&&e.jsx("aside",{className:_,style:y?void 0:{width:t},children:r}),e.jsx("main",{className:"nice-app-shell__content",children:c}),n!=null&&e.jsx("aside",{className:`${_} nice-app-shell__sidebar--right`,style:y?void 0:{width:s},children:n})]}),d!=null&&e.jsx("div",{className:`nice-app-shell__bottom${y?" nice-app-shell__bottom--flush":""}`,style:m!=null?{height:m}:void 0,children:d}),f!=null&&e.jsx("div",{className:"nice-app-shell__status",children:f})]})});ga.displayName="NiceAppShell";const Lr={id:crypto.randomUUID(),name:"New ML Project",type:"classification",status:"draft",datasets:[],experiments:[],models:[],createdAt:new Date,updatedAt:new Date},De={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"}]},Be={classification:["accuracy","precision","recall","f1-score","auc-roc"],regression:["mse","rmse","mae","r2"],clustering:["silhouette","calinski-harabasz","davies-bouldin"]},Pr=[{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"}],$r=({project:i,onProjectChange:a,onExperimentRun:r,onModelDeploy:t,className:n="",tutorial:s})=>{var B;const[c,d]=o.useState(i||Lr),[m,f]=o.useState("data"),[g,y]=o.useState(null),[k,M]=o.useState(null),[T,j]=o.useState(null),[A,_]=o.useState(!1),[l,N]=o.useState({algorithm:"",hyperparameters:{},preprocessing:[]}),w=o.useCallback(b=>{const R={...c,...b,updatedAt:new Date};d(R),a==null||a(R)},[c,a]),p=async b=>{for(const R of Array.from(b)){const q={id:crypto.randomUUID(),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 P=(await R.text()).split(`
37
- `),V=P[0].split(",").map(J=>J.trim());q.rowCount=P.length-1,q.columns=V.map(J=>({name:J,type:"text",nullable:!0,unique:0,missing:0})),q.splits=q.splits.map(J=>({...J,rowCount:Math.floor(q.rowCount*J.ratio)}))}w({datasets:[...c.datasets,q]})}},x=b=>{w({datasets:c.datasets.filter(R=>R.id!==b)}),g===b&&y(null)},v=async()=>{if(!l.algorithm||!g)return;const b={id:crypto.randomUUID(),name:`Experiment ${c.experiments.length+1}`,status:"pending",config:l,metrics:[],artifacts:[],logs:[]};if(w({experiments:[...c.experiments,b]}),_(!1),r){w({experiments:c.experiments.map(R=>R.id===b.id?{...R,status:"running",startedAt:new Date}:R)});try{await r(b);const R=(Be[c.type]||Be.classification).map(q=>({name:q,value:Math.random()*.3+.7,split:"validation"}));w({experiments:c.experiments.map(q=>q.id===b.id?{...q,status:"completed",completedAt:new Date,metrics:R}:q)})}catch{w({experiments:c.experiments.map(R=>R.id===b.id?{...R,status:"failed"}:R)})}}},u=b=>{const R=c.experiments.find(U=>U.id===b);if(!R)return;const q={id:crypto.randomUUID(),name:`Model from ${R.name}`,version:"1.0.0",algorithm:R.config.algorithm,experimentId:b,status:"registered",metrics:R.metrics,size:Math.floor(Math.random()*100)*1024*1024,artifacts:[],deployments:[],createdAt:new Date};w({models:[...c.models,q]})},h=async b=>{const R=c.models.find(U=>U.id===b);if(!R||!t)return;const q=await t(R);w({models:c.models.map(U=>U.id===b?{...U,status:"production",deployments:[...U.deployments,q]}:U)})},I=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`,H=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=>w({name:b.target.value}),className:"project-name-input"}),e.jsxs("select",{value:c.type,onChange:b=>w({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"})]})]}),z=e.jsx("div",{className:"header__tabs",children:["data","experiments","models","deploy"].map(b=>e.jsx("button",{className:`tab-button ${m===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:[m==="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&&p(b.target.files),hidden:!0}),e.jsx($,{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($,{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($,{name:"folder",size:16})}),e.jsx("h3",{children:b.name}),e.jsx("button",{className:"remove-button","aria-label":"Remove dataset",onClick:R=>{R.stopPropagation(),x(b.id)},children:e.jsx($,{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:I(b.size)})]}),e.jsx("div",{className:"splits-bar",children:b.splits.map(R=>e.jsx("div",{className:`split split--${R.name}`,style:{width:`${R.ratio*100}%`},title:`${R.name}: ${(R.ratio*100).toFixed(0)}%`},R.name))})]},b.id))}),g&&e.jsx("div",{className:"dataset-details",children:(()=>{const b=c.datasets.find(R=>R.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(R=>e.jsxs("tr",{children:[e.jsx("td",{children:R.name}),e.jsx("td",{children:e.jsxs("select",{value:R.type,onChange:q=>{w({datasets:c.datasets.map(U=>U.id===b.id?{...U,columns:U.columns.map(P=>P.name===R.name?{...P,type:q.target.value}:P)}:U)})},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:R.missing}),e.jsx("td",{children:R.unique})]},R.name))})]})]}):null})()})]}),m==="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:()=>_(!0),disabled:c.datasets.length===0,children:[e.jsx($,{name:"plus",size:14})," New Experiment"]})]}),A&&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:l.algorithm,onChange:b=>N({...l,algorithm:b.target.value}),children:[e.jsx("option",{value:"",children:"Select algorithm..."}),(De[c.type]||De.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:l.targetColumn||"",onChange:b=>N({...l,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:()=>_(!1),children:"Cancel"}),e.jsx("button",{className:"primary-button",onClick:v,disabled:!l.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($,{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 ${k===b.id?"experiment-card--selected":""}`,onClick:()=>M(b.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:b.name}),e.jsx("span",{className:`status-badge ${H(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(R=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:R.name}),e.jsxs("span",{className:"metric-value",children:[(R.value*100).toFixed(1),"%"]})]},R.name))}),b.status==="completed"&&e.jsx("button",{className:"action-button",onClick:R=>{R.stopPropagation(),u(b.id)},children:"Register Model"})]},b.id))})]}),m==="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($,{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 ${T===b.id?"model-card--selected":""}`,onClick:()=>j(b.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:b.name}),e.jsx("span",{className:`status-badge ${H(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: ",I(b.size)]})]}),b.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:b.metrics.slice(0,3).map(R=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:R.name}),e.jsxs("span",{className:"metric-value",children:[(R.value*100).toFixed(1),"%"]})]},R.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:R=>{R.stopPropagation(),h(b.id)},disabled:b.status==="production",children:b.status==="production"?"Deployed":"Deploy"})]})]},b.id))})]}),m==="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($,{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(R=>({model:b,deployment:R}))).map(({model:b,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 ${H(R.status)}`,children:R.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Model: ",b.name]}),e.jsxs("span",{children:["Endpoint: ",R.endpoint]})]}),e.jsxs("div",{className:"resources-info",children:[e.jsxs("span",{children:["CPU: ",R.resources.cpu," cores"]}),e.jsxs("span",{children:["Memory: ",R.resources.memory," GB"]}),e.jsxs("span",{children:["Replicas: ",R.resources.replicas]})]})]},R.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(ir,{steps:ar(s,Pr)})}),e.jsx(ga,{flush:!0,menubar:C,toolbar:z,children:O})]})},Ir={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},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-accent-pink, #d946ef)","var(--nice-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)"],Or=({project:i,onProjectChange:a,onLabelSave:r,onExport:t,className:n=""})=>{var ae;const{t:s}=Ye(),[c,d]=o.useState(i||Ir),[m,f]=o.useState("label"),[g,y]=o.useState(0),[k,M]=o.useState(null),[T,j]=o.useState("select"),[A,_]=o.useState(!1),[l,N]=o.useState(null),[w,p]=o.useState(1),[x,v]=o.useState(!1),[u,h]=o.useState("all"),I=o.useRef(null),H=o.useRef(null),C=c.items[g];o.useEffect(()=>{i&&d(i)},[i]);const z=o.useCallback(S=>{const E={...c,...S};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(F=>F.labels).filter(F=>F.classId===L.id).length}))},d(E),a==null||a(E)},[c,a]),O=()=>{const S={id:crypto.randomUUID(),name:`Class ${c.labelSchema.classes.length+1}`,color:Fe[c.labelSchema.classes.length%Fe.length],shortcut:String(c.labelSchema.classes.length+1)};z({labelSchema:{...c.labelSchema,classes:[...c.labelSchema.classes,S]}})},B=S=>{z({labelSchema:{...c.labelSchema,classes:c.labelSchema.classes.filter(E=>E.id!==S)},items:c.items.map(E=>({...E,labels:E.labels.filter(L=>L.classId!==S)}))})},b=(S,E)=>{z({labelSchema:{...c.labelSchema,classes:c.labelSchema.classes.map(L=>L.id===S?{...L,...E}:L)}})},R=(S,E)=>{if(!C)return;const L={id:crypto.randomUUID(),classId:S,type:c.type==="classification"?"class":c.type==="bounding-box"?"bbox":"class",data:E||{},createdBy:"current-user",createdAt:new Date},F={...C,labels:[...C.labels,L],status:"labeled"};z({items:c.items.map(X=>X.id===C.id?F:X)}),r==null||r(F)},q=S=>{if(!C)return;const E={...C,labels:C.labels.filter(L=>L.id!==S),status:C.labels.length<=1?"pending":"labeled"};z({items:c.items.map(L=>L.id===C.id?E:L)})},U=S=>{var X;if(T!=="bbox"||!k)return;const E=(X=I.current)==null?void 0:X.getBoundingClientRect();if(!E)return;const L=(S.clientX-E.left)/w,F=(S.clientY-E.top)/w;_(!0),N({x:L,y:F,width:0,height:0})},P=S=>{var X;if(!A||!l)return;const E=(X=I.current)==null?void 0:X.getBoundingClientRect();if(!E)return;const L=(S.clientX-E.left)/w,F=(S.clientY-E.top)/w;N({...l,width:L-l.x,height:F-l.y})},V=()=>{!A||!l||!k||(_(!1),Math.abs(l.width)>10&&Math.abs(l.height)>10&&R(k,{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)}),N(null))},J=S=>{const E=u==="all"?c.items:c.items.filter(F=>F.status===u),L=E.findIndex(F=>F.id===(C==null?void 0:C.id));if(S==="prev"&&L>0){const F=E[L-1];y(c.items.findIndex(X=>X.id===F.id))}else if(S==="next"&&L<E.length-1){const F=E[L+1];y(c.items.findIndex(X=>X.id===F.id))}},W=()=>{if(!C)return;const S={...C,status:"approved"};z({items:c.items.map(E=>E.id===C.id?S:E)}),J("next")},G=()=>{if(!C)return;const S={...C,status:"rejected"};z({items:c.items.map(E=>E.id===C.id?S:E)}),J("next")},Z=async S=>{t&&await t(S)};o.useEffect(()=>{const S=E=>{const L=E.key,F=c.labelSchema.classes.find(X=>X.shortcut===L);F&&(c.type==="classification"?(R(F.id),J("next")):M(F.id)),E.key==="ArrowLeft"||E.key==="a"?J("prev"):(E.key==="ArrowRight"||E.key==="d")&&J("next"),E.key==="Enter"?W():E.key==="Backspace"&&G()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[C,c.labelSchema.classes,c.type]);const ie=S=>{switch(S){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:S=>z({name:S.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(S=>e.jsx("button",{className:`tab-button ${m===S?"tab-button--active":""}`,onClick:()=>f(S),children:S.charAt(0).toUpperCase()+S.slice(1)},S))}),e.jsx("button",{className:"shortcuts-button",onClick:()=>v(!x),children:s("dataLabeler.shortcuts","Shortcuts")})]}),e.jsxs("div",{className:"labeler__content",children:[m==="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 ${T==="select"?"tool-button--active":""}`,onClick:()=>j("select"),children:[e.jsx($,{name:"cursor",size:14})," ",s("dataLabeler.select","Select")]}),(c.type==="bounding-box"||c.type==="multi-label")&&e.jsxs("button",{className:`tool-button ${T==="bbox"?"tool-button--active":""}`,onClick:()=>j("bbox"),children:[e.jsx($,{name:"square",size:14})," Box"]}),c.type==="polygon"&&e.jsxs("button",{className:`tool-button ${T==="polygon"?"tool-button--active":""}`,onClick:()=>j("polygon"),children:[e.jsx($,{name:"hexagon",size:14})," ",s("dataLabeler.polygon","Polygon")]})]}),e.jsxs("div",{className:"zoom-group",children:[e.jsx("button",{onClick:()=>p(Math.max(.25,w-.25)),children:"-"}),e.jsxs("span",{children:[Math.round(w*100),"%"]}),e.jsx("button",{onClick:()=>p(Math.min(4,w+.25)),children:"+"})]}),e.jsxs("div",{className:"navigation-group",children:[e.jsxs("button",{onClick:()=>J("prev"),disabled:g===0,children:[e.jsx($,{name:"arrow-left",size:14})," ",s("dataLabeler.prev","Prev")]}),e.jsxs("span",{children:[g+1," / ",c.items.length]}),e.jsxs("button",{onClick:()=>J("next"),disabled:g>=c.items.length-1,children:[s("dataLabeler.next","Next")," ",e.jsx($,{name:"arrow-right",size:14})]})]})]}),e.jsxs("div",{className:"label-workspace",children:[e.jsx("div",{className:"canvas-container",ref:H,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(${w})`}}),e.jsx("canvas",{ref:I,className:"labeling-canvas",onMouseDown:U,onMouseMove:P,onMouseUp:V,onMouseLeave:V,style:{transform:`scale(${w})`,cursor:T==="bbox"?"crosshair":"default"}}),e.jsxs("div",{className:"annotations-overlay",style:{transform:`scale(${w})`},children:[C.labels.filter(S=>S.type==="bbox"&&S.data.x!==void 0).map(S=>{const E=c.labelSchema.classes.find(L=>L.id===S.classId);return e.jsxs("div",{className:"bbox-annotation",style:{left:S.data.x,top:S.data.y,width:S.data.width,height:S.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",onClick:()=>q(S.id),children:"×"})]},S.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:(ae=c.labelSchema.classes.find(S=>S.id===k))==null?void 0:ae.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($,{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(S=>e.jsxs("button",{className:`class-button ${k===S.id?"class-button--active":""}`,style:{borderLeftColor:S.color},onClick:()=>{c.type==="classification"?(R(S.id),J("next")):M(S.id)},children:[e.jsx("span",{className:"class-color",style:{backgroundColor:S.color}}),e.jsx("span",{className:"class-name",children:S.name}),S.shortcut&&e.jsx("span",{className:"class-shortcut",children:S.shortcut})]},S.id))}),C&&C.labels.length>0&&e.jsxs("div",{className:"current-labels",children:[e.jsx("h4",{children:s("dataLabeler.labels","Labels")}),C.labels.map(S=>{const E=c.labelSchema.classes.find(L=>L.id===S.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:()=>q(S.id),children:e.jsx($,{name:"close",size:14})})]},S.id)})]}),m==="label"&&C&&e.jsxs("div",{className:"label-actions",children:[e.jsxs("button",{className:"approve-button",onClick:W,children:[e.jsx($,{name:"check",size:14})," ",s("dataLabeler.approve","Approve")]}),e.jsxs("button",{className:"reject-button",onClick:G,children:[e.jsx($,{name:"close",size:14})," ",s("dataLabeler.reject","Reject")]})]})]})]})]}),m==="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($,{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:S=>z({type:S.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:S=>z({dataType:S.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((S,E)=>e.jsxs("div",{className:"class-editor",children:[e.jsx("input",{type:"color",value:S.color,onChange:L=>b(S.id,{color:L.target.value}),className:"color-picker"}),e.jsx("input",{type:"text",value:S.name,onChange:L=>b(S.id,{name:L.target.value}),className:"class-name-input",placeholder:s("dataLabeler.classNamePlaceholder","Class name")}),e.jsx("input",{type:"text",value:S.shortcut||"",onChange:L=>b(S.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:()=>B(S.id),children:e.jsx($,{name:"trash",size:16})})]},S.id))}),e.jsxs("div",{className:"guidelines-section",children:[e.jsx("h3",{children:s("dataLabeler.labelingGuidelines","Labeling Guidelines")}),e.jsx("textarea",{value:c.guidelines||"",onChange:S=>z({guidelines:S.target.value}),placeholder:s("dataLabeler.guidelinesPlaceholder","Enter labeling guidelines for annotators..."),rows:6})]})]}),m==="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:S=>h(S.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(S=>u==="all"||S.status===u).map((S,E)=>{var L;return e.jsxs("div",{className:`item-card ${g===c.items.indexOf(S)?"item-card--active":""}`,onClick:()=>{y(c.items.indexOf(S)),f("label")},children:[S.data.type==="image"&&e.jsx("img",{src:S.data.url,alt:`Item ${E+1}`,className:"item-thumbnail"}),S.data.type==="text"&&e.jsxs("p",{className:"item-text-preview",children:[(L=S.data.text)==null?void 0:L.slice(0,100),"..."]}),e.jsxs("div",{className:"item-footer",children:[e.jsx("span",{className:"status-dot",style:{backgroundColor:ie(S.status)}}),e.jsxs("span",{children:[S.labels.length," labels"]})]})]},S.id)})})]}),m==="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:()=>Z("coco"),children:[e.jsx("span",{className:"format-icon",children:e.jsx($,{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:()=>Z("voc"),children:[e.jsx("span",{className:"format-icon",children:e.jsx($,{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:()=>Z("yolo"),children:[e.jsx("span",{className:"format-icon",children:e.jsx($,{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:()=>Z("csv"),children:[e.jsx("span",{className:"format-icon",children:e.jsx($,{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(S=>{const E=c.labelSchema.classes.find(F=>F.id===S.classId),L=S.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:`${L}%`,backgroundColor:E==null?void 0:E.color}})}),e.jsx("span",{className:"count",children:S.count})]},S.classId)})})]})]})]}),x&&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:()=>v(!1),children:e.jsx($,{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(S=>S.shortcut&&e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:S.shortcut}),e.jsxs("span",{className:"description",children:["Label as ",S.name]})]},S.id))]})]})})]})},Hr={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:[]},Er=({endpoint:i,onInference:a,showMetrics:r=!0,showLogs:t=!0,className:n=""})=>{const[s,c]=o.useState(i||Hr),[d,m]=o.useState("test"),[f,g]=o.useState("text"),[y,k]=o.useState(""),[M,T]=o.useState("{}"),[j,A]=o.useState(null),[_,l]=o.useState({temperature:.7,topK:50,topP:.9,maxTokens:256,threshold:.5}),[N,w]=o.useState(null),[p,x]=o.useState(!1),[v,u]=o.useState(null),[h,I]=o.useState([]),[H,C]=o.useState(null),z=o.useRef(null),O=P=>{var J;const V=(J=P.target.files)==null?void 0:J[0];if(V){const W=new FileReader;W.onload=G=>{var Z;A((Z=G.target)==null?void 0:Z.result)},W.readAsDataURL(V)}},B=async()=>{if(!a){u("No inference handler provided");return}x(!0),u(null),w(null);const P=[];switch(f){case"text":P.push({type:"text",data:y});break;case"image":j&&P.push({type:"image",data:j});break;case"json":try{P.push({type:"json",data:JSON.parse(M)})}catch{u("Invalid JSON input"),x(!1);return}break;case"tabular":try{P.push({type:"tabular",data:JSON.parse(M)})}catch{u("Invalid tabular data"),x(!1);return}break}const V={inputs:P,parameters:_};try{const J=Date.now(),W=await a(V),G=Date.now()-J;w(W),c(Z=>({...Z,metrics:{...Z.metrics,requestsTotal:Z.metrics.requestsTotal+1,latencyP50:(Z.metrics.latencyP50+G)/2},logs:[{timestamp:new Date,requestId:W.requestId,duration:G,status:"success",inputSize:JSON.stringify(P).length,outputSize:JSON.stringify(W.predictions).length},...Z.logs.slice(0,99)]}))}catch(J){const W=J instanceof Error?J.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(P).length,outputSize:0,error:W},...G.logs.slice(0,99)]}))}finally{x(!1)}},b=async P=>{if(a){C(0),I([]);for(let V=0;V<P.length;V++){const J={inputs:[P[V]],parameters:_};try{const W=await a(J);I(G=>[...G,W])}catch(W){console.error("Batch item failed:",W)}C((V+1)/P.length*100)}C(null)}},R=P=>P<1e3?`${P.toFixed(0)}ms`:`${(P/1e3).toFixed(2)}s`,q=P=>P.toLocaleTimeString(),U=(P,V)=>e.jsxs("div",{className:"prediction-item",children:[P.label&&e.jsxs("div",{className:"prediction-label",children:[e.jsx("span",{className:"label-name",children:P.label}),P.confidence!==void 0&&e.jsxs("span",{className:"confidence-badge",style:{backgroundColor:`hsl(${P.confidence*120}, 70%, 40%)`},children:[(P.confidence*100).toFixed(1),"%"]})]}),P.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:P.score.toFixed(4)})]}),P.text&&e.jsx("div",{className:"prediction-text",children:e.jsx("pre",{children:P.text})}),P.bbox&&e.jsx("div",{className:"prediction-bbox",children:e.jsxs("span",{children:["Box: (",P.bbox.x,", ",P.bbox.y,") - ",P.bbox.width,"×",P.bbox.height]})}),P.raw!==void 0&&P.raw!==null&&e.jsxs("details",{className:"raw-output",children:[e.jsx("summary",{children:"Raw Output"}),e.jsx("pre",{children:JSON.stringify(P.raw,null,2)})]})]},V);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 ${d==="test"?"tab-button--active":""}`,onClick:()=>m("test"),children:"Test"}),e.jsx("button",{className:`tab-button ${d==="batch"?"tab-button--active":""}`,onClick:()=>m("batch"),children:"Batch"}),r&&e.jsx("button",{className:`tab-button ${d==="metrics"?"tab-button--active":""}`,onClick:()=>m("metrics"),children:"Metrics"}),t&&e.jsx("button",{className:`tab-button ${d==="logs"?"tab-button--active":""}`,onClick:()=>m("logs"),children:"Logs"})]})]}),e.jsxs("div",{className:"inference__content",children:[d==="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(P=>e.jsx("button",{className:`type-button ${f===P?"type-button--active":""}`,onClick:()=>g(P),children:P.charAt(0).toUpperCase()+P.slice(1)},P))}),e.jsxs("div",{className:"input-area",children:[f==="text"&&e.jsx("textarea",{value:y,onChange:P=>k(P.target.value),placeholder:"Enter text input...",rows:6,className:"text-input"}),f==="image"&&e.jsx("div",{className:"image-input",children:j?e.jsxs("div",{className:"image-preview",children:[e.jsx("img",{src:j,alt:"Input preview"}),e.jsx("button",{className:"clear-button",onClick:()=>A(null),children:"Clear"})]}):e.jsxs("label",{className:"upload-zone",children:[e.jsx("input",{ref:z,type:"file",accept:"image/*",onChange:O,hidden:!0}),e.jsx("span",{className:"upload-icon",children:e.jsx($,{name:"image",size:32})}),e.jsx("span",{children:"Click or drag to upload image"})]})}),(f==="json"||f==="tabular")&&e.jsx("textarea",{value:M,onChange:P=>T(P.target.value),placeholder:f==="json"?`{
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=Q(),[s,c]=d.useState(""),[l,m]=d.useState(!1),[g,x]=d.useState(null),[w,N]=d.useState(!1),S=d.useRef(null),R=d.useRef(0),j=d.useCallback(async()=>{var h,$,E;if(!n||!n.enabled||r)return;const{config:o,rateLimiter:k}=n;if(!k.recordRequest()){x("Rate limit exceeded. Please wait before requesting another hint.");return}const y=Le(t,o.privacyMode??!1),p=re.get(y);if(p){c(p),m(!1),x(null),N(!1);return}(h=S.current)==null||h.abort();const b=new AbortController;S.current=b,m(!0),x(null),c(""),N(!1);const v=Ca(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:v,temperature:o.temperature??.7,max_tokens:o.maxTokens??256,stream:u}),O=await fetch(o.endpoint,{method:"POST",headers:C,body:A,signal:b.signal});if(!O.ok){const B=await O.text().catch(()=>O.statusText);throw new Error(`AI request failed (${O.status}): ${B}`)}if(u){N(!0);let B="";for await(const f of qe(O,b.signal))if(b.signal.aborted||(B+=f.token,c(B),($=f.usage)!=null&&$.completion_tokens&&k.recordTokens(f.usage.completion_tokens),f.done))break;if(B.length>0){const f=Math.ceil(B.length/4);k.recordTokens(f)}re.set(y,B)}else{const B=await Ue(O);c(B.text),re.set(y,B.text),(E=B.usage)!=null&&E.completion_tokens?k.recordTokens(B.usage.completion_tokens):k.recordTokens(Math.ceil(B.text.length/4))}}catch(C){if(C instanceof DOMException&&C.name==="AbortError")return;x(C instanceof Error?C.message:"AI hint request failed")}finally{b.signal.aborted||(m(!1),N(!1))}},[n,t,r]);d.useEffect(()=>{if(!n||!n.enabled||r)return;const o=setTimeout(j,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,R.current]),d.useEffect(()=>()=>{var o;(o=S.current)==null||o.abort()},[]);const I=d.useCallback(()=>{var o;(o=S.current)==null||o.abort(),m(!1),N(!1)},[]),_=d.useCallback(()=>{if(n){const o=Le(t,n.config.privacyMode??!1);re.delete(o)}R.current+=1,j()},[n,t,j]);return!n||!n.enabled?{text:"",loading:!1,error:null,streaming:!1,abort:()=>{},refresh:()=>{},hint:null,fetchHint:async()=>{}}:{text:s,loading:l,error:g,streaming:w,abort:I,refresh:_,hint:s?{content:s}:null,fetchHint:async()=>{await j()}}}function Sa(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 Ta(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 Ne=d.forwardRef(({context:t,position:a="auto",debounceMs:i=500,showOnHover:r=!1,triggerIcon:n,className:s,style:c},l)=>{var y;const m=Q(),[g,x]=d.useState(!1),[w,N]=d.useState(!1),S=d.useRef(null),R=d.useRef(null),j=X(t,{debounceMs:i,disabled:!w});d.useEffect(()=>{if(!g)return;const p=b=>{var u,h;const v=b.target;(u=S.current)!=null&&u.contains(v)||(h=R.current)!=null&&h.contains(v)||(x(!1),N(!1))};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[g]),d.useEffect(()=>{if(!g)return;const p=b=>{b.key==="Escape"&&(x(!1),N(!1),j.abort())};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[g,j]);const I=d.useCallback(p=>{if(p.stopPropagation(),r)return;const b=!g;x(b),N(b)},[g,r]),_=d.useCallback(()=>{r&&(x(!0),N(!0))},[r]),o=d.useCallback(()=>{r&&(x(!1),N(!1))},[r]);if(!m||!m.enabled)return null;const k=Sa(a,((y=S.current)==null?void 0:y.getBoundingClientRect())??null);return e.jsxs("span",{ref:l,className:s,style:{position:"relative",display:"inline-flex",...c},onMouseEnter:_,onMouseLeave:o,children:[e.jsx("button",{ref:S,type:"button",onClick:I,"aria-label":"AI hint","aria-expanded":g,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})}),g&&e.jsxs("div",{ref:R,role:"tooltip",className:"ntd-ai-popover",style:Ta(k),children:[j.loading&&!j.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..."})]}),j.text&&e.jsxs("div",{className:"ntd-ai-content",children:[j.text,j.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"}})]}),j.error&&e.jsx("div",{className:"ntd-ai-error",style:{color:"var(--ntd-ai-error, #f38ba8)"},children:j.error}),j.text&&!j.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:()=>j.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 p;(p=navigator.clipboard)==null||p.writeText(j.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"]})]})]})]})});Ne.displayName="NiceAIHintBubble";function Ce(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 Se(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 Te(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 Ae(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 Re(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 Aa(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 Ra(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 He(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 We(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 Ia(t,a,i){const r=d.useMemo(()=>Ce(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 za(t,a,i){const r=d.useMemo(()=>Se(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 Ma(t,a,i){const r=d.useMemo(()=>Te(t,a,i),[t,a,i==null?void 0:i.multiple]);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.disableWeekends]);return X(r,i)}function Pa(t,a,i){const r=d.useMemo(()=>Re(t,a,i),[t,a,i==null?void 0:i.industry]);return X(r,i)}function $a(t,a,i,r,n){const s=d.useMemo(()=>r?We(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 Oa(t,a,i){const r=d.useMemo(()=>t?He(t,a):{fieldLabel:"Form"},[t,a]);return X(r,{...i,disabled:!t||(i==null?void 0:i.disabled)})}function Ge(t,a,i){const n=(a==null?void 0:a.split(`
6
+ `))??[],s=(i==null?void 0:i.cursorLine)!=null?n.slice(Math.max(0,i.cursorLine-8),i.cursorLine+3).join(`
7
+ `):n.slice(0,16).join(`
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 Ve(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 Ke(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 Ye(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 Xe(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 Qe(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 Ea(t,a,i){const r=d.useMemo(()=>Ge(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 Da(t,a,i){const r=d.useMemo(()=>Ve(t,a,i),[t,a,i==null?void 0:i.mode,i==null?void 0:i.locale]);return X(r,i)}function Ba(t,a){const i=d.useMemo(()=>Ke(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 Fa(t,a){const i=d.useMemo(()=>Ye(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 Ja(t,a){const i=d.useMemo(()=>Xe(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 qa(t,a){const i=d.useMemo(()=>Qe(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 Ze(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 Ua(t,a){const i=d.useMemo(()=>Ze(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 ea(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(m=>{var g;return{id:m.id,type:m.type,label:(g=m.label)==null?void 0:g.slice(0,30),pos:[Math.round(m.x),Math.round(m.y)]}}),l=a.map(m=>({id:m.id,src:m.source,tgt:m.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 Ha(t,a,i){const r=d.useMemo(()=>ea(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 aa(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 Wa(t,a){const i=d.useMemo(()=>aa(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 ia(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 Ga(t,a){const i=d.useMemo(()=>ia(t,a),[JSON.stringify(t),a==null?void 0:a.mode,JSON.stringify(a==null?void 0:a.brandColors)]);return X(i,a)}function Va(t,a,i){const r=d.forwardRef((n,s)=>{const{aiEnabled:c=!0,aiPosition:l="right",aiPrompt:m,aiDebounceMs:g=500,aiShowOnHover:x=!1,aiTriggerIcon:w,...N}=n,S=d.useMemo(()=>{const R=a(N);return m&&(R.customPrompt=m),R},[N,m]);return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(t,{...N,ref:s}),c&&e.jsx(Ne,{context:S,position:l,debounceMs:g,showOnHover:x,triggerIcon:w})]})});return r.displayName=i??`withAIHint(${t.displayName??t.name??"Component"})`,r}function Ka(t){return Ce(t.label??"Text",t.value,{placeholder:t.placeholder,maxLength:t.maxLength})}function Ya(t){return Se(t.label??"Number",t.value,{min:t.min,max:t.max,step:t.step})}function Xa(t){return Te(t.label??"Select",t.value,{options:t.options,multiple:t.multiple})}function Qa(t){return Ae(t.label??"Date",t.value,{min:t.min,max:t.max})}function Za(t){return Re(t.label??"Color",t.value)}const ei={id:crypto.randomUUID(),name:"New ML Project",type:"classification",status:"draft",datasets:[],experiments:[],models:[],createdAt:new Date,updatedAt:new Date},Pe={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"}]},$e={classification:["accuracy","precision","recall","f1-score","auc-roc"],regression:["mse","rmse","mae","r2"],clustering:["silhouette","calinski-harabasz","davies-bouldin"]},ai=[{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"}],ii=({project:t,onProjectChange:a,onExperimentRun:i,onModelDeploy:r,className:n="",tutorial:s})=>{var B;const[c,l]=d.useState(t||ei),[m,g]=d.useState("data"),[x,w]=d.useState(null),[N,S]=d.useState(null),[R,j]=d.useState(null),[I,_]=d.useState(!1),[o,k]=d.useState({algorithm:"",hyperparameters:{},preprocessing:[]}),y=d.useCallback(f=>{const z={...c,...f,updatedAt:new Date};l(z),a==null||a(z)},[c,a]),p=async f=>{for(const z of Array.from(f)){const U={id:crypto.randomUUID(),name:z.name.replace(/\.[^.]+$/,""),type:"tabular",source:{type:"file",uri:z.name},size:z.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(z.name.endsWith(".csv")){const P=(await z.text()).split(`
11
+ `),J=P[0].split(",").map(q=>q.trim());U.rowCount=P.length-1,U.columns=J.map(q=>({name:q,type:"text",nullable:!0,unique:0,missing:0})),U.splits=U.splits.map(q=>({...q,rowCount:Math.floor(U.rowCount*q.ratio)}))}y({datasets:[...c.datasets,U]})}},b=f=>{y({datasets:c.datasets.filter(z=>z.id!==f)}),x===f&&w(null)},v=async()=>{if(!o.algorithm||!x)return;const f={id:crypto.randomUUID(),name:`Experiment ${c.experiments.length+1}`,status:"pending",config:o,metrics:[],artifacts:[],logs:[]};if(y({experiments:[...c.experiments,f]}),_(!1),i){y({experiments:c.experiments.map(z=>z.id===f.id?{...z,status:"running",startedAt:new Date}:z)});try{await i(f);const z=($e[c.type]||$e.classification).map(U=>({name:U,value:Math.random()*.3+.7,split:"validation"}));y({experiments:c.experiments.map(U=>U.id===f.id?{...U,status:"completed",completedAt:new Date,metrics:z}:U)})}catch{y({experiments:c.experiments.map(z=>z.id===f.id?{...z,status:"failed"}:z)})}}},u=f=>{const z=c.experiments.find(H=>H.id===f);if(!z)return;const U={id:crypto.randomUUID(),name:`Model from ${z.name}`,version:"1.0.0",algorithm:z.config.algorithm,experimentId:f,status:"registered",metrics:z.metrics,size:Math.floor(Math.random()*100)*1024*1024,artifacts:[],deployments:[],createdAt:new Date};y({models:[...c.models,U]})},h=async f=>{const z=c.models.find(H=>H.id===f);if(!z||!r)return;const U=await r(z);y({models:c.models.map(H=>H.id===f?{...H,status:"production",deployments:[...H.deployments,U]}:H)})},$=f=>f<1024?`${f} B`:f<1024*1024?`${(f/1024).toFixed(1)} KB`:f<1024*1024*1024?`${(f/1024/1024).toFixed(1)} MB`:`${(f/1024/1024/1024).toFixed(1)} GB`,E=f=>{switch(f){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:f=>y({name:f.target.value}),className:"project-name-input"}),e.jsxs("select",{value:c.type,onChange:f=>y({type:f.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(f=>e.jsx("button",{className:`tab-button ${m===f?"tab-button--active":""}`,onClick:()=>g(f),children:f.charAt(0).toUpperCase()+f.slice(1)},f))}),O=e.jsxs("div",{className:"ml-studio__content",children:[m==="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:f=>f.target.files&&p(f.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(f=>e.jsxs("div",{className:`dataset-card ${x===f.id?"dataset-card--selected":""}`,onClick:()=>w(f.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:f.name}),e.jsx("button",{className:"remove-button","aria-label":"Remove dataset",onClick:z=>{z.stopPropagation(),b(f.id)},children:e.jsx(L.NiceIcon,{name:"close",size:14})})]}),e.jsxs("div",{className:"card-stats",children:[e.jsxs("span",{children:[f.rowCount.toLocaleString()," rows"]}),e.jsxs("span",{children:[f.columns.length," columns"]}),e.jsx("span",{children:$(f.size)})]}),e.jsx("div",{className:"splits-bar",children:f.splits.map(z=>e.jsx("div",{className:`split split--${z.name}`,style:{width:`${z.ratio*100}%`},title:`${z.name}: ${(z.ratio*100).toFixed(0)}%`},z.name))})]},f.id))}),x&&e.jsx("div",{className:"dataset-details",children:(()=>{const f=c.datasets.find(z=>z.id===x);return f?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:f.columns.map(z=>e.jsxs("tr",{children:[e.jsx("td",{children:z.name}),e.jsx("td",{children:e.jsxs("select",{value:z.type,onChange:U=>{y({datasets:c.datasets.map(H=>H.id===f.id?{...H,columns:H.columns.map(P=>P.name===z.name?{...P,type:U.target.value}:P)}:H)})},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:z.missing}),e.jsx("td",{children:z.unique})]},z.name))})]})]}):null})()})]}),m==="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:()=>_(!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:x||"",onChange:f=>w(f.target.value),children:[e.jsx("option",{value:"",children:"Select dataset..."}),c.datasets.map(f=>e.jsx("option",{value:f.id,children:f.name},f.id))]})]}),e.jsxs("label",{children:["Algorithm",e.jsxs("select",{value:o.algorithm,onChange:f=>k({...o,algorithm:f.target.value}),children:[e.jsx("option",{value:"",children:"Select algorithm..."}),(Pe[c.type]||Pe.classification).map(f=>e.jsx("option",{value:f.id,children:f.name},f.id))]})]}),x&&e.jsxs("label",{children:["Target Column",e.jsxs("select",{value:o.targetColumn||"",onChange:f=>k({...o,targetColumn:f.target.value}),children:[e.jsx("option",{value:"",children:"Select target..."}),(B=c.datasets.find(f=>f.id===x))==null?void 0:B.columns.map(f=>e.jsx("option",{value:f.name,children:f.name},f.name))]})]})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{className:"secondary-button",onClick:()=>_(!1),children:"Cancel"}),e.jsx("button",{className:"primary-button",onClick:v,disabled:!o.algorithm||!x,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(f=>e.jsxs("div",{className:`experiment-card ${N===f.id?"experiment-card--selected":""}`,onClick:()=>S(f.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:f.name}),e.jsx("span",{className:`status-badge ${E(f.status)}`,children:f.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Algorithm: ",f.config.algorithm]}),f.duration&&e.jsxs("span",{children:["Duration: ",Math.round(f.duration),"s"]})]}),f.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:f.metrics.slice(0,3).map(z=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:z.name}),e.jsxs("span",{className:"metric-value",children:[(z.value*100).toFixed(1),"%"]})]},z.name))}),f.status==="completed"&&e.jsx("button",{className:"action-button",onClick:z=>{z.stopPropagation(),u(f.id)},children:"Register Model"})]},f.id))})]}),m==="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(f=>e.jsxs("div",{className:`model-card ${R===f.id?"model-card--selected":""}`,onClick:()=>j(f.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:f.name}),e.jsx("span",{className:`status-badge ${E(f.status)}`,children:f.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Algorithm: ",f.algorithm]}),e.jsxs("span",{children:["Version: ",f.version]}),e.jsxs("span",{children:["Size: ",$(f.size)]})]}),f.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:f.metrics.slice(0,3).map(z=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:z.name}),e.jsxs("span",{className:"metric-value",children:[(z.value*100).toFixed(1),"%"]})]},z.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:z=>{z.stopPropagation(),h(f.id)},disabled:f.status==="production",children:f.status==="production"?"Deployed":"Deploy"})]})]},f.id))})]}),m==="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(f=>f.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(f=>f.deployments.length>0).flatMap(f=>f.deployments.map(z=>({model:f,deployment:z}))).map(({model:f,deployment:z})=>e.jsxs("div",{className:"deployment-card",children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:z.name}),e.jsx("span",{className:`status-badge ${E(z.status)}`,children:z.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Model: ",f.name]}),e.jsxs("span",{children:["Endpoint: ",z.endpoint]})]}),e.jsxs("div",{className:"resources-info",children:[e.jsxs("span",{children:["CPU: ",z.resources.cpu," cores"]}),e.jsxs("span",{children:["Memory: ",z.resources.memory," GB"]}),e.jsxs("span",{children:["Replicas: ",z.resources.replicas]})]})]},z.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,ai)})}),e.jsx(ka.NiceAppShell,{flush:!0,menubar:C,toolbar:A,children:O})]})},ti={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},Oe=["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-accent-pink, #d946ef)","var(--nice-accent-pink, #ec4899)","var(--nice-danger, #f43f5e)"],ri=({project:t,onProjectChange:a,onLabelSave:i,onExport:r,className:n=""})=>{var Z;const{t:s}=L.useNiceTranslation(),[c,l]=d.useState(t||ti),[m,g]=d.useState("label"),[x,w]=d.useState(0),[N,S]=d.useState(null),[R,j]=d.useState("select"),[I,_]=d.useState(!1),[o,k]=d.useState(null),[y,p]=d.useState(1),[b,v]=d.useState(!1),[u,h]=d.useState("all"),$=d.useRef(null),E=d.useRef(null),C=c.items[x];d.useEffect(()=>{t&&l(t)},[t]);const A=d.useCallback(T=>{const D={...c,...T};D.statistics={totalItems:D.items.length,labeled:D.items.filter(M=>M.status!=="pending").length,reviewed:D.items.filter(M=>M.status==="review"||M.status==="approved").length,approved:D.items.filter(M=>M.status==="approved").length,byClass:D.labelSchema.classes.map(M=>({classId:M.id,count:D.items.flatMap(F=>F.labels).filter(F=>F.classId===M.id).length}))},l(D),a==null||a(D)},[c,a]),O=()=>{const T={id:crypto.randomUUID(),name:`Class ${c.labelSchema.classes.length+1}`,color:Oe[c.labelSchema.classes.length%Oe.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(D=>D.id!==T)},items:c.items.map(D=>({...D,labels:D.labels.filter(M=>M.classId!==T)}))})},f=(T,D)=>{A({labelSchema:{...c.labelSchema,classes:c.labelSchema.classes.map(M=>M.id===T?{...M,...D}:M)}})},z=(T,D)=>{if(!C)return;const M={id:crypto.randomUUID(),classId:T,type:c.type==="classification"?"class":c.type==="bounding-box"?"bbox":"class",data:D||{},createdBy:"current-user",createdAt:new Date},F={...C,labels:[...C.labels,M],status:"labeled"};A({items:c.items.map(K=>K.id===C.id?F:K)}),i==null||i(F)},U=T=>{if(!C)return;const D={...C,labels:C.labels.filter(M=>M.id!==T),status:C.labels.length<=1?"pending":"labeled"};A({items:c.items.map(M=>M.id===C.id?D:M)})},H=T=>{var K;if(R!=="bbox"||!N)return;const D=(K=$.current)==null?void 0:K.getBoundingClientRect();if(!D)return;const M=(T.clientX-D.left)/y,F=(T.clientY-D.top)/y;_(!0),k({x:M,y:F,width:0,height:0})},P=T=>{var K;if(!I||!o)return;const D=(K=$.current)==null?void 0:K.getBoundingClientRect();if(!D)return;const M=(T.clientX-D.left)/y,F=(T.clientY-D.top)/y;k({...o,width:M-o.x,height:F-o.y})},J=()=>{!I||!o||!N||(_(!1),Math.abs(o.width)>10&&Math.abs(o.height)>10&&z(N,{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)}),k(null))},q=T=>{const D=u==="all"?c.items:c.items.filter(F=>F.status===u),M=D.findIndex(F=>F.id===(C==null?void 0:C.id));if(T==="prev"&&M>0){const F=D[M-1];w(c.items.findIndex(K=>K.id===F.id))}else if(T==="next"&&M<D.length-1){const F=D[M+1];w(c.items.findIndex(K=>K.id===F.id))}},W=()=>{if(!C)return;const T={...C,status:"approved"};A({items:c.items.map(D=>D.id===C.id?T:D)}),q("next")},G=()=>{if(!C)return;const T={...C,status:"rejected"};A({items:c.items.map(D=>D.id===C.id?T:D)}),q("next")},Y=async T=>{r&&await r(T)};d.useEffect(()=>{const T=D=>{const M=D.key,F=c.labelSchema.classes.find(K=>K.shortcut===M);F&&(c.type==="classification"?(z(F.id),q("next")):S(F.id)),D.key==="ArrowLeft"||D.key==="a"?q("prev"):(D.key==="ArrowRight"||D.key==="d")&&q("next"),D.key==="Enter"?W():D.key==="Backspace"&&G()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[C,c.labelSchema.classes,c.type]);const ae=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 ${m===T?"tab-button--active":""}`,onClick:()=>g(T),children:T.charAt(0).toUpperCase()+T.slice(1)},T))}),e.jsx("button",{className:"shortcuts-button",onClick:()=>v(!b),children:s("dataLabeler.shortcuts","Shortcuts")})]}),e.jsxs("div",{className:"labeler__content",children:[m==="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 ${R==="select"?"tool-button--active":""}`,onClick:()=>j("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 ${R==="bbox"?"tool-button--active":""}`,onClick:()=>j("bbox"),children:[e.jsx(L.NiceIcon,{name:"square",size:14})," Box"]}),c.type==="polygon"&&e.jsxs("button",{className:`tool-button ${R==="polygon"?"tool-button--active":""}`,onClick:()=>j("polygon"),children:[e.jsx(L.NiceIcon,{name:"hexagon",size:14})," ",s("dataLabeler.polygon","Polygon")]})]}),e.jsxs("div",{className:"zoom-group",children:[e.jsx("button",{onClick:()=>p(Math.max(.25,y-.25)),children:"-"}),e.jsxs("span",{children:[Math.round(y*100),"%"]}),e.jsx("button",{onClick:()=>p(Math.min(4,y+.25)),children:"+"})]}),e.jsxs("div",{className:"navigation-group",children:[e.jsxs("button",{onClick:()=>q("prev"),disabled:x===0,children:[e.jsx(L.NiceIcon,{name:"arrow-left",size:14})," ",s("dataLabeler.prev","Prev")]}),e.jsxs("span",{children:[x+1," / ",c.items.length]}),e.jsxs("button",{onClick:()=>q("next"),disabled:x>=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:E,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(${y})`}}),e.jsx("canvas",{ref:$,className:"labeling-canvas",onMouseDown:H,onMouseMove:P,onMouseUp:J,onMouseLeave:J,style:{transform:`scale(${y})`,cursor:R==="bbox"?"crosshair":"default"}}),e.jsxs("div",{className:"annotations-overlay",style:{transform:`scale(${y})`},children:[C.labels.filter(T=>T.type==="bbox"&&T.data.x!==void 0).map(T=>{const D=c.labelSchema.classes.find(M=>M.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:(D==null?void 0:D.color)||"var(--nice-danger, #ff0000)"},children:[e.jsx("span",{className:"bbox-label",style:{backgroundColor:(D==null?void 0:D.color)||"var(--nice-danger, #ff0000)"},children:D==null?void 0:D.name}),e.jsx("button",{className:"bbox-remove",onClick:()=>U(T.id),children:"×"})]},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:(Z=c.labelSchema.classes.find(T=>T.id===N))==null?void 0:Z.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 ${N===T.id?"class-button--active":""}`,style:{borderLeftColor:T.color},onClick:()=>{c.type==="classification"?(z(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 D=c.labelSchema.classes.find(M=>M.id===T.classId);return e.jsxs("div",{className:"label-item",children:[e.jsx("span",{className:"label-color",style:{backgroundColor:D==null?void 0:D.color}}),e.jsx("span",{className:"label-name",children:D==null?void 0:D.name}),e.jsx("button",{"aria-label":s("dataLabeler.removeLabel","Remove label"),onClick:()=>U(T.id),children:e.jsx(L.NiceIcon,{name:"close",size:14})})]},T.id)})]}),m==="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")]})]})]})]})]}),m==="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,D)=>e.jsxs("div",{className:"class-editor",children:[e.jsx("input",{type:"color",value:T.color,onChange:M=>f(T.id,{color:M.target.value}),className:"color-picker"}),e.jsx("input",{type:"text",value:T.name,onChange:M=>f(T.id,{name:M.target.value}),className:"class-name-input",placeholder:s("dataLabeler.classNamePlaceholder","Class name")}),e.jsx("input",{type:"text",value:T.shortcut||"",onChange:M=>f(T.id,{shortcut:M.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})]})]}),m==="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,D)=>{var M;return e.jsxs("div",{className:`item-card ${x===c.items.indexOf(T)?"item-card--active":""}`,onClick:()=>{w(c.items.indexOf(T)),g("label")},children:[T.data.type==="image"&&e.jsx("img",{src:T.data.url,alt:`Item ${D+1}`,className:"item-thumbnail"}),T.data.type==="text"&&e.jsxs("p",{className:"item-text-preview",children:[(M=T.data.text)==null?void 0:M.slice(0,100),"..."]}),e.jsxs("div",{className:"item-footer",children:[e.jsx("span",{className:"status-dot",style:{backgroundColor:ae(T.status)}}),e.jsxs("span",{children:[T.labels.length," labels"]})]})]},T.id)})})]}),m==="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 D=c.labelSchema.classes.find(F=>F.id===T.classId),M=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:D==null?void 0:D.color},children:D==null?void 0:D.name}),e.jsx("div",{className:"bar-container",children:e.jsx("div",{className:"bar-fill",style:{width:`${M}%`,backgroundColor:D==null?void 0:D.color}})}),e.jsx("span",{className:"count",children:T.count})]},T.classId)})})]})]})]}),b&&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:()=>v(!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))]})]})})]})},ni={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:[]},si=({endpoint:t,onInference:a,showMetrics:i=!0,showLogs:r=!0,className:n=""})=>{const[s,c]=d.useState(t||ni),[l,m]=d.useState("test"),[g,x]=d.useState("text"),[w,N]=d.useState(""),[S,R]=d.useState("{}"),[j,I]=d.useState(null),[_,o]=d.useState({temperature:.7,topK:50,topP:.9,maxTokens:256,threshold:.5}),[k,y]=d.useState(null),[p,b]=d.useState(!1),[v,u]=d.useState(null),[h,$]=d.useState([]),[E,C]=d.useState(null),A=d.useRef(null),O=P=>{var q;const J=(q=P.target.files)==null?void 0:q[0];if(J){const W=new FileReader;W.onload=G=>{var Y;I((Y=G.target)==null?void 0:Y.result)},W.readAsDataURL(J)}},B=async()=>{if(!a){u("No inference handler provided");return}b(!0),u(null),y(null);const P=[];switch(g){case"text":P.push({type:"text",data:w});break;case"image":j&&P.push({type:"image",data:j});break;case"json":try{P.push({type:"json",data:JSON.parse(S)})}catch{u("Invalid JSON input"),b(!1);return}break;case"tabular":try{P.push({type:"tabular",data:JSON.parse(S)})}catch{u("Invalid tabular data"),b(!1);return}break}const J={inputs:P,parameters:_};try{const q=Date.now(),W=await a(J),G=Date.now()-q;y(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(P).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(P).length,outputSize:0,error:W},...G.logs.slice(0,99)]}))}finally{b(!1)}},f=async P=>{if(a){C(0),$([]);for(let J=0;J<P.length;J++){const q={inputs:[P[J]],parameters:_};try{const W=await a(q);$(G=>[...G,W])}catch(W){console.error("Batch item failed:",W)}C((J+1)/P.length*100)}C(null)}},z=P=>P<1e3?`${P.toFixed(0)}ms`:`${(P/1e3).toFixed(2)}s`,U=P=>P.toLocaleTimeString(),H=(P,J)=>e.jsxs("div",{className:"prediction-item",children:[P.label&&e.jsxs("div",{className:"prediction-label",children:[e.jsx("span",{className:"label-name",children:P.label}),P.confidence!==void 0&&e.jsxs("span",{className:"confidence-badge",style:{backgroundColor:`hsl(${P.confidence*120}, 70%, 40%)`},children:[(P.confidence*100).toFixed(1),"%"]})]}),P.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:P.score.toFixed(4)})]}),P.text&&e.jsx("div",{className:"prediction-text",children:e.jsx("pre",{children:P.text})}),P.bbox&&e.jsx("div",{className:"prediction-bbox",children:e.jsxs("span",{children:["Box: (",P.bbox.x,", ",P.bbox.y,") - ",P.bbox.width,"×",P.bbox.height]})}),P.raw!==void 0&&P.raw!==null&&e.jsxs("details",{className:"raw-output",children:[e.jsx("summary",{children:"Raw Output"}),e.jsx("pre",{children:JSON.stringify(P.raw,null,2)})]})]},J);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:()=>m("test"),children:"Test"}),e.jsx("button",{className:`tab-button ${l==="batch"?"tab-button--active":""}`,onClick:()=>m("batch"),children:"Batch"}),i&&e.jsx("button",{className:`tab-button ${l==="metrics"?"tab-button--active":""}`,onClick:()=>m("metrics"),children:"Metrics"}),r&&e.jsx("button",{className:`tab-button ${l==="logs"?"tab-button--active":""}`,onClick:()=>m("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(P=>e.jsx("button",{className:`type-button ${g===P?"type-button--active":""}`,onClick:()=>x(P),children:P.charAt(0).toUpperCase()+P.slice(1)},P))}),e.jsxs("div",{className:"input-area",children:[g==="text"&&e.jsx("textarea",{value:w,onChange:P=>N(P.target.value),placeholder:"Enter text input...",rows:6,className:"text-input"}),g==="image"&&e.jsx("div",{className:"image-input",children:j?e.jsxs("div",{className:"image-preview",children:[e.jsx("img",{src:j,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"})]})}),(g==="json"||g==="tabular")&&e.jsx("textarea",{value:S,onChange:P=>R(P.target.value),placeholder:g==="json"?`{
38
12
  "key": "value"
39
13
  }`:`[
40
14
  {"col1": "value1", "col2": "value2"}
41
- ]`,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:P=>l({..._,temperature:parseFloat(P.target.value)}),min:"0",max:"2",step:"0.1"})]}),e.jsxs("label",{children:["Top K",e.jsx("input",{type:"number",value:_.topK,onChange:P=>l({..._,topK:parseInt(P.target.value)}),min:"1",max:"100"})]}),e.jsxs("label",{children:["Top P",e.jsx("input",{type:"number",value:_.topP,onChange:P=>l({..._,topP:parseFloat(P.target.value)}),min:"0",max:"1",step:"0.05"})]}),e.jsxs("label",{children:["Threshold",e.jsx("input",{type:"number",value:_.threshold,onChange:P=>l({..._,threshold:parseFloat(P.target.value)}),min:"0",max:"1",step:"0.05"})]})]})]}),e.jsx("button",{className:"run-button",onClick:B,disabled:p||!y&&!j&&M==="{}",children:p?"Running...":"Run Inference"})]}),e.jsxs("div",{className:"output-section",children:[e.jsx("h3",{children:"Output"}),v&&e.jsxs("div",{className:"error-message",children:[e.jsx("span",{className:"error-icon",children:e.jsx($,{name:"warning",size:16})}),v]}),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: ",R(N.latency)]}),e.jsxs("span",{children:["Model: ",N.modelVersion]})]}),e.jsx("div",{className:"predictions-list",children:N.predictions.map((P,V)=>U(P,V))})]}),!v&&!N&&e.jsxs("div",{className:"empty-output",children:[e.jsx("span",{className:"icon",children:e.jsx($,{name:"upload",size:32})}),e.jsx("p",{children:"Run inference to see results"})]})]})]}),d==="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 P=>{var J;const V=(J=P.target.files)==null?void 0:J[0];if(V){const W=await V.text();try{const G=JSON.parse(W);if(Array.isArray(G)){const Z=G.map(ie=>({type:"json",data:ie}));b(Z)}}catch{u("Invalid batch file format")}}},hidden:!0}),e.jsx("span",{className:"upload-icon",children:e.jsx($,{name:"folder",size:32})}),e.jsx("span",{children:"Upload JSON array file"})]})]}),H!==null&&e.jsxs("div",{className:"batch-progress",children:[e.jsx("div",{className:"progress-bar",children:e.jsx("div",{className:"progress-fill",style:{width:`${H}%`}})}),e.jsxs("span",{children:[Math.round(H),"%"]})]}),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((P,V)=>e.jsxs("div",{className:"batch-result-item",children:[e.jsxs("span",{className:"result-index",children:["#",V+1]}),P.predictions.map((J,W)=>e.jsxs("span",{className:"result-prediction",children:[J.label,": ",(J.confidence||J.score||0*100).toFixed(1),"%"]},W))]},V))})]})]}),d==="metrics"&&r&&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:R(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:R(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:R(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(P=>e.jsxs("div",{className:"histogram-bar",children:[e.jsx("div",{className:"bar-fill",style:{height:`${Math.min(100,s.metrics.latencyP50*P/100)}px`}}),e.jsxs("span",{className:"percentile-label",children:["P",P]})]},P))})]})]}),d==="logs"&&t&&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(P=>({...P,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((P,V)=>e.jsxs("tr",{className:`log-row log-row--${P.status}`,children:[e.jsx("td",{children:q(P.timestamp)}),e.jsx("td",{className:"request-id",children:P.requestId.slice(0,8)}),e.jsx("td",{children:R(P.duration)}),e.jsx("td",{children:e.jsx("span",{className:`status-badge status-badge--${P.status}`,children:P.status})}),e.jsxs("td",{children:[P.inputSize," B"]}),e.jsxs("td",{children:[P.outputSize," B"]})]},V))})]})})]})]})]})};class se{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,r,t=this.config.maxRetries){let n=null;for(let s=0;s<=t;s++)try{this.abortController=new AbortController;const c=setTimeout(()=>{var m;return(m=this.abortController)==null?void 0:m.abort()},this.config.timeout),d=await fetch(a,{...r,signal:this.abortController.signal});if(clearTimeout(c),d.ok)return d;if(d.status>=400&&d.status<500){const m=await d.text();throw new Error(`API Error ${d.status}: ${m}`)}n=new Error(`HTTP ${d.status}`)}catch(c){n=c,s<t&&await this.delay(this.config.retryDelay*(s+1))}throw n??new Error("Request failed after retries")}delay(a){return new Promise(r=>setTimeout(r,a))}async parseSSEStream(a,r,t,n){var m;const s=(m=a.body)==null?void 0:m.getReader();if(!s){n==null||n(new Error("No response body"));return}const c=new TextDecoder;let d="";try{for(;;){const{done:f,value:g}=await s.read();if(f)break;d+=c.decode(g,{stream:!0});const y=d.split(`
42
- `);d=y.pop()||"";for(const k of y)if(k.startsWith("data: ")){const M=k.slice(6).trim();if(M==="[DONE]"){t==null||t();return}try{const T=JSON.parse(M);r(this.normalizeStreamChunk(T))}catch{}}}t==null||t()}catch(f){n==null||n(f)}finally{s.releaseLock()}}}class ya extends se{constructor(a){super(a),this.type="openai",this.name="OpenAI",this.baseUrl=a.baseUrl||"https://api.openai.com/v1"}async chat(a){const t=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(t,a)}async chatStream(a,r,t,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,r,t,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(t=>t.id.includes("gpt")).map(t=>t.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,r){const t=a;return{id:t.id,model:t.model,choices:t.choices.map(n=>({index:n.index,message:n.message,finishReason:n.finish_reason})),usage:{promptTokens:t.usage.prompt_tokens,completionTokens:t.usage.completion_tokens,totalTokens:t.usage.total_tokens},estimatedCost:this.estimateCost(t.model,t.usage.prompt_tokens,t.usage.completion_tokens)}}normalizeStreamChunk(a){const r=a;return{id:r.id,choices:r.choices.map(t=>({index:t.index,delta:t.delta,finishReason:t.finish_reason}))}}estimateCost(a,r,t){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(d=>a.includes(d)),c=s?n[s]:n["gpt-4o-mini"];return r/1e6*c.input+t/1e6*c.output}}class ba extends se{constructor(a){super(a),this.type="anthropic",this.name="Anthropic Claude",this.baseUrl=a.baseUrl||"https://api.anthropic.com/v1"}async chat(a){const t=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(t)}async chatStream(a,r,t,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,r,t,n)}catch(s){n==null||n(s)}}buildRequestBody(a){const r=a.messages.find(n=>n.role==="system"),t=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:r==null?void 0:r.content,messages:t.map(n=>({role:n.role==="assistant"?"assistant":"user",content:n.content})),temperature:a.temperature??.7}}normalizeResponse(a){const r=a,t=r.content.find(n=>n.type==="text");return{id:r.id,model:r.model,choices:[{index:0,message:{role:"assistant",content:(t==null?void 0:t.text)||""},finishReason:r.stop_reason==="end_turn"?"stop":"length"}],usage:{promptTokens:r.usage.input_tokens,completionTokens:r.usage.output_tokens,totalTokens:r.usage.input_tokens+r.usage.output_tokens},estimatedCost:this.estimateCost(r.model,r.usage.input_tokens,r.usage.output_tokens)}}normalizeStreamChunk(a){var t;const r=a;return{id:"",choices:[{index:r.index||0,delta:{content:((t=r.delta)==null?void 0:t.text)||""},finishReason:r.type==="message_stop"?"stop":null}]}}async parseAnthropicStream(a,r,t,n){var m;const s=(m=a.body)==null?void 0:m.getReader();if(!s){n==null||n(new Error("No response body"));return}const c=new TextDecoder;let d="";try{for(;;){const{done:f,value:g}=await s.read();if(f)break;d+=c.decode(g,{stream:!0});const y=d.split(`
43
- `);d=y.pop()||"";for(const k of y)if(k.startsWith("data: "))try{const M=JSON.parse(k.slice(6));if(M.type==="content_block_delta")r(this.normalizeStreamChunk(M));else if(M.type==="message_stop"){t==null||t();return}}catch{}}t==null||t()}catch(f){n==null||n(f)}finally{s.releaseLock()}}estimateCost(a,r,t){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(d=>a.includes(d)),c=s?n[s]:n["claude-3-5-sonnet"];return r/1e6*c.input+t/1e6*c.output}}class xa extends se{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 r=`${this.config.baseUrl}/openai/deployments/${this.config.deployment}/chat/completions?api-version=${this.config.apiVersion||"2024-02-01"}`,n=await(await this.fetchWithRetry(r,{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,r,t,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,r,t,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 r=a;return{id:r.id,model:r.model,choices:r.choices.map(t=>({index:t.index,message:t.message,finishReason:t.finish_reason})),usage:{promptTokens:r.usage.prompt_tokens,completionTokens:r.usage.completion_tokens,totalTokens:r.usage.total_tokens}}}normalizeStreamChunk(a){const r=a;return{id:r.id,choices:r.choices.map(t=>({index:t.index,delta:t.delta,finishReason:t.finish_reason}))}}}class va extends se{constructor(a){super(a),this.type="ollama",this.name="Ollama (Local)",this.baseUrl=a.baseUrl||"http://localhost:11434"}async chat(a){const t=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(t)}async chatStream(a,r,t,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,r,t,n)}catch(s){n==null||n(s)}}async listModels(){try{return((await(await this.fetchWithRetry(`${this.baseUrl}/api/tags`,{method:"GET"})).json()).models||[]).map(t=>t.name)}catch{return[]}}normalizeResponse(a){const r=a;return{id:`ollama-${Date.now()}`,model:r.model,choices:[{index:0,message:r.message,finishReason:r.done?"stop":null}],usage:{promptTokens:r.prompt_eval_count||0,completionTokens:r.eval_count||0,totalTokens:(r.prompt_eval_count||0)+(r.eval_count||0)},estimatedCost:0}}normalizeStreamChunk(a){var t;const r=a;return{id:`ollama-${Date.now()}`,choices:[{index:0,delta:{content:((t=r.message)==null?void 0:t.content)||""},finishReason:r.done?"stop":null}]}}async parseOllamaStream(a,r,t,n){var m;const s=(m=a.body)==null?void 0:m.getReader();if(!s){n==null||n(new Error("No response body"));return}const c=new TextDecoder;let d="";try{for(;;){const{done:f,value:g}=await s.read();if(f)break;d+=c.decode(g,{stream:!0});const y=d.split(`
44
- `);d=y.pop()||"";for(const k of y)if(k.trim())try{const M=JSON.parse(k);if(r(this.normalizeStreamChunk(M)),M.done){t==null||t();return}}catch{}}t==null||t()}catch(f){n==null||n(f)}finally{s.releaseLock()}}}class _a extends se{constructor(a){super(a),this.type="groq",this.name="Groq",this.baseUrl=a.baseUrl||"https://api.groq.com/openai/v1"}async chat(a){const t=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(t)}async chatStream(a,r,t,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,r,t,n)}catch(s){n==null||n(s)}}normalizeResponse(a){const r=a;return{id:r.id,model:r.model,choices:r.choices.map(t=>({index:t.index,message:t.message,finishReason:t.finish_reason})),usage:{promptTokens:r.usage.prompt_tokens,completionTokens:r.usage.completion_tokens,totalTokens:r.usage.total_tokens},estimatedCost:0}}normalizeStreamChunk(a){const r=a;return{id:r.id,choices:r.choices.map(t=>({index:t.index,delta:t.delta,finishReason:t.finish_reason}))}}}function ne(i){switch(i.type){case"openai":return new ya(i);case"anthropic":return new ba(i);case"azure-openai":return new xa(i);case"ollama":return new va(i);case"groq":return new _a(i);default:throw new Error(`Unsupported provider type: ${i.type}`)}}function K(i){const a=i.endpoint.toLowerCase();let r="custom";a.includes("openai.com")?r="openai":a.includes("anthropic.com")?r="anthropic":a.includes("azure.com")||a.includes("openai.azure.com")?r="azure-openai":a.includes("localhost:11434")||a.includes("ollama")?r="ollama":a.includes("groq.com")&&(r="groq");const t=new URL(i.endpoint),n=`${t.protocol}//${t.host}`;return ne({type:r,apiKey:i.apiKey,baseUrl:n,model:i.model,headers:i.headers})}function re(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 r={};for(const n of i.variables)r[n.name]=a[n.name]??n.default;const t=n=>n.replace(/\{\{(\w+)\}\}/g,(s,c)=>{const d=r[c];return d===void 0?`{{${c}}}`:typeof d=="object"?JSON.stringify(d,null,2):String(d)});return{system:t(i.system),user:t(i.user),metadata:{templateId:i.id,variables:r,timestamp:Date.now()}}}const oe={id:"data-grid-filter",name:"DataGrid Natural Language Filter",description:"Convert natural language queries to DataGrid filter configurations",category:"data-query",system:`You are a filter query generator for a data grid component.
15
+ ]`,rows:10,className:"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:P=>o({..._,temperature:parseFloat(P.target.value)}),min:"0",max:"2",step:"0.1"})]}),e.jsxs("label",{children:["Top K",e.jsx("input",{type:"number",value:_.topK,onChange:P=>o({..._,topK:parseInt(P.target.value)}),min:"1",max:"100"})]}),e.jsxs("label",{children:["Top P",e.jsx("input",{type:"number",value:_.topP,onChange:P=>o({..._,topP:parseFloat(P.target.value)}),min:"0",max:"1",step:"0.05"})]}),e.jsxs("label",{children:["Threshold",e.jsx("input",{type:"number",value:_.threshold,onChange:P=>o({..._,threshold:parseFloat(P.target.value)}),min:"0",max:"1",step:"0.05"})]})]})]}),e.jsx("button",{className:"run-button",onClick:B,disabled:p||!w&&!j&&S==="{}",children:p?"Running...":"Run Inference"})]}),e.jsxs("div",{className:"output-section",children:[e.jsx("h3",{children:"Output"}),v&&e.jsxs("div",{className:"error-message",children:[e.jsx("span",{className:"error-icon",children:e.jsx(L.NiceIcon,{name:"warning",size:16})}),v]}),k&&e.jsxs("div",{className:"result-container",children:[e.jsxs("div",{className:"result-meta",children:[e.jsxs("span",{children:["Request ID: ",k.requestId]}),e.jsxs("span",{children:["Latency: ",z(k.latency)]}),e.jsxs("span",{children:["Model: ",k.modelVersion]})]}),e.jsx("div",{className:"predictions-list",children:k.predictions.map((P,J)=>H(P,J))})]}),!v&&!k&&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 P=>{var q;const J=(q=P.target.files)==null?void 0:q[0];if(J){const W=await J.text();try{const G=JSON.parse(W);if(Array.isArray(G)){const Y=G.map(ae=>({type:"json",data:ae}));f(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"})]})]}),E!==null&&e.jsxs("div",{className:"batch-progress",children:[e.jsx("div",{className:"progress-bar",children:e.jsx("div",{className:"progress-fill",style:{width:`${E}%`}})}),e.jsxs("span",{children:[Math.round(E),"%"]})]}),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((P,J)=>e.jsxs("div",{className:"batch-result-item",children:[e.jsxs("span",{className:"result-index",children:["#",J+1]}),P.predictions.map((q,W)=>e.jsxs("span",{className:"result-prediction",children:[q.label,": ",(q.confidence||q.score||0).toFixed(1),"%"]},W))]},J))})]})]}),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:z(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:z(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:z(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(P=>e.jsxs("div",{className:"histogram-bar",children:[e.jsx("div",{className:"bar-fill",style:{height:`${Math.min(100,s.metrics.latencyP50*P/100)}px`}}),e.jsxs("span",{className:"percentile-label",children:["P",P]})]},P))})]})]}),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(P=>({...P,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((P,J)=>e.jsxs("tr",{className:`log-row log-row--${P.status}`,children:[e.jsx("td",{children:U(P.timestamp)}),e.jsx("td",{className:"request-id",children:P.requestId.slice(0,8)}),e.jsx("td",{children:z(P.duration)}),e.jsx("td",{children:e.jsx("span",{className:`status-badge status-badge--${P.status}`,children:P.status})}),e.jsxs("td",{children:[P.inputSize," B"]}),e.jsxs("td",{children:[P.outputSize," B"]})]},J))})]})})]})]})]})};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 m;return(m=this.abortController)==null?void 0:m.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 m=await l.text();throw new Error(`API Error ${l.status}: ${m}`)}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 m;const s=(m=a.body)==null?void 0:m.getReader();if(!s){n==null||n(new Error("No response body"));return}const c=new TextDecoder;let l="";try{for(;;){const{done:g,value:x}=await s.read();if(g)break;l+=c.decode(x,{stream:!0});const w=l.split(`
16
+ `);l=w.pop()||"";for(const N of w)if(N.startsWith("data: ")){const S=N.slice(6).trim();if(S==="[DONE]"){r==null||r();return}try{const R=JSON.parse(S);i(this.normalizeStreamChunk(R))}catch{}}}r==null||r()}catch(g){n==null||n(g)}finally{s.releaseLock()}}}class ta 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 ra 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 m;const s=(m=a.body)==null?void 0:m.getReader();if(!s){n==null||n(new Error("No response body"));return}const c=new TextDecoder;let l="";try{for(;;){const{done:g,value:x}=await s.read();if(g)break;l+=c.decode(x,{stream:!0});const w=l.split(`
17
+ `);l=w.pop()||"";for(const N of w)if(N.startsWith("data: "))try{const S=JSON.parse(N.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(g){n==null||n(g)}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 na 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 sa 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 m;const s=(m=a.body)==null?void 0:m.getReader();if(!s){n==null||n(new Error("No response body"));return}const c=new TextDecoder;let l="";try{for(;;){const{done:g,value:x}=await s.read();if(g)break;l+=c.decode(x,{stream:!0});const w=l.split(`
18
+ `);l=w.pop()||"";for(const N of w)if(N.trim())try{const S=JSON.parse(N);if(i(this.normalizeStreamChunk(S)),S.done){r==null||r();return}}catch{}}r==null||r()}catch(g){n==null||n(g)}finally{s.releaseLock()}}}class ca 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 ie(t){switch(t.type){case"openai":return new ta(t);case"anthropic":return new ra(t);case"azure-openai":return new na(t);case"ollama":return new sa(t);case"groq":return new ca(t);default:throw new Error(`Unsupported provider type: ${t.type}`)}}function V(t){const a=t.endpoint.toLowerCase();let i="custom";a.includes("openai.com")?i="openai":a.includes("anthropic.com")?i="anthropic":a.includes("azure.com")||a.includes("openai.azure.com")?i="azure-openai":a.includes("localhost:11434")||a.includes("ollama")?i="ollama":a.includes("groq.com")&&(i="groq");const r=new URL(t.endpoint),n=`${r.protocol}//${r.host}`;return ie({type:i,apiKey:t.apiKey,baseUrl:n,model:t.model,headers:t.headers})}function ee(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(/\{\{(\w+)\}\}/g,(s,c)=>{const l=i[c];return l===void 0?`{{${c}}}`:typeof l=="object"?JSON.stringify(l,null,2):String(l)});return{system:r(t.system),user:r(t.user),metadata:{templateId:t.id,variables:i,timestamp:Date.now()}}}const ne={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.
45
19
  Given column definitions and a natural language query, generate a JSON filter configuration.
46
20
 
47
21
  Available filter operators:
@@ -74,7 +48,7 @@ Generate the filter configuration:`,variables:[{name:"columns",description:"JSON
74
48
  { "column": "city", "operator": "equals", "value": "New York" }
75
49
  ],
76
50
  "logic": "and"
77
- }`}],suggestedTemperature:.2,maxTokens:512},le={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},se={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.
78
52
  Given columns and a natural language request, generate sort configuration.
79
53
 
80
54
  Output format:
@@ -92,7 +66,7 @@ Keywords mapping:
92
66
 
93
67
  Request: "{{query}}"
94
68
 
95
- 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},de={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},ce={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.
96
70
 
97
71
  Available field types:
98
72
  - text, email, phone, url, password
@@ -142,7 +116,7 @@ Generate the form configuration:`,variables:[{name:"description",description:"Na
142
116
  { "id": "message", "type": "textarea", "label": "Message", "required": true }
143
117
  ],
144
118
  "layout": { "columns": 1 }
145
- }`}],suggestedTemperature:.5,maxTokens:2048},ue={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},oe={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.
146
120
 
147
121
  Available chart types:
148
122
  - line, area, bar, column
@@ -182,14 +156,14 @@ Available data fields: {{data}}
182
156
  Context: {{context}}
183
157
  {{/if}}
184
158
 
185
- 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},pe={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},le={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.
186
160
 
187
161
  Rules:
188
162
  - Match the existing code style
189
163
  - Use the same language features and patterns
190
164
  - Keep completions concise and focused
191
165
  - Do not repeat existing code
192
- - 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},me={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}}\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},de={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.
193
167
 
194
168
  Output BPMN-compatible JSON:
195
169
  {
@@ -231,7 +205,7 @@ Available roles: {{roles}}
231
205
  Systems involved: {{systems}}
232
206
  {{/if}}
233
207
 
234
- 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},fe={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.
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},ue={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.
235
209
 
236
210
  Available report elements:
237
211
  - header, footer
@@ -269,7 +243,7 @@ Output JSON:
269
243
  Available data sources: {{dataSources}}
270
244
  {{/if}}
271
245
 
272
- 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},he={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.
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},pe={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.
273
247
  Generate a complete theme from brand colors following accessibility guidelines.
274
248
 
275
249
  Rules:
@@ -309,7 +283,7 @@ Output JSON:
309
283
  {{#if industry}}Industry: {{industry}}{{/if}}
310
284
  {{#if style}}Style preference: {{style}}{{/if}}
311
285
 
312
- 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},ke={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).
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},_e={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).
313
287
  Analyze code for accessibility issues and provide fixes.
314
288
 
315
289
  Check for:
@@ -336,7 +310,7 @@ Output JSON:
336
310
  ],
337
311
  "score": 0-100,
338
312
  "summary": "Brief summary of findings"
339
- }`,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},Ne={id:"translation",name:"UI Translation",description:"Translate UI text maintaining context and formatting",category:"translation",system:`You are a professional UI translator.
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},we={id:"translation",name:"UI Translation",description:"Translate UI text maintaining context and formatting",category:"translation",system:`You are a professional UI translator.
340
314
  Translate text while:
341
315
  - Preserving placeholders like {name}, {{count}}, %s
342
316
  - Maintaining ICU message format syntax
@@ -354,7 +328,7 @@ Output JSON:
354
328
 
355
329
  {{texts}}
356
330
 
357
- 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.
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},je={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.
358
332
 
359
333
  Provide:
360
334
  - Key statistics (min, max, mean, median)
@@ -378,7 +352,7 @@ Format output as structured JSON:
378
352
 
379
353
  {{#if context}}Context: {{context}}{{/if}}
380
354
 
381
- 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},be={[oe.id]:oe,[le.id]:le,[de.id]:de,[ue.id]:ue,[pe.id]:pe,[me.id]:me,[fe.id]:fe,[he.id]:he,[ke.id]:ke,[Ne.id]:Ne,[Ce.id]:Ce};function Dr(i){return be[i]}function Br(i){return Object.values(be).filter(a=>a.category===i)}function Fr(){return Object.keys(be)}class $e{constructor(){this.records=new Map}async save(a,r){const t=this.records.get(a)||[];this.records.set(a,[...t,...r])}async load(a,r,t){const n=this.records.get(a)||[];return!r&&!t?n:n.filter(s=>!(r&&s.timestamp<r.getTime()||t&&s.timestamp>t.getTime()))}async clear(a,r){if(!r)this.records.delete(a);else{const t=this.records.get(a)||[];this.records.set(a,t.filter(n=>n.timestamp>=r.getTime()))}}}class wa{constructor(){this.prefix="nice2dev-ai-cost:"}async save(a,r){if(typeof window>"u")return;const t=`${this.prefix}${a}`,s=[...JSON.parse(localStorage.getItem(t)||"[]"),...r],c=Date.now()-30*24*60*60*1e3,d=s.filter(m=>m.timestamp>c);localStorage.setItem(t,JSON.stringify(d))}async load(a,r,t){if(typeof window>"u")return[];const n=`${this.prefix}${a}`,s=JSON.parse(localStorage.getItem(n)||"[]");return!r&&!t?s:s.filter(c=>!(r&&c.timestamp<r.getTime()||t&&c.timestamp>t.getTime()))}async clear(a,r){if(typeof window>"u")return;const t=`${this.prefix}${a}`;if(!r)localStorage.removeItem(t);else{const n=JSON.parse(localStorage.getItem(t)||"[]");localStorage.setItem(t,JSON.stringify(n.filter(s=>s.timestamp>=r.getTime())))}}}class ja{constructor(a,r){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],...r}}async recordUsage(a,r){const t={...r,id:this.generateId(),timestamp:Date.now()};this.pendingRecords.push(t),this.updateCounters(a),this.scheduleFlush(a);const n=await this.getBudgetStatus(a);this.checkAlerts(a,n)}async canMakeRequest(a){const r=await this.getBudgetStatus(a);return r.isOverBudget?{allowed:!1,reason:"Budget exceeded"}:this.budgetConfig.maxRequestsPerMinute&&r.requestsThisMinute>=this.budgetConfig.maxRequestsPerMinute?{allowed:!1,reason:"Rate limit exceeded (per minute)"}:this.budgetConfig.maxRequestsPerDay&&r.requestsToday>=this.budgetConfig.maxRequestsPerDay?{allowed:!1,reason:"Daily request limit exceeded"}:{allowed:!0}}async getBudgetStatus(a){const r=new Date,t=new Date(r.getFullYear(),r.getMonth(),r.getDate()),n=new Date(r.getFullYear(),r.getMonth(),1),s=await this.storage.load(a,t),c=await this.storage.load(a,n),d=s.reduce((T,j)=>T+j.estimatedCost,0),m=c.reduce((T,j)=>T+j.estimatedCost,0),f=this.budgetConfig.dailyBudget||1/0,g=this.budgetConfig.monthlyBudget||1/0,y=f?d/f*100:0,k=g?m/g*100:0,M=[];for(const T of this.budgetConfig.alertThresholds||[])y>=T&&M.push(`Daily budget ${T}% used`),k>=T&&M.push(`Monthly budget ${T}% used`);return{dailyUsed:d,dailyRemaining:Math.max(0,f-d),dailyPercent:y,monthlyUsed:m,monthlyRemaining:Math.max(0,g-m),monthlyPercent:k,requestsToday:s.length,requestsThisMinute:this.getMinuteCount(a),isOverBudget:d>=f||m>=g,alerts:M}}async getUsageStats(a,r,t){const n=await this.storage.load(a,r,t),s={totalRequests:n.length,totalTokens:0,totalPromptTokens:0,totalCompletionTokens:0,totalCost:0,averageLatency:0,errorCount:0,cacheHitRate:0,byModel:{},byFeature:{},byDay:{}};let c=0,d=0;for(const m of n){s.totalTokens+=m.totalTokens,s.totalPromptTokens+=m.promptTokens,s.totalCompletionTokens+=m.completionTokens,s.totalCost+=m.estimatedCost,c+=m.latencyMs,m.error&&s.errorCount++,m.cached&&d++,s.byModel[m.model]||(s.byModel[m.model]={requests:0,tokens:0,cost:0}),s.byModel[m.model].requests++,s.byModel[m.model].tokens+=m.totalTokens,s.byModel[m.model].cost+=m.estimatedCost;const f=m.feature||"unknown";s.byFeature[f]||(s.byFeature[f]={requests:0,tokens:0,cost:0}),s.byFeature[f].requests++,s.byFeature[f].tokens+=m.totalTokens,s.byFeature[f].cost+=m.estimatedCost;const g=new Date(m.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+=m.totalTokens,s.byDay[g].cost+=m.estimatedCost}return n.length>0&&(s.averageLatency=c/n.length,s.cacheHitRate=d/n.length),s}onAlert(a){return this.alertCallbacks.push(a),()=>{const r=this.alertCallbacks.indexOf(a);r>=0&&this.alertCallbacks.splice(r,1)}}setBudgetConfig(a){this.budgetConfig={...this.budgetConfig,...a}}async clearUsage(a,r){await this.storage.clear(a,r)}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}updateCounters(a){const r=Date.now(),t=r-6e4,n=this.minuteCounter.get(a)||[];n.push(r),this.minuteCounter.set(a,n.filter(d=>d>t));const s=new Date().toISOString().split("T")[0],c=`${a}:${s}`;this.dayCounter.set(c,(this.dayCounter.get(c)||0)+1)}getMinuteCount(a){const t=Date.now()-6e4;return(this.minuteCounter.get(a)||[]).filter(s=>s>t).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,r){if(r.alerts.length!==0)for(const t of r.alerts)for(const n of this.alertCallbacks)try{n(t,r)}catch{}}}function Vr(i,a){const r=o.useRef(null),[t,n]=o.useState(null),[s,c]=o.useState(null),[d,m]=o.useState(!0);o.useEffect(()=>{const k=typeof window<"u"?new wa:new $e;r.current=new ja(k,a);const M=r.current.onAlert(T=>{console.warn(`[AI Cost Alert] ${T}`)});return()=>{M()}},[]);const f=o.useCallback(async()=>{if(r.current){m(!0);try{const[k,M]=await Promise.all([r.current.getBudgetStatus(i),r.current.getUsageStats(i)]);n(k),c(M)}finally{m(!1)}}},[i]);o.useEffect(()=>{f()},[f]);const g=o.useCallback(async k=>{r.current&&(await r.current.recordUsage(i,k),await f())},[i,f]),y=o.useCallback(async()=>r.current?r.current.canMakeRequest(i):{allowed:!0},[i]);return{status:t,stats:s,loading:d,recordUsage:g,canMakeRequest:y,refresh:f}}class Jr{constructor(a=100,r=36e5){this.cache=new Map,this.maxSize=a,this.ttl=r}hashRequest(a){const r=JSON.stringify({messages:a.messages,model:a.model,temperature:a.temperature});let t=0;for(let n=0;n<r.length;n++){const s=r.charCodeAt(n);t=(t<<5)-t+s,t=t&t}return t.toString(36)}get(a){const r=this.hashRequest(a),t=this.cache.get(r);return t?Date.now()-t.timestamp>this.ttl?(this.cache.delete(r),null):t.response:null}set(a,r){const t=this.hashRequest(a);if(this.cache.size>=this.maxSize){const n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(t,{request:t,response:r,timestamp:Date.now()})}clear(){this.cache.clear()}}class ka{constructor(a,r){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,...r},this.cache=new Jr(100,this.config.cacheTTL);for(const t of this.config.backupProviders||[])this.backupProviders.push(ne(t));this.config.offlineConfig&&(this.offlineProvider=ne(this.config.offlineConfig))}async chat(a){if(this.isCircuitOpen(this.primaryProvider.type))return this.executeWithFallback(a,new Error("Circuit breaker open"));try{const r=await this.primaryProvider.chat(a);return this.cache.set(a,r),this.resetCircuitBreaker(this.primaryProvider.type),r}catch(r){return this.recordFailure(this.primaryProvider.type),this.executeWithFallback(a,r)}}async executeWithFallback(a,r){var t,n;for(const s of this.config.strategies)try{const c=await this.executeStrategy(s,a,r);if(c)return(n=(t=this.config).onFallback)==null||n.call(t,s,r),c}catch{}throw new Error(`All fallback strategies failed. Original error: ${r.message}`)}async executeStrategy(a,r,t){switch(a){case"retry":return this.retryStrategy(r);case"failover":return this.failoverStrategy(r);case"cache":return this.cacheStrategy(r);case"offline":return this.offlineStrategy(r);case"graceful-degrade":return this.gracefulDegradeStrategy(r,t);case"circuit-breaker":return this.openCircuitBreaker(this.primaryProvider.type),null;default:return null}}async retryStrategy(a){let r=this.config.retryDelay;for(let t=0;t<this.config.maxRetries;t++){await this.delay(r);try{const n=await this.primaryProvider.chat(a);return this.cache.set(a,n),n}catch{r*=this.config.backoffMultiplier}}return null}async failoverStrategy(a){for(const r of this.backupProviders)if(!this.isCircuitOpen(r.type))try{const t=await r.chat(a);return this.cache.set(a,t),t}catch{this.recordFailure(r.type)}return null}cacheStrategy(a){const r=this.cache.get(a);return r?{...r,id:`cached-${r.id}`}:null}async offlineStrategy(a){if(!this.offlineProvider)return null;try{return await this.offlineProvider.chat(a)}catch{return null}}gracefulDegradeStrategy(a,r){const t=[...a.messages].reverse().find(n=>n.role==="user");return{id:`degraded-${Date.now()}`,model:"fallback",choices:[{index:0,message:{role:"assistant",content:this.generateDegradedResponse((t==null?void 0:t.content)||"",r)},finishReason:"stop"}],usage:{promptTokens:0,completionTokens:0,totalTokens:0}}}generateDegradedResponse(a,r){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: ${r.message.substring(0,50)})`}isCircuitOpen(a){const r=this.circuitBreakers.get(a);return r&&r.isOpen?Date.now()-r.lastFailure>this.config.circuitBreakerResetTime?(this.resetCircuitBreaker(a),!1):!0:!1}recordFailure(a){const r=this.circuitBreakers.get(a)||{failures:0,lastFailure:0,isOpen:!1};r.failures++,r.lastFailure=Date.now(),r.failures>=this.config.circuitBreakerThreshold&&(r.isOpen=!0),this.circuitBreakers.set(a,r)}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(r=>setTimeout(r,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[r,t]of this.circuitBreakers)a[r]={...t};return a}async healthCheck(){const a={};a[this.primaryProvider.type]=await this.primaryProvider.healthCheck();for(const r of this.backupProviders)a[`backup-${r.type}`]=await r.healthCheck();return this.offlineProvider&&(a.offline=await this.offlineProvider.healthCheck()),a}}function Na(i,a){const r=ne(i);return new ka(r,a)}function qr(i,a){const r={strategies:["retry","failover","cache","graceful-degrade"],maxRetries:3,retryDelay:1e3,backoffMultiplier:2,backupProviders:a?[a]:[],circuitBreakerThreshold:5,circuitBreakerResetTime:6e4};return typeof window>"u"&&(r.offlineConfig={type:"ollama",model:"llama3"}),Na(i,r)}function Ca(i){const{columns:a,config:r,onFilterGenerated:t,onSortGenerated:n,onError:s}=i,c=ee(),[d,m]=o.useState(!1),[f,g]=o.useState(null),[y,k]=o.useState(null),[M,T]=o.useState([]),j=o.useRef(null),A=r||(c==null?void 0:c.config),_=o.useMemo(()=>a.map(p=>({id:p.id,label:p.label,type:p.type,...p.options?{options:p.options}:{}})),[a]),l=o.useCallback(async p=>{var v;if(!A){const u="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(u),{type:"filter",error:u}}m(!0),g(p);const x=performance.now();(v=j.current)==null||v.abort(),j.current=new AbortController;try{const u=K(A),h=p.toLowerCase(),I=h.includes("sort")||h.includes("order")||h.includes("arrange")||h.includes("by highest")||h.includes("by lowest"),H=h.includes("show")||h.includes("find")||h.includes("filter")||h.includes("where")||h.includes("with")||h.includes("only")||!I,C={type:"combined"};if(H){const z=re(oe,{columns:_,query:p}),O=await u.chat({messages:[{role:"system",content:z.system},{role:"user",content:z.user}],temperature:.2,maxTokens:512}),B=Ur(O);B&&(C.filterConfig=B,C.type="filter",t==null||t(B))}if(I){const z=re(le,{columns:_,query:p}),O=await u.chat({messages:[{role:"system",content:z.system},{role:"user",content:z.user}],temperature:.1,maxTokens:256}),B=Wr(O);B&&(C.sortConfig=B,C.type=C.filterConfig?"combined":"sort",n==null||n(B))}return C.latencyMs=performance.now()-x,k(C),T(z=>[...z.slice(-9),{query:p,result:C}]),C}catch(u){const h=u instanceof Error?u.message:"AI request failed",I={type:"filter",error:h,latencyMs:performance.now()-x};return k(I),s==null||s(h),I}finally{m(!1)}},[A,_,t,n,s]),N=o.useCallback(()=>{g(null),k(null)},[]),w=o.useCallback(()=>{var p;(p=j.current)==null||p.abort(),m(!1)},[]);return o.useEffect(()=>()=>{var p;(p=j.current)==null||p.abort()},[]),{processQuery:l,loading:d,lastQuery:f,lastResult:y,history:M,clearResults:N,abort:w,isConfigured:!!A}}function Ur(i){var a,r,t;try{const n=((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"",c=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,d=JSON.parse(c);if(d.filters&&Array.isArray(d.filters))return{filters:d.filters,logic:d.logic||"and",confidence:d.confidence,explanation:d.explanation}}catch{}return null}function Wr(i){var a,r,t;try{const n=((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"",c=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,d=JSON.parse(c);if(d.sort&&Array.isArray(d.sort))return{sort:d.sort,confidence:d.confidence}}catch{}return null}function Gr({columns:i,config:a,onFilter:r,onSort:t,placeholder:n='Ask AI to filter or sort data... (e.g., "show orders from last week")',showHistory:s=!0,showSuggestions:c=!0,className:d,style:m}){const[f,g]=o.useState(""),[y,k]=o.useState(!1),M=o.useRef(null),{processQuery:T,loading:j,lastResult:A,history:_,isConfigured:l}=Ca({columns:i,config:a,onFilterGenerated:r,onSortGenerated:t}),N=o.useMemo(()=>{if(!c||i.length===0)return[];const u=[],h=i.filter(z=>z.type==="string");h.length>0&&u.push(`Show ${h[0].label}s containing "example"`);const I=i.filter(z=>z.type==="number");I.length>0&&(u.push(`${I[0].label} greater than 100`),u.push(`Sort by highest ${I[0].label}`));const H=i.filter(z=>z.type==="date");H.length>0&&(u.push(`${H[0].label} in the last 7 days`),u.push(`Sort by newest ${H[0].label}`));const C=i.filter(z=>{var O;return z.type==="enum"&&((O=z.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)},[i,c]),w=async()=>{!f.trim()||j||(await T(f.trim()),k(!1))},p=u=>{u.key==="Enter"?(u.preventDefault(),w()):u.key==="Escape"&&k(!1)},x=u=>{var h;g(u),k(!1),(h=M.current)==null||h.focus()},v=u=>{g(u),k(!1),T(u)};return l?e.jsxs("div",{className:`nice-datagrid-ai ${d||""}`,style:m,children:[e.jsxs("div",{className:"nice-datagrid-ai__input-wrapper",children:[e.jsx("span",{className:"nice-datagrid-ai__icon",children:e.jsx($,{name:"search",size:16})}),e.jsx("input",{ref:M,type:"text",value:f,onChange:u=>g(u.target.value),onKeyDown:p,onFocus:()=>k(!0),onBlur:()=>setTimeout(()=>k(!1),200),placeholder:n,className:"nice-datagrid-ai__input",disabled:j,"aria-label":"AI query input"}),j?e.jsx("span",{className:"nice-datagrid-ai__spinner"}):e.jsx("button",{type:"button",onClick:w,className:"nice-datagrid-ai__submit",disabled:!f.trim(),"aria-label":"Submit query",children:e.jsx($,{name:"send",size:16})})]}),y&&(N.length>0||s&&_.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:()=>x(u),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx($,{name:"lightbulb",size:14})}),u]},h))]}),s&&_.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:"Recent"}),_.slice(-5).reverse().map((u,h)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>v(u.query),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx($,{name:"clock",size:14})}),u.query,u.result.error&&e.jsx("span",{className:"nice-datagrid-ai__item-error",children:e.jsx($,{name:"warning",size:14})})]},h))]})]}),A&&!A.error&&e.jsxs("div",{className:"nice-datagrid-ai__result",children:[A.filterConfig&&e.jsxs("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--filter",children:[A.filterConfig.filters.length," filter",A.filterConfig.filters.length!==1?"s":""," applied"]}),A.sortConfig&&e.jsxs("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--sort",children:["Sorted by ",A.sortConfig.sort.map(u=>u.column).join(", ")]}),A.latencyMs&&e.jsxs("span",{className:"nice-datagrid-ai__latency",children:[Math.round(A.latencyMs),"ms"]})]}),(A==null?void 0:A.error)&&e.jsx("div",{className:"nice-datagrid-ai__error",children:A.error}),e.jsx("style",{children:`
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={[ne.id]:ne,[se.id]:se,[ce.id]:ce,[oe.id]:oe,[le.id]:le,[de.id]:de,[ue.id]:ue,[pe.id]:pe,[_e.id]:_e,[we.id]:we,[je.id]:je};function ci(t){return ge[t]}function oi(t){return Object.values(ge).filter(a=>a.category===t)}function li(){return Object.keys(ge)}class Ie{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 oa{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(m=>m.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 la{constructor(a,i){this.pendingRecords=[],this.flushTimer=null,this.alertCallbacks=[],this.minuteCounter=new Map,this.dayCounter=new Map,this.storage=a||new Ie,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((R,j)=>R+j.estimatedCost,0),m=c.reduce((R,j)=>R+j.estimatedCost,0),g=this.budgetConfig.dailyBudget||1/0,x=this.budgetConfig.monthlyBudget||1/0,w=g?l/g*100:0,N=x?m/x*100:0,S=[];for(const R of this.budgetConfig.alertThresholds||[])w>=R&&S.push(`Daily budget ${R}% used`),N>=R&&S.push(`Monthly budget ${R}% used`);return{dailyUsed:l,dailyRemaining:Math.max(0,g-l),dailyPercent:w,monthlyUsed:m,monthlyRemaining:Math.max(0,x-m),monthlyPercent:N,requestsToday:s.length,requestsThisMinute:this.getMinuteCount(a),isOverBudget:l>=g||m>=x,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 m of n){s.totalTokens+=m.totalTokens,s.totalPromptTokens+=m.promptTokens,s.totalCompletionTokens+=m.completionTokens,s.totalCost+=m.estimatedCost,c+=m.latencyMs,m.error&&s.errorCount++,m.cached&&l++,s.byModel[m.model]||(s.byModel[m.model]={requests:0,tokens:0,cost:0}),s.byModel[m.model].requests++,s.byModel[m.model].tokens+=m.totalTokens,s.byModel[m.model].cost+=m.estimatedCost;const g=m.feature||"unknown";s.byFeature[g]||(s.byFeature[g]={requests:0,tokens:0,cost:0}),s.byFeature[g].requests++,s.byFeature[g].tokens+=m.totalTokens,s.byFeature[g].cost+=m.estimatedCost;const x=new Date(m.timestamp).toISOString().split("T")[0];s.byDay[x]||(s.byDay[x]={requests:0,tokens:0,cost:0}),s.byDay[x].requests++,s.byDay[x].tokens+=m.totalTokens,s.byDay[x].cost+=m.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 di(t,a){const i=d.useRef(null),[r,n]=d.useState(null),[s,c]=d.useState(null),[l,m]=d.useState(!0);d.useEffect(()=>{const N=typeof window<"u"?new oa:new Ie;i.current=new la(N,a);const S=i.current.onAlert(R=>{console.warn(`[AI Cost Alert] ${R}`)});return()=>{S()}},[]);const g=d.useCallback(async()=>{if(i.current){m(!0);try{const[N,S]=await Promise.all([i.current.getBudgetStatus(t),i.current.getUsageStats(t)]);n(N),c(S)}finally{m(!1)}}},[t]);d.useEffect(()=>{g()},[g]);const x=d.useCallback(async N=>{i.current&&(await i.current.recordUsage(t,N),await g())},[t,g]),w=d.useCallback(async()=>i.current?i.current.canMakeRequest(t):{allowed:!0},[t]);return{status:r,stats:s,loading:l,recordUsage:x,canMakeRequest:w,refresh:g}}class ui{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 da{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 ui(100,this.config.cacheTTL);for(const r of this.config.backupProviders||[])this.backupProviders.push(ie(r));this.config.offlineConfig&&(this.offlineProvider=ie(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 ua(t,a){const i=ie(t);return new da(i,a)}function pi(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"}),ua(t,i)}function pa(t){const{columns:a,config:i,onFilterGenerated:r,onSortGenerated:n,onError:s}=t,c=Q(),[l,m]=d.useState(!1),[g,x]=d.useState(null),[w,N]=d.useState(null),[S,R]=d.useState([]),j=d.useRef(null),I=i||(c==null?void 0:c.config),_=d.useMemo(()=>a.map(p=>({id:p.id,label:p.label,type:p.type,...p.options?{options:p.options}:{}})),[a]),o=d.useCallback(async p=>{var v;if(!I){const u="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(u),{type:"filter",error:u}}m(!0),x(p);const b=performance.now();(v=j.current)==null||v.abort(),j.current=new AbortController;try{const u=V(I),h=p.toLowerCase(),$=h.includes("sort")||h.includes("order")||h.includes("arrange")||h.includes("by highest")||h.includes("by lowest"),E=h.includes("show")||h.includes("find")||h.includes("filter")||h.includes("where")||h.includes("with")||h.includes("only")||!$,C={type:"combined"};if(E){const A=ee(ne,{columns:_,query:p}),O=await u.chat({messages:[{role:"system",content:A.system},{role:"user",content:A.user}],temperature:.2,maxTokens:512}),B=mi(O);B&&(C.filterConfig=B,C.type="filter",r==null||r(B))}if($){const A=ee(se,{columns:_,query:p}),O=await u.chat({messages:[{role:"system",content:A.system},{role:"user",content:A.user}],temperature:.1,maxTokens:256}),B=hi(O);B&&(C.sortConfig=B,C.type=C.filterConfig?"combined":"sort",n==null||n(B))}return C.latencyMs=performance.now()-b,N(C),R(A=>[...A.slice(-9),{query:p,result:C}]),C}catch(u){const h=u instanceof Error?u.message:"AI request failed",$={type:"filter",error:h,latencyMs:performance.now()-b};return N($),s==null||s(h),$}finally{m(!1)}},[I,_,r,n,s]),k=d.useCallback(()=>{x(null),N(null)},[]),y=d.useCallback(()=>{var p;(p=j.current)==null||p.abort(),m(!1)},[]);return d.useEffect(()=>()=>{var p;(p=j.current)==null||p.abort()},[]),{processQuery:o,loading:l,lastQuery:g,lastResult:w,history:S,clearResults:k,abort:y,isConfigured:!!I}}function mi(t){var a,i,r;try{const n=((i=(a=t.choices[0])==null?void 0:a.message)==null?void 0:i.content)||"",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 hi(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 gi({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:m}){const[g,x]=d.useState(""),[w,N]=d.useState(!1),S=d.useRef(null),{processQuery:R,loading:j,lastResult:I,history:_,isConfigured:o}=pa({columns:t,config:a,onFilterGenerated:i,onSortGenerated:r}),k=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 E=t.filter(A=>A.type==="date");E.length>0&&(u.push(`${E[0].label} in the last 7 days`),u.push(`Sort by newest ${E[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]),y=async()=>{!g.trim()||j||(await R(g.trim()),N(!1))},p=u=>{u.key==="Enter"?(u.preventDefault(),y()):u.key==="Escape"&&N(!1)},b=u=>{var h;x(u),N(!1),(h=S.current)==null||h.focus()},v=u=>{x(u),N(!1),R(u)};return o?e.jsxs("div",{className:`nice-datagrid-ai ${l||""}`,style:m,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:g,onChange:u=>x(u.target.value),onKeyDown:p,onFocus:()=>N(!0),onBlur:()=>setTimeout(()=>N(!1),200),placeholder:n,className:"nice-datagrid-ai__input",disabled:j,"aria-label":"AI query input"}),j?e.jsx("span",{className:"nice-datagrid-ai__spinner"}):e.jsx("button",{type:"button",onClick:y,className:"nice-datagrid-ai__submit",disabled:!g.trim(),"aria-label":"Submit query",children:e.jsx(L.NiceIcon,{name:"send",size:16})})]}),w&&(k.length>0||s&&_.length>0)&&e.jsxs("div",{className:"nice-datagrid-ai__dropdown",children:[c&&k.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:"Suggestions"}),k.map((u,h)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>b(u),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:e.jsx(L.NiceIcon,{name:"lightbulb",size:14})}),u]},h))]}),s&&_.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:"Recent"}),_.slice(-5).reverse().map((u,h)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>v(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:`
382
356
  .nice-datagrid-ai {
383
357
  position: relative;
384
358
  font-family: var(--nice-font-family, system-ui, sans-serif);
@@ -560,13 +534,13 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
560
534
  border-radius: var(--nice-radius-sm, 4px);
561
535
  font-size: 13px;
562
536
  }
563
- `})]}):e.jsx("div",{className:`nice-datagrid-ai nice-datagrid-ai--disabled ${d||""}`,style:m,children:e.jsx("input",{type:"text",placeholder:"AI not configured",disabled:!0,className:"nice-datagrid-ai__input"})})}function Ma(i={}){const{config:a,schema:r,context:t,onFormGenerated:n,onError:s}=i,c=ee(),[d,m]=o.useState(!1),[f,g]=o.useState(null),[y,k]=o.useState(null),[M,T]=o.useState([]),j=o.useRef(null),A=a||(c==null?void 0:c.config),_=o.useCallback(async p=>{var v,u,h;if(!A){const I="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(I),{error:I}}m(!0),g(p);const x=performance.now();(v=j.current)==null||v.abort(),j.current=new AbortController;try{const I=K(A),H=re(de,{description:p,schema:r?JSON.stringify(r,null,2):void 0,context:t}),C=await I.chat({messages:[{role:"system",content:H.system},{role:"user",content:H.user}],temperature:.5,maxTokens:2048}),z=Kr(C),O={config:z||void 0,rawResponse:(h=(u=C.choices[0])==null?void 0:u.message)==null?void 0:h.content,latencyMs:performance.now()-x,error:z?void 0:"Failed to parse form configuration"};return z&&(n==null||n(z)),k(O),T(B=>[...B.slice(-9),{description:p,result:O}]),O}catch(I){const H=I instanceof Error?I.message:"AI request failed",C={error:H,latencyMs:performance.now()-x};return k(C),s==null||s(H),C}finally{m(!1)}},[A,r,t,n,s]),l=o.useCallback(async p=>{if(!(y!=null&&y.config))return{error:"No form to refine. Generate a form first."};const x=`
537
+ `})]}):e.jsx("div",{className:`nice-datagrid-ai nice-datagrid-ai--disabled ${l||""}`,style:m,children:e.jsx("input",{type:"text",placeholder:"AI not configured",disabled:!0,className:"nice-datagrid-ai__input"})})}function ma(t={}){const{config:a,schema:i,context:r,onFormGenerated:n,onError:s}=t,c=Q(),[l,m]=d.useState(!1),[g,x]=d.useState(null),[w,N]=d.useState(null),[S,R]=d.useState([]),j=d.useRef(null),I=a||(c==null?void 0:c.config),_=d.useCallback(async p=>{var v,u,h;if(!I){const $="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s($),{error:$}}m(!0),x(p);const b=performance.now();(v=j.current)==null||v.abort(),j.current=new AbortController;try{const $=V(I),E=ee(ce,{description:p,schema:i?JSON.stringify(i,null,2):void 0,context:r}),C=await $.chat({messages:[{role:"system",content:E.system},{role:"user",content:E.user}],temperature:.5,maxTokens:2048}),A=fi(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()-b,error:A?void 0:"Failed to parse form configuration"};return A&&(n==null||n(A)),N(O),R(B=>[...B.slice(-9),{description:p,result:O}]),O}catch($){const E=$ instanceof Error?$.message:"AI request failed",C={error:E,latencyMs:performance.now()-b};return N(C),s==null||s(E),C}finally{m(!1)}},[I,i,r,n,s]),o=d.useCallback(async p=>{if(!(w!=null&&w.config))return{error:"No form to refine. Generate a form first."};const b=`
564
538
  Modify this existing form based on the following instructions:
565
539
 
566
- Current form: ${JSON.stringify(y.config,null,2)}
540
+ Current form: ${JSON.stringify(w.config,null,2)}
567
541
 
568
542
  Instructions: ${p}
569
- `;return _(x)},[y,_]),N=o.useCallback(()=>{g(null),k(null)},[]),w=o.useCallback(()=>{var p;(p=j.current)==null||p.abort(),m(!1)},[]);return o.useEffect(()=>()=>{var p;(p=j.current)==null||p.abort()},[]),{generateForm:_,refineForm:l,loading:d,lastDescription:f,lastResult:y,history:M,clearResults:N,abort:w,isConfigured:!!A}}function Kr(i){var a,r,t;try{const n=((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"",c=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,d=JSON.parse(c);if(d.fields&&Array.isArray(d.fields))return{title:d.title,description:d.description,fields:d.fields,layout:d.layout,submitLabel:d.submitLabel,validation:d.validation}}catch{}return null}function Yr({config:i,schema:a,context:r,onGenerate:t,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:d,style:m,renderForm:f}){const[g,y]=o.useState(""),[k,M]=o.useState(!1),T=o.useRef(null),{generateForm:j,loading:A,lastResult:_,isConfigured:l}=Ma({config:i,schema:a,context:r,onFormGenerated:t}),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"],w=async()=>{!g.trim()||A||await j(g.trim())},p=u=>{var h;y(u),M(!1),(h=T.current)==null||h.focus()},x=u=>{u.key==="Enter"&&(u.ctrlKey||u.metaKey)&&(u.preventDefault(),w())},v=u=>{y(u.target.value),u.target.style.height="auto",u.target.style.height=Math.min(u.target.scrollHeight,200)+"px"};return l?e.jsxs("div",{className:`nice-form-builder-ai ${d||""}`,style:m,children:[e.jsxs("div",{className:"nice-form-builder-ai__input-section",children:[e.jsxs("label",{className:"nice-form-builder-ai__label",children:[e.jsx("span",{className:"nice-form-builder-ai__label-icon",children:e.jsx($,{name:"wand",size:16})}),"Describe your form"]}),e.jsxs("div",{className:"nice-form-builder-ai__input-wrapper",children:[e.jsx("textarea",{ref:T,value:g,onChange:v,onKeyDown:x,placeholder:n,className:"nice-form-builder-ai__textarea",disabled:A,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:"Examples"}),k&&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:()=>p(u),children:u},h))})]}),e.jsx("button",{type:"button",onClick:w,disabled:!g.trim()||A,className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--primary",children:A?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"nice-form-builder-ai__spinner"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx($,{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"]})]}),_&&e.jsx("div",{className:"nice-form-builder-ai__result",children:_.error?e.jsxs("div",{className:"nice-form-builder-ai__error",children:[e.jsx("strong",{children:"Error:"})," ",_.error]}):_.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: ",_.config.title||"Untitled"]}),_.latencyMs&&e.jsxs("span",{className:"nice-form-builder-ai__latency",children:[Math.round(_.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>t==null?void 0:t(_.config),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--success",children:"Use This Form"})]}),_.config.description&&e.jsx("p",{className:"nice-form-builder-ai__result-description",children:_.config.description}),c&&e.jsx("div",{className:"nice-form-builder-ai__preview",children:f?f(_.config):e.jsx(Xr,{config:_.config})}),e.jsxs("details",{className:"nice-form-builder-ai__json",children:[e.jsx("summary",{children:"View JSON Configuration"}),e.jsx("pre",{children:JSON.stringify(_.config,null,2)})]})]})}),e.jsx("style",{children:`
543
+ `;return _(b)},[w,_]),k=d.useCallback(()=>{x(null),N(null)},[]),y=d.useCallback(()=>{var p;(p=j.current)==null||p.abort(),m(!1)},[]);return d.useEffect(()=>()=>{var p;(p=j.current)==null||p.abort()},[]),{generateForm:_,refineForm:o,loading:l,lastDescription:g,lastResult:w,history:S,clearResults:k,abort:y,isConfigured:!!I}}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.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 xi({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:m,renderForm:g}){const[x,w]=d.useState(""),[N,S]=d.useState(!1),R=d.useRef(null),{generateForm:j,loading:I,lastResult:_,isConfigured:o}=ma({config:t,schema:a,context:i,onFormGenerated:r}),k=["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"],y=async()=>{!x.trim()||I||await j(x.trim())},p=u=>{var h;w(u),S(!1),(h=R.current)==null||h.focus()},b=u=>{u.key==="Enter"&&(u.ctrlKey||u.metaKey)&&(u.preventDefault(),y())},v=u=>{w(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:m,children:[e.jsxs("div",{className:"nice-form-builder-ai__input-section",children:[e.jsxs("label",{className:"nice-form-builder-ai__label",children:[e.jsx("span",{className:"nice-form-builder-ai__label-icon",children:e.jsx(L.NiceIcon,{name:"wand",size:16})}),"Describe your form"]}),e.jsxs("div",{className:"nice-form-builder-ai__input-wrapper",children:[e.jsx("textarea",{ref:R,value:x,onChange:v,onKeyDown:b,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(!N),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--secondary",children:"Examples"}),N&&e.jsx("div",{className:"nice-form-builder-ai__dropdown",children:k.map((u,h)=>e.jsx("button",{type:"button",className:"nice-form-builder-ai__dropdown-item",onClick:()=>p(u),children:u},h))})]}),e.jsx("button",{type:"button",onClick:y,disabled:!x.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"]})]}),_&&e.jsx("div",{className:"nice-form-builder-ai__result",children:_.error?e.jsxs("div",{className:"nice-form-builder-ai__error",children:[e.jsx("strong",{children:"Error:"})," ",_.error]}):_.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: ",_.config.title||"Untitled"]}),_.latencyMs&&e.jsxs("span",{className:"nice-form-builder-ai__latency",children:[Math.round(_.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(_.config),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--success",children:"Use This Form"})]}),_.config.description&&e.jsx("p",{className:"nice-form-builder-ai__result-description",children:_.config.description}),c&&e.jsx("div",{className:"nice-form-builder-ai__preview",children:g?g(_.config):e.jsx(bi,{config:_.config})}),e.jsxs("details",{className:"nice-form-builder-ai__json",children:[e.jsx("summary",{children:"View JSON Configuration"}),e.jsx("pre",{children:JSON.stringify(_.config,null,2)})]})]})}),e.jsx("style",{children:`
570
544
  .nice-form-builder-ai {
571
545
  font-family: var(--nice-font-family, system-ui, sans-serif);
572
546
  }
@@ -787,7 +761,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
787
761
  color: var(--nice-error, #c62828);
788
762
  border-radius: var(--nice-radius-md, 6px);
789
763
  }
790
- `})]}):e.jsx("div",{className:`nice-form-builder-ai nice-form-builder-ai--disabled ${d||""}`,style:m,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function Xr({config:i}){var t,n;const a=s=>{var d,m;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,"..."]}),(d=s.options)==null?void 0:d.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:(m=s.options)==null?void 0:m.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"})}},r=((t=i.layout)==null?void 0:t.columns)||1;return e.jsxs("form",{className:"nice-form-preview",style:{"--columns":r},children:[(n=i.layout)!=null&&n.sections?i.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(d=>{const m=i.fields.find(f=>f.id===d);return m?e.jsxs("div",{className:"nice-form-preview__field",children:[m.type!=="checkbox"&&e.jsxs("label",{className:"nice-form-preview__label",children:[m.label,m.required&&e.jsx("span",{className:"nice-form-preview__required",children:"*"})]}),a(m)]},m.id):null})})]},c)):e.jsx("div",{className:"nice-form-preview__grid",children:i.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:i.submitLabel||"Submit"})}),e.jsx("style",{children:`
764
+ `})]}):e.jsx("div",{className:`nice-form-builder-ai nice-form-builder-ai--disabled ${l||""}`,style:m,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function bi({config:t}){var r,n;const a=s=>{var l,m;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(g=>e.jsx("option",{value:g.value,children:g.label},g.value))]});case"radio":return e.jsx("div",{className:"nice-form-preview__radio-group",children:(m=s.options)==null?void 0:m.map(g=>e.jsxs("label",{className:"nice-form-preview__radio",children:[e.jsx("input",{type:"radio",name:s.id,value:g.value,disabled:!0}),g.label]},g.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 m=t.fields.find(g=>g.id===l);return m?e.jsxs("div",{className:"nice-form-preview__field",children:[m.type!=="checkbox"&&e.jsxs("label",{className:"nice-form-preview__label",children:[m.label,m.required&&e.jsx("span",{className:"nice-form-preview__required",children:"*"})]}),a(m)]},m.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:`
791
765
  .nice-form-preview {
792
766
  --columns: 1;
793
767
  }
@@ -892,7 +866,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
892
866
  cursor: not-allowed;
893
867
  opacity: 0.7;
894
868
  }
895
- `})]})}function Sa(i={}){const{config:a,dataFields:r,context:t,onChartGenerated:n,onError:s}=i,c=ee(),[d,m]=o.useState(!1),[f,g]=o.useState(null),[y,k]=o.useState(null),[M,T]=o.useState([]),j=o.useRef(null),A=a||(c==null?void 0:c.config),_=o.useMemo(()=>{if(r)return r.map(x=>{var v;return{name:x.name,type:x.type,label:x.label||x.name,...(v=x.sampleValues)!=null&&v.length?{samples:x.sampleValues.slice(0,3)}:{}}})},[r]),l=o.useCallback(async x=>{var u,h,I;if(!A){const H="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(H),{error:H}}m(!0),g(x);const v=performance.now();(u=j.current)==null||u.abort(),j.current=new AbortController;try{const H=K(A),C=re(ue,{request:x,data:_?JSON.stringify(_,null,2):void 0,context:t}),z=await H.chat({messages:[{role:"system",content:C.system},{role:"user",content:C.user}],temperature:.4,maxTokens:1024}),O=Zr(z),B={config:O||void 0,rawResponse:(I=(h=z.choices[0])==null?void 0:h.message)==null?void 0:I.content,latencyMs:performance.now()-v,error:O?void 0:"Failed to parse chart configuration",suggestions:Qr(O)};return O&&(n==null||n(O)),k(B),T(b=>[...b.slice(-9),{request:x,result:B}]),B}catch(H){const C=H instanceof Error?H.message:"AI request failed",z={error:C,latencyMs:performance.now()-v};return k(z),s==null||s(C),z}finally{m(!1)}},[A,_,t,n,s]),N=o.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]),w=o.useCallback(()=>{g(null),k(null)},[]),p=o.useCallback(()=>{var x;(x=j.current)==null||x.abort(),m(!1)},[]);return o.useEffect(()=>()=>{var x;(x=j.current)==null||x.abort()},[]),{generateChart:l,suggestAlternatives:N,loading:d,lastRequest:f,lastResult:y,history:M,clearResults:w,abort:p,isConfigured:!!A}}function Zr(i){var a,r,t;try{const n=((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"",c=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,d=JSON.parse(c);if(d.type)return{type:d.type,title:d.title,subtitle:d.subtitle,data:d.data||{},xAxis:d.xAxis,yAxis:d.yAxis,options:d.options}}catch{}return null}function Qr(i){var r;if(!i)return[];const a=[];return(i.type==="line"||i.type==="bar")&&(a.push("Add trend line for forecasting"),a.push("Stack series for comparison")),(i.type==="pie"||i.type==="donut")&&(a.push("Convert to bar chart for better comparison"),a.push("Add data labels for percentages")),(r=i.options)!=null&&r.animation||a.push("Enable animations for better UX"),a.slice(0,3)}function ei({config:i,dataFields:a,context:r,onGenerate:t,placeholder:n='Describe the chart you want... (e.g., "Show monthly sales as a line chart")',showTypeSelector:s=!0,showPreview:c=!0,className:d,style:m,renderChart:f}){const[g,y]=o.useState(""),[k,M]=o.useState(null),T=o.useRef(null),{generateChart:j,suggestAlternatives:A,loading:_,lastResult:l,isConfigured:N}=Sa({config:i,dataFields:a,context:r,onChartGenerated:t}),w=[{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"}],p=async()=>{if(!g.trim()||_)return;const h=k?`Create a ${k} chart: ${g}`:g;await j(h)},x=h=>{h.key==="Enter"&&(h.preventDefault(),p())},v=h=>{M(k===h?null:h)},u=async h=>{if(!(l!=null&&l.config))return;const I={...l.config,type:h};t==null||t(I)};return N?e.jsxs("div",{className:`nice-chart-ai ${d||""}`,style:m,children:[s&&e.jsx("div",{className:"nice-chart-ai__types",children:w.map(({type:h,icon:I,label:H})=>e.jsxs("button",{type:"button",className:`nice-chart-ai__type ${k===h?"nice-chart-ai__type--selected":""}`,onClick:()=>v(h),title:H,children:[e.jsx("span",{className:"nice-chart-ai__type-icon",children:e.jsx($,{name:I,size:20})}),e.jsx("span",{className:"nice-chart-ai__type-label",children:H})]},h))}),e.jsxs("div",{className:"nice-chart-ai__input-wrapper",children:[e.jsx("span",{className:"nice-chart-ai__icon",children:e.jsx($,{name:"bar-chart",size:18})}),e.jsx("input",{ref:T,type:"text",value:g,onChange:h=>y(h.target.value),onKeyDown:x,placeholder:n,className:"nice-chart-ai__input",disabled:_}),_?e.jsx("span",{className:"nice-chart-ai__spinner"}):e.jsx("button",{type:"button",onClick:p,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))]}),l&&e.jsx("div",{className:"nice-chart-ai__result",children:l.error?e.jsx("div",{className:"nice-chart-ai__error",children:l.error}):l.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 h=(I=w.find(H=>H.type===l.config.type))==null?void 0:I.icon;return h?e.jsx($,{name:h,size:16}):null})(),l.config.type.charAt(0).toUpperCase()+l.config.type.slice(1)," ","Chart"]}),l.config.title&&e.jsx("span",{className:"nice-chart-ai__chart-title",children:l.config.title})]}),l.latencyMs&&e.jsxs("span",{className:"nice-chart-ai__latency",children:[Math.round(l.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>t==null?void 0:t(l.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:"}),w.filter(h=>h.type!==l.config.type).slice(0,4).map(({type:h,icon:I})=>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($,{name:I,size:16})},h))]}),c&&e.jsx("div",{className:"nice-chart-ai__preview",children:f?f(l.config):e.jsx(ai,{config:l.config})}),e.jsxs("details",{className:"nice-chart-ai__json",children:[e.jsx("summary",{children:"View Configuration"}),e.jsx("pre",{children:JSON.stringify(l.config,null,2)})]})]})}),e.jsx("style",{children:`
869
+ `})]})}function ha(t={}){const{config:a,dataFields:i,context:r,onChartGenerated:n,onError:s}=t,c=Q(),[l,m]=d.useState(!1),[g,x]=d.useState(null),[w,N]=d.useState(null),[S,R]=d.useState([]),j=d.useRef(null),I=a||(c==null?void 0:c.config),_=d.useMemo(()=>{if(i)return i.map(b=>{var v;return{name:b.name,type:b.type,label:b.label||b.name,...(v=b.sampleValues)!=null&&v.length?{samples:b.sampleValues.slice(0,3)}:{}}})},[i]),o=d.useCallback(async b=>{var u,h,$;if(!I){const E="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(E),{error:E}}m(!0),x(b);const v=performance.now();(u=j.current)==null||u.abort(),j.current=new AbortController;try{const E=V(I),C=ee(oe,{request:b,data:_?JSON.stringify(_,null,2):void 0,context:r}),A=await E.chat({messages:[{role:"system",content:C.system},{role:"user",content:C.user}],temperature:.4,maxTokens:1024}),O=vi(A),B={config:O||void 0,rawResponse:($=(h=A.choices[0])==null?void 0:h.message)==null?void 0:$.content,latencyMs:performance.now()-v,error:O?void 0:"Failed to parse chart configuration",suggestions:yi(O)};return O&&(n==null||n(O)),N(B),R(f=>[...f.slice(-9),{request:b,result:B}]),B}catch(E){const C=E instanceof Error?E.message:"AI request failed",A={error:C,latencyMs:performance.now()-v};return N(A),s==null||s(C),A}finally{m(!1)}},[I,_,r,n,s]),k=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]),y=d.useCallback(()=>{x(null),N(null)},[]),p=d.useCallback(()=>{var b;(b=j.current)==null||b.abort(),m(!1)},[]);return d.useEffect(()=>()=>{var b;(b=j.current)==null||b.abort()},[]),{generateChart:o,suggestAlternatives:k,loading:l,lastRequest:g,lastResult:w,history:S,clearResults:y,abort:p,isConfigured:!!I}}function vi(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 yi(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 _i({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:m,renderChart:g}){const[x,w]=d.useState(""),[N,S]=d.useState(null),R=d.useRef(null),{generateChart:j,suggestAlternatives:I,loading:_,lastResult:o,isConfigured:k}=ha({config:t,dataFields:a,context:i,onChartGenerated:r}),y=[{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"}],p=async()=>{if(!x.trim()||_)return;const h=N?`Create a ${N} chart: ${x}`:x;await j(h)},b=h=>{h.key==="Enter"&&(h.preventDefault(),p())},v=h=>{S(N===h?null:h)},u=async h=>{if(!(o!=null&&o.config))return;const $={...o.config,type:h};r==null||r($)};return k?e.jsxs("div",{className:`nice-chart-ai ${l||""}`,style:m,children:[s&&e.jsx("div",{className:"nice-chart-ai__types",children:y.map(({type:h,icon:$,label:E})=>e.jsxs("button",{type:"button",className:`nice-chart-ai__type ${N===h?"nice-chart-ai__type--selected":""}`,onClick:()=>v(h),title:E,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:E})]},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:R,type:"text",value:x,onChange:h=>w(h.target.value),onKeyDown:b,placeholder:n,className:"nice-chart-ai__input",disabled:_}),_?e.jsx("span",{className:"nice-chart-ai__spinner"}):e.jsx("button",{type:"button",onClick:p,className:"nice-chart-ai__submit",disabled:!x.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=($=y.find(E=>E.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:"}),y.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:g?g(o.config):e.jsx(wi,{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:`
896
870
  .nice-chart-ai {
897
871
  font-family: var(--nice-font-family, system-ui, sans-serif);
898
872
  }
@@ -1136,7 +1110,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
1136
1110
  color: var(--nice-error, #c62828);
1137
1111
  border-radius: var(--nice-radius-md, 6px);
1138
1112
  }
1139
- `})]}):e.jsx("div",{className:`nice-chart-ai nice-chart-ai--disabled ${d||""}`,style:m,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function ai({config:i}){var r;const a=()=>{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-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 t=i.type==="donut"?35:40,n=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:t,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: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($,{name:"bar-chart",size:32})}),e.jsxs("span",{children:[i.type.charAt(0).toUpperCase()+i.type.slice(1)," Chart"]})]})}};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:a()}),((r=i.options)==null?void 0:r.legend)&&e.jsxs("div",{className:"nice-chart-preview__legend",children:[e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"var(--nice-success, #4caf50)"}}),"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:`
1113
+ `})]}):e.jsx("div",{className:`nice-chart-ai nice-chart-ai--disabled ${l||""}`,style:m,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function wi({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-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:`
1140
1114
  .nice-chart-preview {
1141
1115
  text-align: center;
1142
1116
  }
@@ -1197,11 +1171,11 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
1197
1171
  height: 12px;
1198
1172
  border-radius: var(--nice-radius-sm, 2px);
1199
1173
  }
1200
- `})]})}function za(i={}){const{config:a,language:r="typescript",context:t,maxSuggestions:n=3,debounceMs:s=300,onSuggestion:c,onError:d}=i,m=ee(),[f,g]=o.useState(!1),[y,k]=o.useState([]),[M,T]=o.useState(-1),j=o.useRef(null),A=o.useRef(null),_=a||(m==null?void 0:m.config),l=o.useCallback(async(C,z)=>{var B,b,R;if(!_)return{suggestions:[],error:"AI not configured"};g(!0),(B=j.current)==null||B.abort(),j.current=new AbortController;const O=performance.now();try{const q=K(_),U=C.split(`
1201
- `),P=U[z.line]||"",V=P.substring(0,z.column),J=P.substring(z.column),W=U.slice(Math.max(0,z.line-20),z.line).join(`
1202
- `),G=U.slice(z.line+1,z.line+10).join(`
1203
- `),Z=re(pe,{language:r,code_context:W,prefix:V,suffix:J,context_after:G,context:t}),ie=await q.chat({messages:[{role:"system",content:Z.system},{role:"user",content:Z.user}],temperature:.2,maxTokens:512}),ae=ri(ie,z,n),S={suggestions:ae,rawResponse:(R=(b=ie.choices[0])==null?void 0:b.message)==null?void 0:R.content,latencyMs:performance.now()-O};return k(ae),T(ae.length>0?0:-1),c==null||c(ae),S}catch(q){const U=q instanceof Error?q.message:"Completion failed";return d==null||d(U),{suggestions:[],error:U,latencyMs:performance.now()-O}}finally{g(!1)}},[_,r,t,n,c,d]),N=o.useCallback((C,z)=>{A.current&&clearTimeout(A.current),A.current=setTimeout(()=>{l(C,z)},s)},[l,s]),w=o.useCallback(async C=>{if(!_)return null;g(!0);try{const O=await K(_).chat({messages:[{role:"system",content:`You are a code explanation assistant. Explain the following ${r} 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 ii(O)}catch{return null}finally{g(!1)}},[_,r]),p=o.useCallback(async C=>{if(!_)return[];g(!0);try{const O=await K(_).chat({messages:[{role:"system",content:`You are a code refactoring assistant. Analyze the following ${r} 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 ti(O)}catch{return[]}finally{g(!1)}},[_,r]),x=o.useCallback(async(C,z)=>{var O,B;if(!_)return null;g(!0);try{const b=K(_),R=z||ni(r);return((B=(O=(await b.chat({messages:[{role:"system",content:`You are a testing expert. Generate comprehensive unit tests for the following ${r} code using ${R}. 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)}},[_,r]),v=o.useCallback(async(C,z)=>{var O,B;if(!_)return null;g(!0);try{const b=K(_),R=z||si(r);return((B=(O=(await b.chat({messages:[{role:"system",content:`Generate ${R} documentation for the following ${r} 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)}},[_,r]),u=o.useCallback((C=M)=>{const z=y[C];return k([]),T(-1),z},[y,M]),h=o.useCallback(()=>{k([]),T(-1)},[]),I=o.useCallback(C=>{y.length!==0&&T(z=>C==="up"?z<=0?y.length-1:z-1:z>=y.length-1?0:z+1)},[y.length]),H=o.useCallback(()=>{var C;(C=j.current)==null||C.abort(),A.current&&clearTimeout(A.current),g(!1)},[]);return o.useEffect(()=>()=>{var C;(C=j.current)==null||C.abort(),A.current&&clearTimeout(A.current)},[]),{getCompletions:l,getCompletionsDebounced:N,suggestions:y,activeSuggestion:M,acceptSuggestion:u,dismissSuggestions:h,navigateSuggestions:I,explainCode:w,suggestRefactoring:p,generateTests:x,generateDocs:v,loading:f,abort:H,isConfigured:!!_}}function ri(i,a,r){var t,n;try{return(((n=(t=i.choices[0])==null?void 0:t.message)==null?void 0:n.content)||"").split(`
1204
- `).filter(d=>d.trim()).slice(0,r).map((d,m)=>({id:`suggestion-${Date.now()}-${m}`,text:d.trim(),type:"inline",preview:d.trim().slice(0,50),confidence:.8-m*.1,insertPosition:a}))}catch{return[]}}function ii(i){var a,r;try{const t=((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"",n=t.match(/\{[\s\S]*\}/);return n?JSON.parse(n[0]):{summary:t}}catch{return null}}function ti(i){var a,r;try{const n=(((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"").match(/\[[\s\S]*\]/);if(n)return JSON.parse(n[0])}catch{}return[]}function ni(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 si(i){return{javascript:"jsdoc",typescript:"tsdoc",python:"docstring",java:"javadoc",kotlin:"javadoc"}[i]||"jsdoc"}function ci({code:i="",language:a="typescript",config:r,onChange:t,onAcceptSuggestion:n,showToolbar:s=!0,enableInlineSuggestions:c=!0,placeholder:d="Start typing code...",className:m,style:f,renderEditor:g}){const[y,k]=o.useState(i),[M,T]=o.useState(null),[j,A]=o.useState(null),[_,l]=o.useState([]),[N,w]=o.useState(null),[p,x]=o.useState(null),v=o.useRef(null),{getCompletionsDebounced:u,suggestions:h,activeSuggestion:I,acceptSuggestion:H,dismissSuggestions:C,navigateSuggestions:z,explainCode:O,suggestRefactoring:B,generateTests:b,generateDocs:R,loading:q,isConfigured:U}=za({config:r,language:a}),P=L=>{if(k(L),t==null||t(L),c&&v.current){const F=oi(v.current);u(L,F)}},V=L=>{if(h.length>0)if(L.key==="ArrowUp")L.preventDefault(),z("up");else if(L.key==="ArrowDown")L.preventDefault(),z("down");else if(L.key==="Tab"||L.key==="Enter"){if(I>=0){L.preventDefault();const F=H(I);F&&(J(F),n==null||n(F))}}else L.key==="Escape"&&C()},J=L=>{if(!v.current)return;const F=v.current,X=F.selectionStart,Ie=y.slice(0,X)+L.text+y.slice(X);k(Ie),t==null||t(Ie);const Oe=X+L.text.length;setTimeout(()=>{F.focus(),F.setSelectionRange(Oe,Oe)},0)},W=async()=>{const L=M||y;if(!L.trim())return;x("explain");const F=await O(L);A(F)},G=async()=>{const L=M||y;if(!L.trim())return;x("refactor");const F=await B(L);l(F)},Z=async()=>{if(!y.trim())return;x("tests");const L=await b(y);w(L)},ie=async()=>{if(!y.trim())return;x("docs");const L=await R(y);w(L)},ae=L=>{const F=y.replace(L.before,L.after);k(F),t==null||t(F),x(null)},S=()=>{N&&navigator.clipboard.writeText(N)},E=()=>{if(v.current){const L=v.current.selectionStart,F=v.current.selectionEnd;T(L!==F?y.slice(L,F):null)}};return U?g?e.jsx("div",{className:`nice-code-editor-ai ${m||""}`,style:f,children:g({code:y,onChange:P,suggestions:h,onAccept:L=>{const F=H(L);F&&(n==null||n(F))}})}):e.jsxs("div",{className:`nice-code-editor-ai ${m||""}`,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:q||!y.trim(),title:"Explain code",children:[e.jsx($,{name:"lightbulb",size:14})," Explain"]}),e.jsxs("button",{type:"button",onClick:G,disabled:q||!y.trim(),title:"Suggest refactoring",children:[e.jsx($,{name:"settings",size:14})," Refactor"]}),e.jsxs("button",{type:"button",onClick:Z,disabled:q||!y.trim(),title:"Generate tests",children:[e.jsx($,{name:"flask",size:14})," Tests"]}),e.jsxs("button",{type:"button",onClick:ie,disabled:q||!y.trim(),title:"Generate docs",children:[e.jsx($,{name:"edit",size:14})," Docs"]})]}),q&&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:v,value:y,onChange:L=>P(L.target.value),onKeyDown:V,onSelect:E,placeholder:d,className:"nice-code-editor-ai__textarea",spellCheck:!1}),h.length>0&&e.jsxs("div",{className:"nice-code-editor-ai__suggestions",children:[h.map((L,F)=>e.jsxs("div",{className:`nice-code-editor-ai__suggestion ${F===I?"nice-code-editor-ai__suggestion--active":""}`,onClick:()=>{const X=H(F);X&&(J(X),n==null||n(X))},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($,{name:"arrow-up",size:11}),e.jsx($,{name:"arrow-down",size:11})," navigate • Tab accept • Esc dismiss"]})]})]}),p&&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:[p==="explain"&&e.jsxs(e.Fragment,{children:[e.jsx($,{name:"lightbulb",size:14})," Explanation"]}),p==="refactor"&&e.jsxs(e.Fragment,{children:[e.jsx($,{name:"settings",size:14})," Refactoring Suggestions"]}),p==="tests"&&e.jsxs(e.Fragment,{children:[e.jsx($,{name:"flask",size:14})," Generated Tests"]}),p==="docs"&&e.jsxs(e.Fragment,{children:[e.jsx($,{name:"edit",size:14})," Generated Documentation"]})]}),e.jsx("button",{type:"button",onClick:()=>x(null),"aria-label":"Close panel",children:e.jsx($,{name:"close",size:16})})]}),e.jsxs("div",{className:"nice-code-editor-ai__panel-content",children:[p==="explain"&&j&&e.jsxs("div",{className:"nice-code-editor-ai__explanation",children:[e.jsx("div",{className:"nice-code-editor-ai__explanation-summary",children:j.summary}),j.details&&e.jsx("div",{className:"nice-code-editor-ai__explanation-details",children:j.details}),j.complexity&&e.jsxs("span",{className:`nice-code-editor-ai__complexity nice-code-editor-ai__complexity--${j.complexity}`,children:["Complexity: ",j.complexity]}),j.suggestions&&j.suggestions.length>0&&e.jsx("ul",{className:"nice-code-editor-ai__explanation-suggestions",children:j.suggestions.map((L,F)=>e.jsx("li",{children:L},F))})]}),p==="refactor"&&_.length>0&&e.jsx("div",{className:"nice-code-editor-ai__refactorings",children:_.map((L,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: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:()=>ae(L),children:"Apply"})]},F))}),(p==="tests"||p==="docs")&&N&&e.jsxs("div",{className:"nice-code-editor-ai__generated",children:[e.jsx("pre",{children:N}),e.jsxs("button",{type:"button",onClick:S,children:[e.jsx($,{name:"clipboard",size:14})," Copy"]})]})]})]}),e.jsx("style",{children:`
1174
+ `})]})}function ga(t={}){const{config:a,language:i="typescript",context:r,maxSuggestions:n=3,debounceMs:s=300,onSuggestion:c,onError:l}=t,m=Q(),[g,x]=d.useState(!1),[w,N]=d.useState([]),[S,R]=d.useState(-1),j=d.useRef(null),I=d.useRef(null),_=a||(m==null?void 0:m.config),o=d.useCallback(async(C,A)=>{var B,f,z;if(!_)return{suggestions:[],error:"AI not configured"};x(!0),(B=j.current)==null||B.abort(),j.current=new AbortController;const O=performance.now();try{const U=V(_),H=C.split(`
1175
+ `),P=H[A.line]||"",J=P.substring(0,A.column),q=P.substring(A.column),W=H.slice(Math.max(0,A.line-20),A.line).join(`
1176
+ `),G=H.slice(A.line+1,A.line+10).join(`
1177
+ `),Y=ee(le,{language:i,code_context:W,prefix:J,suffix:q,context_after:G,context:r}),ae=await U.chat({messages:[{role:"system",content:Y.system},{role:"user",content:Y.user}],temperature:.2,maxTokens:512}),Z=ji(ae,A,n),T={suggestions:Z,rawResponse:(z=(f=ae.choices[0])==null?void 0:f.message)==null?void 0:z.content,latencyMs:performance.now()-O};return N(Z),R(Z.length>0?0:-1),c==null||c(Z),T}catch(U){const H=U instanceof Error?U.message:"Completion failed";return l==null||l(H),{suggestions:[],error:H,latencyMs:performance.now()-O}}finally{x(!1)}},[_,i,r,n,c,l]),k=d.useCallback((C,A)=>{I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{o(C,A)},s)},[o,s]),y=d.useCallback(async C=>{if(!_)return null;x(!0);try{const O=await V(_).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 ki(O)}catch{return null}finally{x(!1)}},[_,i]),p=d.useCallback(async C=>{if(!_)return[];x(!0);try{const O=await V(_).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 Ni(O)}catch{return[]}finally{x(!1)}},[_,i]),b=d.useCallback(async(C,A)=>{var O,B;if(!_)return null;x(!0);try{const f=V(_),z=A||Ci(i);return((B=(O=(await f.chat({messages:[{role:"system",content:`You are a testing expert. Generate comprehensive unit tests for the following ${i} code using ${z}. 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{x(!1)}},[_,i]),v=d.useCallback(async(C,A)=>{var O,B;if(!_)return null;x(!0);try{const f=V(_),z=A||Si(i);return((B=(O=(await f.chat({messages:[{role:"system",content:`Generate ${z} 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{x(!1)}},[_,i]),u=d.useCallback((C=S)=>{const A=w[C];return N([]),R(-1),A},[w,S]),h=d.useCallback(()=>{N([]),R(-1)},[]),$=d.useCallback(C=>{w.length!==0&&R(A=>C==="up"?A<=0?w.length-1:A-1:A>=w.length-1?0:A+1)},[w.length]),E=d.useCallback(()=>{var C;(C=j.current)==null||C.abort(),I.current&&clearTimeout(I.current),x(!1)},[]);return d.useEffect(()=>()=>{var C;(C=j.current)==null||C.abort(),I.current&&clearTimeout(I.current)},[]),{getCompletions:o,getCompletionsDebounced:k,suggestions:w,activeSuggestion:S,acceptSuggestion:u,dismissSuggestions:h,navigateSuggestions:$,explainCode:y,suggestRefactoring:p,generateTests:b,generateDocs:v,loading:g,abort:E,isConfigured:!!_}}function ji(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,m)=>({id:`suggestion-${Date.now()}-${m}`,text:l.trim(),type:"inline",preview:l.trim().slice(0,50),confidence:.8-m*.1,insertPosition:a}))}catch{return[]}}function ki(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 Ni(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 Ci(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 Si(t){return{javascript:"jsdoc",typescript:"tsdoc",python:"docstring",java:"javadoc",kotlin:"javadoc"}[t]||"jsdoc"}function Ti({code:t="",language:a="typescript",config:i,onChange:r,onAcceptSuggestion:n,showToolbar:s=!0,enableInlineSuggestions:c=!0,placeholder:l="Start typing code...",className:m,style:g,renderEditor:x}){const[w,N]=d.useState(t),[S,R]=d.useState(null),[j,I]=d.useState(null),[_,o]=d.useState([]),[k,y]=d.useState(null),[p,b]=d.useState(null),v=d.useRef(null),{getCompletionsDebounced:u,suggestions:h,activeSuggestion:$,acceptSuggestion:E,dismissSuggestions:C,navigateSuggestions:A,explainCode:O,suggestRefactoring:B,generateTests:f,generateDocs:z,loading:U,isConfigured:H}=ga({config:i,language:a}),P=M=>{if(N(M),r==null||r(M),c&&v.current){const F=Ai(v.current);u(M,F)}},J=M=>{if(h.length>0)if(M.key==="ArrowUp")M.preventDefault(),A("up");else if(M.key==="ArrowDown")M.preventDefault(),A("down");else if(M.key==="Tab"||M.key==="Enter"){if($>=0){M.preventDefault();const F=E($);F&&(q(F),n==null||n(F))}}else M.key==="Escape"&&C()},q=M=>{if(!v.current)return;const F=v.current,K=F.selectionStart,ze=w.slice(0,K)+M.text+w.slice(K);N(ze),r==null||r(ze);const Me=K+M.text.length;setTimeout(()=>{F.focus(),F.setSelectionRange(Me,Me)},0)},W=async()=>{const M=S||w;if(!M.trim())return;b("explain");const F=await O(M);I(F)},G=async()=>{const M=S||w;if(!M.trim())return;b("refactor");const F=await B(M);o(F)},Y=async()=>{if(!w.trim())return;b("tests");const M=await f(w);y(M)},ae=async()=>{if(!w.trim())return;b("docs");const M=await z(w);y(M)},Z=M=>{const F=w.replace(M.before,M.after);N(F),r==null||r(F),b(null)},T=()=>{k&&navigator.clipboard.writeText(k)},D=()=>{if(v.current){const M=v.current.selectionStart,F=v.current.selectionEnd;R(M!==F?w.slice(M,F):null)}};return H?x?e.jsx("div",{className:`nice-code-editor-ai ${m||""}`,style:g,children:x({code:w,onChange:P,suggestions:h,onAccept:M=>{const F=E(M);F&&(n==null||n(F))}})}):e.jsxs("div",{className:`nice-code-editor-ai ${m||""}`,style:g,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:U||!w.trim(),title:"Explain code",children:[e.jsx(L.NiceIcon,{name:"lightbulb",size:14})," Explain"]}),e.jsxs("button",{type:"button",onClick:G,disabled:U||!w.trim(),title:"Suggest refactoring",children:[e.jsx(L.NiceIcon,{name:"settings",size:14})," Refactor"]}),e.jsxs("button",{type:"button",onClick:Y,disabled:U||!w.trim(),title:"Generate tests",children:[e.jsx(L.NiceIcon,{name:"flask",size:14})," Tests"]}),e.jsxs("button",{type:"button",onClick:ae,disabled:U||!w.trim(),title:"Generate docs",children:[e.jsx(L.NiceIcon,{name:"edit",size:14})," Docs"]})]}),U&&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:v,value:w,onChange:M=>P(M.target.value),onKeyDown:J,onSelect:D,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((M,F)=>e.jsxs("div",{className:`nice-code-editor-ai__suggestion ${F===$?"nice-code-editor-ai__suggestion--active":""}`,onClick:()=>{const K=E(F);K&&(q(K),n==null||n(K))},children:[e.jsx("span",{className:"nice-code-editor-ai__suggestion-text",children:M.text}),e.jsxs("span",{className:"nice-code-editor-ai__suggestion-confidence",children:[Math.round(M.confidence*100),"%"]})]},M.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"]})]})]}),p&&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:[p==="explain"&&e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"lightbulb",size:14})," Explanation"]}),p==="refactor"&&e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"settings",size:14})," Refactoring Suggestions"]}),p==="tests"&&e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"flask",size:14})," Generated Tests"]}),p==="docs"&&e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"edit",size:14})," Generated Documentation"]})]}),e.jsx("button",{type:"button",onClick:()=>b(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:[p==="explain"&&j&&e.jsxs("div",{className:"nice-code-editor-ai__explanation",children:[e.jsx("div",{className:"nice-code-editor-ai__explanation-summary",children:j.summary}),j.details&&e.jsx("div",{className:"nice-code-editor-ai__explanation-details",children:j.details}),j.complexity&&e.jsxs("span",{className:`nice-code-editor-ai__complexity nice-code-editor-ai__complexity--${j.complexity}`,children:["Complexity: ",j.complexity]}),j.suggestions&&j.suggestions.length>0&&e.jsx("ul",{className:"nice-code-editor-ai__explanation-suggestions",children:j.suggestions.map((M,F)=>e.jsx("li",{children:M},F))})]}),p==="refactor"&&_.length>0&&e.jsx("div",{className:"nice-code-editor-ai__refactorings",children:_.map((M,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:M.title}),e.jsx("span",{className:`nice-code-editor-ai__refactoring-type nice-code-editor-ai__refactoring-type--${M.type}`,children:M.type})]}),e.jsx("p",{className:"nice-code-editor-ai__refactoring-desc",children:M.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:M.before})]}),e.jsxs("div",{className:"nice-code-editor-ai__refactoring-after",children:[e.jsx("span",{children:"After:"}),e.jsx("pre",{children:M.after})]})]}),e.jsx("button",{type:"button",className:"nice-code-editor-ai__refactoring-apply",onClick:()=>Z(M),children:"Apply"})]},F))}),(p==="tests"||p==="docs")&&k&&e.jsxs("div",{className:"nice-code-editor-ai__generated",children:[e.jsx("pre",{children:k}),e.jsxs("button",{type:"button",onClick:T,children:[e.jsx(L.NiceIcon,{name:"clipboard",size:14})," Copy"]})]})]})]}),e.jsx("style",{children:`
1205
1179
  .nice-code-editor-ai {
1206
1180
  font-family: var(--nice-font-family, system-ui, sans-serif);
1207
1181
  display: flex;
@@ -1507,11 +1481,11 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
1507
1481
  border-radius: var(--nice-radius-md, 6px);
1508
1482
  cursor: pointer;
1509
1483
  }
1510
- `})]}):e.jsxs("div",{className:`nice-code-editor-ai nice-code-editor-ai--disabled ${m||""}`,style:f,children:[e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."}),e.jsx("textarea",{value:y,onChange:L=>P(L.target.value),placeholder:d,className:"nice-code-editor-ai__textarea"})]})}function oi(i){const r=i.value.substring(0,i.selectionStart).split(`
1511
- `);return{line:r.length-1,column:r[r.length-1].length}}function Ta(i={}){const{config:a,context:r,existingRoles:t,existingVariables:n,onWorkflowGenerated:s,onError:c}=i,d=ee(),[m,f]=o.useState(!1),[g,y]=o.useState(null),[k,M]=o.useState([]),T=o.useRef(null),j=a||(d==null?void 0:d.config),A=o.useCallback(async x=>{var u,h,I;if(!j){const H="AI not configured";return c==null||c(H),{error:H}}f(!0);const v=performance.now();(u=T.current)==null||u.abort(),T.current=new AbortController;try{const H=K(j),C=[r,t!=null&&t.length?`Available roles: ${t.join(", ")}`:"",n!=null&&n.length?`Existing variables: ${n.join(", ")}`:""].filter(Boolean).join(`
1512
- `),z=re(me,{description:x,context:C}),O=await H.chat({messages:[{role:"system",content:z.system},{role:"user",content:z.user}],temperature:.5,maxTokens:2048}),B=Ve(O),b={workflow:B||void 0,rawResponse:(I=(h=O.choices[0])==null?void 0:h.message)==null?void 0:I.content,latencyMs:performance.now()-v,error:B?void 0:"Failed to generate workflow",suggestions:di(B)};return B&&(s==null||s(B)),y(b),M(R=>[...R.slice(-9),{request:x,result:b}]),b}catch(H){const C=H instanceof Error?H.message:"Workflow generation failed",z={error:C,latencyMs:performance.now()-v};return y(z),c==null||c(C),z}finally{f(!1)}},[j,r,t,n,s,c]),_=o.useCallback(async x=>{if(!j)return{error:"AI not configured"};f(!0);const v=performance.now();try{const h=await K(j).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(x,null,2)}],temperature:.4,maxTokens:2048});return{workflow:Ve(h)||void 0,latencyMs:performance.now()-v}}catch(u){return{error:u instanceof Error?u.message:"Optimization failed"}}finally{f(!1)}},[j]),l=o.useCallback(async(x,v)=>{var u,h;if(!j)return[];f(!0);try{const I=K(j),H=x.nodes.find(B=>B.id===v),O=(((h=(u=(await I.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: ${x.name}
1513
- Current node: ${(H==null?void 0:H.label)||v}
1514
- Existing nodes: ${x.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[]},[j]),N=o.useCallback(async x=>{var v,u;if(!j)return[];f(!0);try{const C=(((u=(v=(await K(j).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(x,null,2)}],temperature:.3,maxTokens:1024})).choices[0])==null?void 0:v.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[]},[j]),w=o.useCallback(()=>{y(null)},[]),p=o.useCallback(()=>{var x;(x=T.current)==null||x.abort(),f(!1)},[]);return o.useEffect(()=>()=>{var x;(x=T.current)==null||x.abort()},[]),{generateWorkflow:A,optimizeWorkflow:_,suggestNextStep:l,validateWorkflow:N,loading:m,lastResult:g,history:k,clearResults:w,abort:p,isConfigured:!!j}}function Ve(i){var a,r,t;try{const n=((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"",c=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,d=JSON.parse(c);if(d.nodes&&Array.isArray(d.nodes)){const m=d.nodes.map((f,g)=>({...f,id:f.id||`node_${g}`,position:f.position||li(g,d.nodes.length)}));return{id:d.id||`workflow_${Date.now()}`,name:d.name||"Generated Workflow",description:d.description,version:d.version||"1.0",nodes:m,edges:d.edges||[],lanes:d.lanes,variables:d.variables,metadata:d.metadata}}}catch{}return null}function li(i,a){const s=Math.floor(i/5);return{x:100+i%5*200,y:100+s*100}}function di(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 ui=["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:i,context:a,roles:r,onGenerate:t,placeholder:n='Describe the workflow process... (e.g., "Leave request with manager approval")',showExamples:s=!0,showPreview:c=!0,className:d,style:m,renderWorkflow:f}){const[g,y]=o.useState(""),[k,M]=o.useState([]),T=o.useRef(null),{generateWorkflow:j,validateWorkflow:A,loading:_,lastResult:l,isConfigured:N}=Ta({config:i,context:a,existingRoles:r,onWorkflowGenerated:t}),w=async()=>{!g.trim()||_||await j(g)},p=u=>{var h;y(u),(h=T.current)==null||h.focus()},x=async()=>{if(!(l!=null&&l.workflow))return;const u=await A(l.workflow);M(u)},v=()=>{if(!(l!=null&&l.workflow))return;const u=fi(l.workflow),h=new Blob([u],{type:"application/xml"}),I=URL.createObjectURL(h),H=document.createElement("a");H.href=I,H.download=`${l.workflow.name.replace(/\s+/g,"_")}.bpmn`,H.click(),URL.revokeObjectURL(I)};return N?e.jsxs("div",{className:`nice-workflow-ai ${d||""}`,style:m,children:[e.jsxs("div",{className:"nice-workflow-ai__input-section",children:[e.jsx("textarea",{ref:T,value:g,onChange:u=>y(u.target.value),placeholder:n,className:"nice-workflow-ai__input",rows:3,disabled:_}),e.jsx("button",{type:"button",onClick:w,className:"nice-workflow-ai__submit",disabled:_||!g.trim(),children:_?e.jsx("span",{className:"nice-workflow-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx($,{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:"}),ui.slice(0,3).map((u,h)=>e.jsx("button",{type:"button",className:"nice-workflow-ai__example",onClick:()=>p(u),children:u},h))]}),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:()=>t==null?void 0:t(l.workflow),children:[e.jsx($,{name:"check",size:14})," Use Workflow"]}),e.jsxs("button",{type:"button",onClick:x,children:[e.jsx($,{name:"search",size:14})," Validate"]}),e.jsxs("button",{type:"button",onClick:v,children:[e.jsx($,{name:"download",size:14})," Export BPMN"]})]}),k.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:k.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(l.workflow):e.jsx(mi,{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($,{name:"lightbulb",size:14})," Suggestions:"]}),e.jsx("ul",{children:l.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(l.workflow,null,2)})]})]})}),e.jsx("style",{children:`
1484
+ `})]}):e.jsxs("div",{className:`nice-code-editor-ai nice-code-editor-ai--disabled ${m||""}`,style:g,children:[e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."}),e.jsx("textarea",{value:w,onChange:M=>P(M.target.value),placeholder:l,className:"nice-code-editor-ai__textarea"})]})}function Ai(t){const i=t.value.substring(0,t.selectionStart).split(`
1485
+ `);return{line:i.length-1,column:i[i.length-1].length}}function fa(t={}){const{config:a,context:i,existingRoles:r,existingVariables:n,onWorkflowGenerated:s,onError:c}=t,l=Q(),[m,g]=d.useState(!1),[x,w]=d.useState(null),[N,S]=d.useState([]),R=d.useRef(null),j=a||(l==null?void 0:l.config),I=d.useCallback(async b=>{var u,h,$;if(!j){const E="AI not configured";return c==null||c(E),{error:E}}g(!0);const v=performance.now();(u=R.current)==null||u.abort(),R.current=new AbortController;try{const E=V(j),C=[i,r!=null&&r.length?`Available roles: ${r.join(", ")}`:"",n!=null&&n.length?`Existing variables: ${n.join(", ")}`:""].filter(Boolean).join(`
1486
+ `),A=ee(de,{description:b,context:C}),O=await E.chat({messages:[{role:"system",content:A.system},{role:"user",content:A.user}],temperature:.5,maxTokens:2048}),B=Ee(O),f={workflow:B||void 0,rawResponse:($=(h=O.choices[0])==null?void 0:h.message)==null?void 0:$.content,latencyMs:performance.now()-v,error:B?void 0:"Failed to generate workflow",suggestions:Ii(B)};return B&&(s==null||s(B)),w(f),S(z=>[...z.slice(-9),{request:b,result:f}]),f}catch(E){const C=E instanceof Error?E.message:"Workflow generation failed",A={error:C,latencyMs:performance.now()-v};return w(A),c==null||c(C),A}finally{g(!1)}},[j,i,r,n,s,c]),_=d.useCallback(async b=>{if(!j)return{error:"AI not configured"};g(!0);const v=performance.now();try{const h=await V(j).chat({messages:[{role:"system",content:"You are a workflow optimization expert. Analyze the following BPMN workflow and suggest improvements for efficiency, clarity, and error handling. Return the optimized workflow in JSON format with the same structure."},{role:"user",content:JSON.stringify(b,null,2)}],temperature:.4,maxTokens:2048});return{workflow:Ee(h)||void 0,latencyMs:performance.now()-v}}catch(u){return{error:u instanceof Error?u.message:"Optimization failed"}}finally{g(!1)}},[j]),o=d.useCallback(async(b,v)=>{var u,h;if(!j)return[];g(!0);try{const $=V(j),E=b.nodes.find(B=>B.id===v),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: ${b.name}
1487
+ Current node: ${(E==null?void 0:E.label)||v}
1488
+ Existing nodes: ${b.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{g(!1)}return[]},[j]),k=d.useCallback(async b=>{var v,u;if(!j)return[];g(!0);try{const C=(((u=(v=(await V(j).chat({messages:[{role:"system",content:'Analyze the BPMN workflow for potential issues. Check for: dead ends, unreachable nodes, missing error handling, infinite loops, unclear conditions, missing assignments. Return JSON array of issues: [{ "severity": "error"|"warning"|"info", "message": string, "nodeId": string? }]'},{role:"user",content:JSON.stringify(b,null,2)}],temperature:.3,maxTokens:1024})).choices[0])==null?void 0:v.message)==null?void 0:u.content)||"").match(/\[[\s\S]*\]/);if(C)return JSON.parse(C[0]).map(O=>`[${O.severity}] ${O.message}`)}catch{}finally{g(!1)}return[]},[j]),y=d.useCallback(()=>{w(null)},[]),p=d.useCallback(()=>{var b;(b=R.current)==null||b.abort(),g(!1)},[]);return d.useEffect(()=>()=>{var b;(b=R.current)==null||b.abort()},[]),{generateWorkflow:I,optimizeWorkflow:_,suggestNextStep:o,validateWorkflow:k,loading:m,lastResult:x,history:N,clearResults:y,abort:p,isConfigured:!!j}}function Ee(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 m=l.nodes.map((g,x)=>({...g,id:g.id||`node_${x}`,position:g.position||Ri(x,l.nodes.length)}));return{id:l.id||`workflow_${Date.now()}`,name:l.name||"Generated Workflow",description:l.description,version:l.version||"1.0",nodes:m,edges:l.edges||[],lanes:l.lanes,variables:l.variables,metadata:l.metadata}}}catch{}return null}function Ri(t,a){const s=Math.floor(t/5);return{x:100+t%5*200,y:100+s*100}}function Ii(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 zi=["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 Mi({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:m,renderWorkflow:g}){const[x,w]=d.useState(""),[N,S]=d.useState([]),R=d.useRef(null),{generateWorkflow:j,validateWorkflow:I,loading:_,lastResult:o,isConfigured:k}=fa({config:t,context:a,existingRoles:i,onWorkflowGenerated:r}),y=async()=>{!x.trim()||_||await j(x)},p=u=>{var h;w(u),(h=R.current)==null||h.focus()},b=async()=>{if(!(o!=null&&o.workflow))return;const u=await I(o.workflow);S(u)},v=()=>{if(!(o!=null&&o.workflow))return;const u=Pi(o.workflow),h=new Blob([u],{type:"application/xml"}),$=URL.createObjectURL(h),E=document.createElement("a");E.href=$,E.download=`${o.workflow.name.replace(/\s+/g,"_")}.bpmn`,E.click(),URL.revokeObjectURL($)};return k?e.jsxs("div",{className:`nice-workflow-ai ${l||""}`,style:m,children:[e.jsxs("div",{className:"nice-workflow-ai__input-section",children:[e.jsx("textarea",{ref:R,value:x,onChange:u=>w(u.target.value),placeholder:n,className:"nice-workflow-ai__input",rows:3,disabled:_}),e.jsx("button",{type:"button",onClick:y,className:"nice-workflow-ai__submit",disabled:_||!x.trim(),children:_?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:"}),zi.slice(0,3).map((u,h)=>e.jsx("button",{type:"button",className:"nice-workflow-ai__example",onClick:()=>p(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:b,children:[e.jsx(L.NiceIcon,{name:"search",size:14})," Validate"]}),e.jsxs("button",{type:"button",onClick:v,children:[e.jsx(L.NiceIcon,{name:"download",size:14})," Export BPMN"]})]}),N.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:N.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:g?g(o.workflow):e.jsx(Li,{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:`
1515
1489
  .nice-workflow-ai {
1516
1490
  font-family: var(--nice-font-family, system-ui, sans-serif);
1517
1491
  }
@@ -1772,7 +1746,7 @@ Existing nodes: ${x.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxToken
1772
1746
  color: var(--nice-error, #c62828);
1773
1747
  border-radius: var(--nice-radius-md, 6px);
1774
1748
  }
1775
- `})]}):e.jsx("div",{className:`nice-workflow-ai nice-workflow-ai--disabled ${d||""}`,style:m,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function mi({workflow:i}){const a=t=>({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"})[t]||"clipboard",r=t=>t==="start"?"var(--nice-success, #4caf50)":t==="end"?"var(--nice-danger, #f44336)":t.startsWith("gateway")?"var(--nice-warning, #ff9800)":t.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(t=>{var n,s;return e.jsxs("div",{className:`workflow-preview__node workflow-preview__node--${t.type.split("-")[0]}`,style:{left:(n=t.position)==null?void 0:n.x,top:(s=t.position)==null?void 0:s.y,borderColor:r(t.type)},children:[e.jsx("span",{className:"workflow-preview__node-icon",children:e.jsx($,{name:a(t.type),size:16})}),e.jsx("span",{className:"workflow-preview__node-label",children:t.label})]},t.id)}),e.jsxs("svg",{className:"workflow-preview__connections",children:[i.edges.map(t=>{const n=i.nodes.find(g=>g.id===t.source),s=i.nodes.find(g=>g.id===t.target);if(!(n!=null&&n.position)||!(s!=null&&s.position))return null;const c=n.position.x+60,d=n.position.y+20,m=s.position.x,f=s.position.y+20;return e.jsxs("g",{children:[e.jsx("line",{x1:c,y1:d,x2:m,y2:f,stroke:"var(--nice-text-secondary, #666)",strokeWidth:"2",markerEnd:"url(#arrowhead)"}),t.label&&e.jsx("text",{x:(c+m)/2,y:(d+f)/2-5,fontSize:"10",fill:"var(--nice-text-secondary, #666)",textAnchor:"middle",children:t.label})]},t.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(t=>e.jsx("span",{className:"workflow-preview__lane",children:t.name},t.id))]}),e.jsx("style",{children:`
1749
+ `})]}):e.jsx("div",{className:`nice-workflow-ai nice-workflow-ai--disabled ${l||""}`,style:m,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function Li({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(x=>x.id===r.source),s=t.nodes.find(x=>x.id===r.target);if(!(n!=null&&n.position)||!(s!=null&&s.position))return null;const c=n.position.x+60,l=n.position.y+20,m=s.position.x,g=s.position.y+20;return e.jsxs("g",{children:[e.jsx("line",{x1:c,y1:l,x2:m,y2:g,stroke:"var(--nice-text-secondary, #666)",strokeWidth:"2",markerEnd:"url(#arrowhead)"}),r.label&&e.jsx("text",{x:(c+m)/2,y:(l+g)/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:`
1776
1750
  .workflow-preview {
1777
1751
  min-height: 200px;
1778
1752
  }
@@ -1861,21 +1835,21 @@ Existing nodes: ${x.nodes.map(B=>B.label).join(", ")}`}],temperature:.6,maxToken
1861
1835
  border-radius: var(--nice-radius-sm, 4px);
1862
1836
  font-size: 12px;
1863
1837
  }
1864
- `})]})}function fi(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"},r=i.nodes.map(n=>` <${a[n.type]||"bpmn:task"} id="${n.id}" name="${xe(n.label)}" />`).join(`
1865
- `),t=i.edges.map(n=>` <bpmn:sequenceFlow id="${n.id}" sourceRef="${n.source}" targetRef="${n.target}"${n.label?` name="${xe(n.label)}"`:""} />`).join(`
1838
+ `})]})}function Pi(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(`
1839
+ `),r=t.edges.map(n=>` <bpmn:sequenceFlow id="${n.id}" sourceRef="${n.source}" targetRef="${n.target}"${n.label?` name="${fe(n.label)}"`:""} />`).join(`
1866
1840
  `);return`<?xml version="1.0" encoding="UTF-8"?>
1867
1841
  <bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL"
1868
1842
  xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
1869
- id="${i.id}"
1843
+ id="${t.id}"
1870
1844
  targetNamespace="http://nice2dev.com/bpmn">
1871
- <bpmn:process id="Process_${i.id}" name="${xe(i.name)}" isExecutable="true">
1845
+ <bpmn:process id="Process_${t.id}" name="${fe(t.name)}" isExecutable="true">
1846
+ ${i}
1872
1847
  ${r}
1873
- ${t}
1874
1848
  </bpmn:process>
1875
- </bpmn:definitions>`}function xe(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Aa(i={}){const{config:a,dataSources:r,context:t,onReportGenerated:n,onError:s}=i,c=ee(),[d,m]=o.useState(!1),[f,g]=o.useState(null),[y,k]=o.useState([]),M=o.useRef(null),T=a||(c==null?void 0:c.config),j=o.useCallback(async p=>{var v,u,h;if(!T){const I="AI not configured";return s==null||s(I),{error:I}}m(!0);const x=performance.now();(v=M.current)==null||v.abort(),M.current=new AbortController;try{const I=K(T),H=r?r.map(b=>`- ${b.name} (${b.id}): ${b.fields.join(", ")}`).join(`
1876
- `):void 0,C=re(fe,{description:p,data_sources:H,context:t}),z=await I.chat({messages:[{role:"system",content:C.system},{role:"user",content:C.user}],temperature:.5,maxTokens:2048}),O=hi(z),B={layout:O||void 0,rawResponse:(h=(u=z.choices[0])==null?void 0:u.message)==null?void 0:h.content,latencyMs:performance.now()-x,error:O?void 0:"Failed to generate report layout",suggestions:gi(O)};return O&&(n==null||n(O)),g(B),k(b=>[...b.slice(-9),{request:p,result:B}]),B}catch(I){const H=I instanceof Error?I.message:"Report generation failed",C={error:H,latencyMs:performance.now()-x};return g(C),s==null||s(H),C}finally{m(!1)}},[T,r,t,n,s]),A=o.useCallback(async p=>{var x,v;if(!T)return[];m(!0);try{const H=(((v=(x=(await K(T).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: ${p.name}
1877
- Existing sections: ${p.sections.map(C=>C.type).join(", ")}`}],temperature:.6,maxTokens:1024})).choices[0])==null?void 0:x.message)==null?void 0:v.content)||"").match(/\[[\s\S]*\]/);if(H)return JSON.parse(H[0])}catch{}finally{m(!1)}return[]},[T]),_=o.useCallback(async p=>{var x,v;if(!T)return null;m(!0);try{return((v=(x=(await K(T).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(p,null,2)}],temperature:.5,maxTokens:512})).choices[0])==null?void 0:x.message)==null?void 0:v.content)||null}catch{return null}finally{m(!1)}},[T]),l=o.useCallback(async(p,x)=>{var v,u,h;if(!T)return"bar";try{const I=K(T),H=p.slice(0,5),z=(h=(u=(v=(await I.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(H)}
1878
- Purpose: ${x}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:v.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=>z==null?void 0:z.includes(B))||"bar"}catch{return"bar"}},[T]),N=o.useCallback(()=>{g(null)},[]),w=o.useCallback(()=>{var p;(p=M.current)==null||p.abort(),m(!1)},[]);return o.useEffect(()=>()=>{var p;(p=M.current)==null||p.abort()},[]),{generateReport:j,suggestSections:A,generateSummary:_,suggestChartType:l,loading:d,lastResult:f,history:y,clearResults:N,abort:w,isConfigured:!!T}}function hi(i){var a,r,t;try{const n=((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"",c=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,d=JSON.parse(c);if(d.sections&&Array.isArray(d.sections)){const m=d.sections.map((f,g)=>({...f,id:f.id||`section_${g}`,order:f.order??g,config:f.config||{}}));return{id:d.id||`report_${Date.now()}`,name:d.name||"Generated Report",description:d.description,orientation:d.orientation||"portrait",pageSize:d.pageSize||"A4",margins:d.margins||{top:20,right:20,bottom:20,left:20},sections:m,dataSources:d.dataSources,parameters:d.parameters,styles:d.styles}}}catch{}return null}function gi(i){if(!i)return[];const a=[],r=new Set(i.sections.map(t=>t.type));return r.has("summary")||a.push("Add an executive summary for quick insights"),r.has("kpi")||a.push("Include KPI cards for key metrics"),r.has("chart")||a.push("Add visualizations to make data more accessible"),r.has("footer")||a.push("Add a footer with page numbers and date"),i.sections.length>5&&!r.has("toc")&&a.push("Consider adding a table of contents"),a.slice(0,3)}const yi=[{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 bi({config:i,dataSources:a,context:r,onGenerate:t,placeholder:n='Describe the report you need... (e.g., "Monthly sales report with KPIs and charts")',showTemplates:s=!0,showPreview:c=!0,className:d,style:m,renderReport:f}){const[g,y]=o.useState(""),k=o.useRef(null),{generateReport:M,loading:T,lastResult:j,isConfigured:A}=Aa({config:i,dataSources:a,context:r,onReportGenerated:t}),_=async()=>{!g.trim()||T||await M(g)},l=w=>{var p;y(w.prompt),(p=k.current)==null||p.focus()},N=()=>{if(!(j!=null&&j.layout))return;const w=JSON.stringify(j.layout,null,2),p=new Blob([w],{type:"application/json"}),x=URL.createObjectURL(p),v=document.createElement("a");v.href=x,v.download=`${j.layout.name.replace(/\s+/g,"_")}.json`,v.click(),URL.revokeObjectURL(x)};return A?e.jsxs("div",{className:`nice-report-ai ${d||""}`,style:m,children:[s&&e.jsx("div",{className:"nice-report-ai__templates",children:yi.map((w,p)=>e.jsxs("button",{type:"button",className:"nice-report-ai__template",onClick:()=>l(w),children:[e.jsx("span",{className:"nice-report-ai__template-icon",children:e.jsx($,{name:w.icon,size:24})}),e.jsx("span",{className:"nice-report-ai__template-name",children:w.name})]},p))}),e.jsxs("div",{className:"nice-report-ai__input-section",children:[e.jsx("textarea",{ref:k,value:g,onChange:w=>y(w.target.value),placeholder:n,className:"nice-report-ai__input",rows:3,disabled:T}),e.jsx("button",{type:"button",onClick:_,className:"nice-report-ai__submit",disabled:T||!g.trim(),children:T?e.jsx("span",{className:"nice-report-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx($,{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(w=>e.jsx("span",{className:"nice-report-ai__datasource",children:w.name},w.id))]}),j&&e.jsx("div",{className:"nice-report-ai__result",children:j.error?e.jsx("div",{className:"nice-report-ai__error",children:j.error}):j.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:j.layout.name}),j.layout.description&&e.jsx("span",{className:"nice-report-ai__report-desc",children:j.layout.description})]}),e.jsxs("div",{className:"nice-report-ai__result-meta",children:[e.jsxs("span",{className:"nice-report-ai__stat",children:[j.layout.sections.length," sections"]}),e.jsxs("span",{className:"nice-report-ai__stat",children:[j.layout.pageSize," ",j.layout.orientation]}),j.latencyMs&&e.jsxs("span",{className:"nice-report-ai__latency",children:[Math.round(j.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-report-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>t==null?void 0:t(j.layout),children:[e.jsx($,{name:"check",size:14})," Use Report"]}),e.jsxs("button",{type:"button",onClick:N,children:[e.jsx($,{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:j.layout.sections.map((w,p)=>e.jsxs("div",{className:"nice-report-ai__section",children:[e.jsx("span",{className:"nice-report-ai__section-number",children:p+1}),e.jsx("span",{className:"nice-report-ai__section-icon",children:e.jsx($,{name:Ra(w.type),size:16})}),e.jsx("span",{className:"nice-report-ai__section-type",children:w.type}),w.title&&e.jsx("span",{className:"nice-report-ai__section-title",children:w.title})]},w.id))})]}),c&&e.jsx("div",{className:"nice-report-ai__preview",children:f?f(j.layout):e.jsx(xi,{layout:j.layout})}),j.suggestions&&j.suggestions.length>0&&e.jsxs("div",{className:"nice-report-ai__suggestions",children:[e.jsxs("span",{className:"nice-report-ai__suggestions-title",children:[e.jsx($,{name:"lightbulb",size:14})," Suggestions:"]}),e.jsx("ul",{children:j.suggestions.map((w,p)=>e.jsx("li",{children:w},p))})]}),e.jsxs("details",{className:"nice-report-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(j.layout,null,2)})]})]})}),e.jsx("style",{children:`
1849
+ </bpmn:definitions>`}function fe(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function xa(t={}){const{config:a,dataSources:i,context:r,onReportGenerated:n,onError:s}=t,c=Q(),[l,m]=d.useState(!1),[g,x]=d.useState(null),[w,N]=d.useState([]),S=d.useRef(null),R=a||(c==null?void 0:c.config),j=d.useCallback(async p=>{var v,u,h;if(!R){const $="AI not configured";return s==null||s($),{error:$}}m(!0);const b=performance.now();(v=S.current)==null||v.abort(),S.current=new AbortController;try{const $=V(R),E=i?i.map(f=>`- ${f.name} (${f.id}): ${f.fields.join(", ")}`).join(`
1850
+ `):void 0,C=ee(ue,{description:p,data_sources:E,context:r}),A=await $.chat({messages:[{role:"system",content:C.system},{role:"user",content:C.user}],temperature:.5,maxTokens:2048}),O=$i(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()-b,error:O?void 0:"Failed to generate report layout",suggestions:Oi(O)};return O&&(n==null||n(O)),x(B),N(f=>[...f.slice(-9),{request:p,result:B}]),B}catch($){const E=$ instanceof Error?$.message:"Report generation failed",C={error:E,latencyMs:performance.now()-b};return x(C),s==null||s(E),C}finally{m(!1)}},[R,i,r,n,s]),I=d.useCallback(async p=>{var b,v;if(!R)return[];m(!0);try{const E=(((v=(b=(await V(R).chat({messages:[{role:"system",content:"Given the existing report layout, suggest 2-3 additional sections that would enhance it. Return JSON array of sections with: id, type, title, order, config."},{role:"user",content:`Report: ${p.name}
1851
+ Existing sections: ${p.sections.map(C=>C.type).join(", ")}`}],temperature:.6,maxTokens:1024})).choices[0])==null?void 0:b.message)==null?void 0:v.content)||"").match(/\[[\s\S]*\]/);if(E)return JSON.parse(E[0])}catch{}finally{m(!1)}return[]},[R]),_=d.useCallback(async p=>{var b,v;if(!R)return null;m(!0);try{return((v=(b=(await V(R).chat({messages:[{role:"system",content:"Generate a concise executive summary (2-3 paragraphs) based on the provided data. Highlight key metrics, trends, and actionable insights."},{role:"user",content:JSON.stringify(p,null,2)}],temperature:.5,maxTokens:512})).choices[0])==null?void 0:b.message)==null?void 0:v.content)||null}catch{return null}finally{m(!1)}},[R]),o=d.useCallback(async(p,b)=>{var v,u,h;if(!R)return"bar";try{const $=V(R),E=p.slice(0,5),A=(h=(u=(v=(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(E)}
1852
+ Purpose: ${b}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:v.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"}},[R]),k=d.useCallback(()=>{x(null)},[]),y=d.useCallback(()=>{var p;(p=S.current)==null||p.abort(),m(!1)},[]);return d.useEffect(()=>()=>{var p;(p=S.current)==null||p.abort()},[]),{generateReport:j,suggestSections:I,generateSummary:_,suggestChartType:o,loading:l,lastResult:g,history:w,clearResults:k,abort:y,isConfigured:!!R}}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.sections&&Array.isArray(l.sections)){const m=l.sections.map((g,x)=>({...g,id:g.id||`section_${x}`,order:g.order??x,config:g.config||{}}));return{id:l.id||`report_${Date.now()}`,name:l.name||"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:m,dataSources:l.dataSources,parameters:l.parameters,styles:l.styles}}}catch{}return null}function Oi(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 Ei=[{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 Di({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:m,renderReport:g}){const[x,w]=d.useState(""),N=d.useRef(null),{generateReport:S,loading:R,lastResult:j,isConfigured:I}=xa({config:t,dataSources:a,context:i,onReportGenerated:r}),_=async()=>{!x.trim()||R||await S(x)},o=y=>{var p;w(y.prompt),(p=N.current)==null||p.focus()},k=()=>{if(!(j!=null&&j.layout))return;const y=JSON.stringify(j.layout,null,2),p=new Blob([y],{type:"application/json"}),b=URL.createObjectURL(p),v=document.createElement("a");v.href=b,v.download=`${j.layout.name.replace(/\s+/g,"_")}.json`,v.click(),URL.revokeObjectURL(b)};return I?e.jsxs("div",{className:`nice-report-ai ${l||""}`,style:m,children:[s&&e.jsx("div",{className:"nice-report-ai__templates",children:Ei.map((y,p)=>e.jsxs("button",{type:"button",className:"nice-report-ai__template",onClick:()=>o(y),children:[e.jsx("span",{className:"nice-report-ai__template-icon",children:e.jsx(L.NiceIcon,{name:y.icon,size:24})}),e.jsx("span",{className:"nice-report-ai__template-name",children:y.name})]},p))}),e.jsxs("div",{className:"nice-report-ai__input-section",children:[e.jsx("textarea",{ref:N,value:x,onChange:y=>w(y.target.value),placeholder:n,className:"nice-report-ai__input",rows:3,disabled:R}),e.jsx("button",{type:"button",onClick:_,className:"nice-report-ai__submit",disabled:R||!x.trim(),children:R?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(y=>e.jsx("span",{className:"nice-report-ai__datasource",children:y.name},y.id))]}),j&&e.jsx("div",{className:"nice-report-ai__result",children:j.error?e.jsx("div",{className:"nice-report-ai__error",children:j.error}):j.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:j.layout.name}),j.layout.description&&e.jsx("span",{className:"nice-report-ai__report-desc",children:j.layout.description})]}),e.jsxs("div",{className:"nice-report-ai__result-meta",children:[e.jsxs("span",{className:"nice-report-ai__stat",children:[j.layout.sections.length," sections"]}),e.jsxs("span",{className:"nice-report-ai__stat",children:[j.layout.pageSize," ",j.layout.orientation]}),j.latencyMs&&e.jsxs("span",{className:"nice-report-ai__latency",children:[Math.round(j.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-report-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>r==null?void 0:r(j.layout),children:[e.jsx(L.NiceIcon,{name:"check",size:14})," Use Report"]}),e.jsxs("button",{type:"button",onClick:k,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:j.layout.sections.map((y,p)=>e.jsxs("div",{className:"nice-report-ai__section",children:[e.jsx("span",{className:"nice-report-ai__section-number",children:p+1}),e.jsx("span",{className:"nice-report-ai__section-icon",children:e.jsx(L.NiceIcon,{name:ba(y.type),size:16})}),e.jsx("span",{className:"nice-report-ai__section-type",children:y.type}),y.title&&e.jsx("span",{className:"nice-report-ai__section-title",children:y.title})]},y.id))})]}),c&&e.jsx("div",{className:"nice-report-ai__preview",children:g?g(j.layout):e.jsx(Bi,{layout:j.layout})}),j.suggestions&&j.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:j.suggestions.map((y,p)=>e.jsx("li",{children:y},p))})]}),e.jsxs("details",{className:"nice-report-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(j.layout,null,2)})]})]})}),e.jsx("style",{children:`
1879
1853
  .nice-report-ai {
1880
1854
  font-family: var(--nice-font-family, system-ui, sans-serif);
1881
1855
  }
@@ -2183,7 +2157,7 @@ Purpose: ${x}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:v.messa
2183
2157
  color: var(--nice-error, #c62828);
2184
2158
  border-radius: var(--nice-radius-md, 6px);
2185
2159
  }
2186
- `})]}):e.jsx("div",{className:`nice-report-ai nice-report-ai--disabled ${d||""}`,style:m,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function Ra(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 xi({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($,{name:Ra(a.type),size:14})}),e.jsx("span",{className:"report-preview__section-label",children:a.title||a.type})]},a.id))}),e.jsx("style",{children:`
2160
+ `})]}):e.jsx("div",{className:`nice-report-ai nice-report-ai--disabled ${l||""}`,style:m,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function ba(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 Bi({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:ba(a.type),size:14})}),e.jsx("span",{className:"report-preview__section-label",children:a.title||a.type})]},a.id))}),e.jsx("style",{children:`
2187
2161
  .report-preview {
2188
2162
  display: flex;
2189
2163
  justify-content: center;
@@ -2262,19 +2236,19 @@ Purpose: ${x}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:v.messa
2262
2236
  text-overflow: ellipsis;
2263
2237
  white-space: nowrap;
2264
2238
  }
2265
- `})]})}function La(i={}){const{config:a,generateDarkMode:r=!0,onThemeGenerated:t,onError:n}=i,s=ee(),[c,d]=o.useState(!1),[m,f]=o.useState(null),g=o.useRef(null),y=a||(s==null?void 0:s.config),k=o.useCallback(async l=>{var w,p,x,v;if(!y){const u="AI not configured";return n==null||n(u),{error:u}}d(!0);const N=performance.now();(w=g.current)==null||w.abort(),g.current=new AbortController;try{const u=K(y);let h="";switch(l.type){case"description":h=l.value;break;case"brand":h=`Create a theme for "${l.value.name}"${l.value.industry?` in the ${l.value.industry} industry`:""}${(p=l.value.keywords)!=null&&p.length?`. Keywords: ${l.value.keywords.join(", ")}`:""}`;break;case"colors":h=`Create a theme based on primary color ${l.value.primary}${l.value.secondary?` and secondary color ${l.value.secondary}`:""}`;break;case"image":h="Extract colors and create a theme from the provided image palette";break}const I=re(he,{description:h,generate_dark_mode:r?"true":"false"}),H=await u.chat({messages:[{role:"system",content:I.system},{role:"user",content:I.user}],temperature:.6,maxTokens:2048}),C=Je(H),z={theme:C.light||void 0,darkTheme:C.dark||void 0,rawResponse:(v=(x=H.choices[0])==null?void 0:x.message)==null?void 0:v.content,latencyMs:performance.now()-N,error:C.light?void 0:"Failed to generate theme",suggestions:vi(C.light)};return C.light&&(t==null||t(C.light,C.dark??void 0)),f(z),z}catch(u){const h=u instanceof Error?u.message:"Theme generation failed",I={error:h,latencyMs:performance.now()-N};return f(I),n==null||n(h),I}finally{d(!1)}},[y,r,t,n]),M=o.useCallback(async(l,N)=>{if(!y)return null;d(!0);try{const p=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:
2266
- ${JSON.stringify(l,null,2)}
2239
+ `})]})}function va(t={}){const{config:a,generateDarkMode:i=!0,onThemeGenerated:r,onError:n}=t,s=Q(),[c,l]=d.useState(!1),[m,g]=d.useState(null),x=d.useRef(null),w=a||(s==null?void 0:s.config),N=d.useCallback(async o=>{var y,p,b,v;if(!w){const u="AI not configured";return n==null||n(u),{error:u}}l(!0);const k=performance.now();(y=x.current)==null||y.abort(),x.current=new AbortController;try{const u=V(w);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`:""}${(p=o.value.keywords)!=null&&p.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 $=ee(pe,{description:h,generate_dark_mode:i?"true":"false"}),E=await u.chat({messages:[{role:"system",content:$.system},{role:"user",content:$.user}],temperature:.6,maxTokens:2048}),C=De(E),A={theme:C.light||void 0,darkTheme:C.dark||void 0,rawResponse:(v=(b=E.choices[0])==null?void 0:b.message)==null?void 0:v.content,latencyMs:performance.now()-k,error:C.light?void 0:"Failed to generate theme",suggestions:Fi(C.light)};return C.light&&(r==null||r(C.light,C.dark??void 0)),g(A),A}catch(u){const h=u instanceof Error?u.message:"Theme generation failed",$={error:h,latencyMs:performance.now()-k};return g($),n==null||n(h),$}finally{l(!1)}},[w,i,r,n]),S=d.useCallback(async(o,k)=>{if(!w)return null;l(!0);try{const p=await V(w).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:
2240
+ ${JSON.stringify(o,null,2)}
2267
2241
 
2268
- Adjustments: ${N}`}],temperature:.4,maxTokens:2048});return Je(p).light||null}catch{return null}finally{d(!1)}},[y]),T=o.useCallback(l=>{const N=[];return N.push(" /* Colors */"),Object.entries(l.colors).forEach(([w,p])=>{N.push(` --nice-${_e(w)}: ${p};`)}),N.push(`
2269
- /* Typography */`),Object.entries(l.typography).forEach(([w,p])=>{N.push(` --nice-${_e(w)}: ${p};`)}),N.push(`
2270
- /* Spacing */`),Object.entries(l.spacing).forEach(([w,p])=>{N.push(` --nice-spacing-${w}: ${p};`)}),N.push(`
2271
- /* Border Radius */`),Object.entries(l.borderRadius).forEach(([w,p])=>{N.push(` --nice-radius-${w}: ${p};`)}),N.push(`
2272
- /* Shadows */`),Object.entries(l.shadows).forEach(([w,p])=>{N.push(` --nice-shadow-${w}: ${p};`)}),N.push(`
2273
- /* Animations */`),Object.entries(l.animations).forEach(([w,p])=>{N.push(` --nice-${_e(w)}: ${p};`)}),`:root {
2274
- ${N.join(`
2242
+ Adjustments: ${k}`}],temperature:.4,maxTokens:2048});return De(p).light||null}catch{return null}finally{l(!1)}},[w]),R=d.useCallback(o=>{const k=[];return k.push(" /* Colors */"),Object.entries(o.colors).forEach(([y,p])=>{k.push(` --nice-${be(y)}: ${p};`)}),k.push(`
2243
+ /* Typography */`),Object.entries(o.typography).forEach(([y,p])=>{k.push(` --nice-${be(y)}: ${p};`)}),k.push(`
2244
+ /* Spacing */`),Object.entries(o.spacing).forEach(([y,p])=>{k.push(` --nice-spacing-${y}: ${p};`)}),k.push(`
2245
+ /* Border Radius */`),Object.entries(o.borderRadius).forEach(([y,p])=>{k.push(` --nice-radius-${y}: ${p};`)}),k.push(`
2246
+ /* Shadows */`),Object.entries(o.shadows).forEach(([y,p])=>{k.push(` --nice-shadow-${y}: ${p};`)}),k.push(`
2247
+ /* Animations */`),Object.entries(o.animations).forEach(([y,p])=>{k.push(` --nice-${be(y)}: ${p};`)}),`:root {
2248
+ ${k.join(`
2275
2249
  `)}
2276
- }`},[]),j=o.useCallback(l=>{const N={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
2277
- module.exports = ${JSON.stringify(N,null,2)}`},[]),A=o.useCallback(()=>{f(null)},[]),_=o.useCallback(()=>{var l;(l=g.current)==null||l.abort(),d(!1)},[]);return o.useEffect(()=>()=>{var l;(l=g.current)==null||l.abort()},[]),{generateTheme:k,adjustTheme:M,toCSSVariables:T,toTailwindConfig:j,loading:c,lastResult:m,clearResults:A,abort:_,isConfigured:!!y}}function Je(i){var a,r,t;try{const n=((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"",c=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,d=JSON.parse(c);if(d.light||d.theme)return{light:ve(d.light||d.theme),dark:d.dark?ve(d.dark):null};if(d.colors)return{light:ve(d),dark:null}}catch{}return{light:null,dark:null}}function ve(i){return{id:i.id||`theme_${Date.now()}`,name:i.name||"Generated Theme",description:i.description,mode:i.mode||"light",colors:{primary:"var(--nice-primary, #0066cc)",primaryLight:"#4d94db",primaryDark:"#004499",secondary:"var(--nice-text-secondary, #6c757d)",secondaryLight:"var(--nice-text-muted, #9ca3af)",secondaryDark:"var(--nice-text-secondary, #4b5563)",accent:"#ff6b35",background:"var(--nice-bg, #fff)",surface:"var(--nice-bg-secondary, #f8f9fa)",text:"var(--nice-text, #212529)",textMuted:"var(--nice-text-secondary, #6c757d)",textInverse:"var(--nice-bg, #fff)",border:"var(--nice-border, #dee2e6)",success:"var(--nice-success, #28a745)",warning:"var(--nice-warning, #ffc107)",error:"var(--nice-danger, #dc3545)",info:"var(--nice-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 var(--nice-overlay-5, rgba(0, 0, 0, 0.05))",md:"0 4px 6px var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",lg:"0 10px 15px var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",xl:"0 20px 25px var(--nice-overlay-10, 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 vi(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 _e(i){return i.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}const _i=[{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 wi({config:i,generateDarkMode:a=!0,onGenerate:r,showPresets:t=!0,showPreview:n=!0,className:s,style:c}){const[d,m]=o.useState("description"),[f,g]=o.useState(""),[y,k]=o.useState(""),[M,T]=o.useState(""),[j,A]=o.useState("var(--nice-primary, #0066cc)"),[_,l]=o.useState("light"),{generateTheme:N,toCSSVariables:w,toTailwindConfig:p,loading:x,lastResult:v,isConfigured:u}=La({config:i,generateDarkMode:a,onThemeGenerated:r}),h=async()=>{if(x)return;let O;switch(d){case"brand":if(!y.trim())return;O={type:"brand",value:{name:y,industry:M||void 0}};break;case"colors":O={type:"colors",value:{primary:j}};break;default:if(!f.trim())return;O={type:"description",value:f}}await N(O)},I=O=>{m("description"),g(O.prompt)},H=()=>{if(!(v!=null&&v.theme))return;const O=w(v.theme),B=new Blob([O],{type:"text/css"}),b=URL.createObjectURL(B),R=document.createElement("a");R.href=b,R.download=`${v.theme.name.replace(/\s+/g,"-").toLowerCase()}.css`,R.click(),URL.revokeObjectURL(b)},C=()=>{if(!(v!=null&&v.theme))return;const O=p(v.theme),B=new Blob([O],{type:"text/javascript"}),b=URL.createObjectURL(B),R=document.createElement("a");R.href=b,R.download="tailwind.config.js",R.click(),URL.revokeObjectURL(b)},z=_==="dark"&&(v!=null&&v.darkTheme)?v.darkTheme:v==null?void 0:v.theme;return u?e.jsxs("div",{className:`nice-theme-ai ${s||""}`,style:c,children:[t&&e.jsx("div",{className:"nice-theme-ai__presets",children:_i.map((O,B)=>e.jsxs("button",{type:"button",className:"nice-theme-ai__preset",onClick:()=>I(O),children:[e.jsx("span",{className:"nice-theme-ai__preset-icon",children:e.jsx($,{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 ${d==="description"?"nice-theme-ai__tab--active":""}`,onClick:()=>m("description"),children:[e.jsx($,{name:"edit",size:14})," Description"]}),e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${d==="brand"?"nice-theme-ai__tab--active":""}`,onClick:()=>m("brand"),children:[e.jsx($,{name:"tag",size:14})," Brand"]}),e.jsxs("button",{type:"button",className:`nice-theme-ai__tab ${d==="colors"?"nice-theme-ai__tab--active":""}`,onClick:()=>m("colors"),children:[e.jsx($,{name:"palette",size:14})," Colors"]})]}),e.jsxs("div",{className:"nice-theme-ai__input-section",children:[d==="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:x}),d==="brand"&&e.jsxs("div",{className:"nice-theme-ai__brand-inputs",children:[e.jsx("input",{type:"text",value:y,onChange:O=>k(O.target.value),placeholder:"Brand name",className:"nice-theme-ai__input",disabled:x}),e.jsx("input",{type:"text",value:M,onChange:O=>T(O.target.value),placeholder:"Industry (optional)",className:"nice-theme-ai__input",disabled:x})]}),d==="colors"&&e.jsx("div",{className:"nice-theme-ai__color-input",children:e.jsxs("label",{children:["Primary Color:",e.jsx("input",{type:"color",value:j,onChange:O=>A(O.target.value),className:"nice-theme-ai__color-picker",disabled:x}),e.jsx("span",{className:"nice-theme-ai__color-value",children:j})]})}),e.jsx("button",{type:"button",onClick:h,className:"nice-theme-ai__submit",disabled:x,children:x?e.jsx("span",{className:"nice-theme-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx($,{name:"wand",size:14})," Generate Theme"]})})]}),v&&z&&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:z.name}),z.description&&e.jsx("span",{className:"nice-theme-ai__theme-desc",children:z.description})]}),e.jsxs("div",{className:"nice-theme-ai__actions",children:[v.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($,{name:"sun",size:16})}),e.jsx("button",{type:"button","aria-label":"Dark mode",className:_==="dark"?"active":"",onClick:()=>l("dark"),children:e.jsx($,{name:"moon",size:16})})]}),e.jsxs("button",{type:"button",onClick:H,children:[e.jsx($,{name:"download",size:14})," CSS"]}),e.jsxs("button",{type:"button",onClick:C,children:[e.jsx($,{name:"download",size:14})," Tailwind"]})]})]}),n&&e.jsx(ji,{theme:z}),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(z.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:z.typography.fontFamily},children:[e.jsx("p",{style:{fontSize:z.typography.fontSize3xl,fontWeight:z.typography.fontWeightBold},children:"Heading 1"}),e.jsx("p",{style:{fontSize:z.typography.fontSizeLg},children:"Body text: The quick brown fox jumps over the lazy dog."}),e.jsx("p",{style:{fontFamily:z.typography.fontFamilyMono,fontSize:z.typography.fontSizeSm},children:'const code = "Monospace font"'})]})]})]}),e.jsx("style",{children:`
2250
+ }`},[]),j=d.useCallback(o=>{const k={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
2251
+ module.exports = ${JSON.stringify(k,null,2)}`},[]),I=d.useCallback(()=>{g(null)},[]),_=d.useCallback(()=>{var o;(o=x.current)==null||o.abort(),l(!1)},[]);return d.useEffect(()=>()=>{var o;(o=x.current)==null||o.abort()},[]),{generateTheme:N,adjustTheme:S,toCSSVariables:R,toTailwindConfig:j,loading:c,lastResult:m,clearResults:I,abort:_,isConfigured:!!w}}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.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:"var(--nice-primary, #0066cc)",primaryLight:"#4d94db",primaryDark:"#004499",secondary:"var(--nice-text-secondary, #6c757d)",secondaryLight:"var(--nice-text-muted, #9ca3af)",secondaryDark:"var(--nice-text-secondary, #4b5563)",accent:"#ff6b35",background:"var(--nice-bg, #fff)",surface:"var(--nice-bg-secondary, #f8f9fa)",text:"var(--nice-text, #212529)",textMuted:"var(--nice-text-secondary, #6c757d)",textInverse:"var(--nice-bg, #fff)",border:"var(--nice-border, #dee2e6)",success:"var(--nice-success, #28a745)",warning:"var(--nice-warning, #ffc107)",error:"var(--nice-danger, #dc3545)",info:"var(--nice-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 var(--nice-overlay-5, rgba(0, 0, 0, 0.05))",md:"0 4px 6px var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",lg:"0 10px 15px var(--nice-overlay-10, rgba(0, 0, 0, 0.1))",xl:"0 20px 25px var(--nice-overlay-10, 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 Fi(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 Ji=[{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 qi({config:t,generateDarkMode:a=!0,onGenerate:i,showPresets:r=!0,showPreview:n=!0,className:s,style:c}){const[l,m]=d.useState("description"),[g,x]=d.useState(""),[w,N]=d.useState(""),[S,R]=d.useState(""),[j,I]=d.useState("var(--nice-primary, #0066cc)"),[_,o]=d.useState("light"),{generateTheme:k,toCSSVariables:y,toTailwindConfig:p,loading:b,lastResult:v,isConfigured:u}=va({config:t,generateDarkMode:a,onThemeGenerated:i}),h=async()=>{if(b)return;let O;switch(l){case"brand":if(!w.trim())return;O={type:"brand",value:{name:w,industry:S||void 0}};break;case"colors":O={type:"colors",value:{primary:j}};break;default:if(!g.trim())return;O={type:"description",value:g}}await k(O)},$=O=>{m("description"),x(O.prompt)},E=()=>{if(!(v!=null&&v.theme))return;const O=y(v.theme),B=new Blob([O],{type:"text/css"}),f=URL.createObjectURL(B),z=document.createElement("a");z.href=f,z.download=`${v.theme.name.replace(/\s+/g,"-").toLowerCase()}.css`,z.click(),URL.revokeObjectURL(f)},C=()=>{if(!(v!=null&&v.theme))return;const O=p(v.theme),B=new Blob([O],{type:"text/javascript"}),f=URL.createObjectURL(B),z=document.createElement("a");z.href=f,z.download="tailwind.config.js",z.click(),URL.revokeObjectURL(f)},A=_==="dark"&&(v!=null&&v.darkTheme)?v.darkTheme:v==null?void 0:v.theme;return u?e.jsxs("div",{className:`nice-theme-ai ${s||""}`,style:c,children:[r&&e.jsx("div",{className:"nice-theme-ai__presets",children:Ji.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:()=>m("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:()=>m("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:()=>m("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:g,onChange:O=>x(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:b}),l==="brand"&&e.jsxs("div",{className:"nice-theme-ai__brand-inputs",children:[e.jsx("input",{type:"text",value:w,onChange:O=>N(O.target.value),placeholder:"Brand name",className:"nice-theme-ai__input",disabled:b}),e.jsx("input",{type:"text",value:S,onChange:O=>R(O.target.value),placeholder:"Industry (optional)",className:"nice-theme-ai__input",disabled:b})]}),l==="colors"&&e.jsx("div",{className:"nice-theme-ai__color-input",children:e.jsxs("label",{children:["Primary Color:",e.jsx("input",{type:"color",value:j,onChange:O=>I(O.target.value),className:"nice-theme-ai__color-picker",disabled:b}),e.jsx("span",{className:"nice-theme-ai__color-value",children:j})]})}),e.jsx("button",{type:"button",onClick:h,className:"nice-theme-ai__submit",disabled:b,children:b?e.jsx("span",{className:"nice-theme-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"wand",size:14})," Generate Theme"]})})]}),v&&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:[v.darkTheme&&e.jsxs("div",{className:"nice-theme-ai__mode-toggle",children:[e.jsx("button",{type:"button","aria-label":"Light mode",className:_==="light"?"active":"",onClick:()=>o("light"),children:e.jsx(L.NiceIcon,{name:"sun",size:16})}),e.jsx("button",{type:"button","aria-label":"Dark mode",className:_==="dark"?"active":"",onClick:()=>o("dark"),children:e.jsx(L.NiceIcon,{name:"moon",size:16})})]}),e.jsxs("button",{type:"button",onClick:E,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(Ui,{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:`
2278
2252
  .nice-theme-ai {
2279
2253
  font-family: var(--nice-font-family, system-ui, sans-serif);
2280
2254
  }
@@ -2545,7 +2519,7 @@ module.exports = ${JSON.stringify(N,null,2)}`},[]),A=o.useCallback(()=>{f(null)}
2545
2519
  .nice-theme-ai__typography {
2546
2520
  margin-top: var(--nice-space-5, 20px);
2547
2521
  }
2548
- `})]}):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 ji({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:`
2522
+ `})]}):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 Ui({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:`
2549
2523
  .theme-preview {
2550
2524
  background: var(--preview-bg);
2551
2525
  border: 1px solid var(--preview-border);
@@ -2591,13 +2565,13 @@ module.exports = ${JSON.stringify(N,null,2)}`},[]),A=o.useCallback(()=>{f(null)}
2591
2565
  cursor: text;
2592
2566
  width: 150px;
2593
2567
  }
2594
- `})]})}function Pa(i={}){const{config:a,targetDevice:r="responsive",onLayoutGenerated:t,onError:n}=i,s=ee(),[c,d]=o.useState(!1),[m,f]=o.useState(null),g=o.useRef(null),y=a||(s==null?void 0:s.config),k=o.useCallback(async(_,l)=>{var w,p,x;if(!y){const v="AI not configured";return n==null||n(v),{error:v}}d(!0);const N=performance.now();(w=g.current)==null||w.abort(),g.current=new AbortController;try{const v=K(y),u=`You are a UI layout expert. Generate a responsive layout based on the description.
2568
+ `})]})}function ya(t={}){const{config:a,targetDevice:i="responsive",onLayoutGenerated:r,onError:n}=t,s=Q(),[c,l]=d.useState(!1),[m,g]=d.useState(null),x=d.useRef(null),w=a||(s==null?void 0:s.config),N=d.useCallback(async(_,o)=>{var y,p,b;if(!w){const v="AI not configured";return n==null||n(v),{error:v}}l(!0);const k=performance.now();(y=x.current)==null||y.abort(),x.current=new AbortController;try{const v=V(w),u=`You are a UI layout expert. Generate a responsive layout based on the description.
2595
2569
  Return JSON with this structure:
2596
2570
  {
2597
2571
  "id": "unique_id",
2598
2572
  "name": "Layout Name",
2599
2573
  "description": "Description",
2600
- "type": "${l||"dashboard"}",
2574
+ "type": "${o||"dashboard"}",
2601
2575
  "container": {
2602
2576
  "direction": "row|column|grid",
2603
2577
  "gap": "16px",
@@ -2626,45 +2600,45 @@ Return JSON with this structure:
2626
2600
  "xl": "1280px",
2627
2601
  "2xl": "1536px"
2628
2602
  }
2629
- }`,h=await v.chat({messages:[{role:"system",content:u},{role:"user",content:`Create a ${r} layout: ${_}${l?` (type: ${l})`:""}`}],temperature:.5,maxTokens:2048}),I=ki(h),H={layout:I||void 0,rawResponse:(x=(p=h.choices[0])==null?void 0:p.message)==null?void 0:x.content,latencyMs:performance.now()-N,error:I?void 0:"Failed to generate layout",suggestions:Ni(I)};return I&&(t==null||t(I)),f(H),H}catch(v){const u=v instanceof Error?v.message:"Layout generation failed",h={error:u,latencyMs:performance.now()-N};return f(h),n==null||n(u),h}finally{d(!1)}},[y,r,t,n]),M=o.useCallback(_=>{let l=`.${_.id} {
2630
- `;if(l+=` display: ${_.container.direction==="grid"?"grid":"flex"};
2631
- `,_.container.direction==="grid"){if(_.container.gridColumns){const N=typeof _.container.gridColumns=="number"?`repeat(${_.container.gridColumns}, 1fr)`:_.container.gridColumns;l+=` grid-template-columns: ${N};
2632
- `}_.container.gridRows&&(l+=` grid-template-rows: ${_.container.gridRows};
2633
- `)}else l+=` flex-direction: ${_.container.direction};
2634
- `,_.container.wrap&&(l+=` flex-wrap: wrap;
2635
- `);return _.container.gap&&(l+=` gap: ${_.container.gap};
2636
- `),_.container.padding&&(l+=` padding: ${_.container.padding};
2637
- `),_.container.align&&(l+=` align-items: ${_.container.align};
2638
- `),_.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};
2639
- `),l+=`}
2640
-
2641
- `,_.regions.forEach(N=>{var w,p,x,v,u,h;l+=`.${_.id}__${N.id} {
2642
- `,(w=N.position)!=null&&w.gridColumn&&(l+=` grid-column: ${N.position.gridColumn};
2643
- `),(p=N.position)!=null&&p.gridRow&&(l+=` grid-row: ${N.position.gridRow};
2644
- `),(x=N.size)!=null&&x.width&&(l+=` width: ${N.size.width};
2645
- `),(v=N.size)!=null&&v.height&&(l+=` height: ${N.size.height};
2646
- `),(u=N.size)!=null&&u.minWidth&&(l+=` min-width: ${N.size.minWidth};
2647
- `),(h=N.size)!=null&&h.maxWidth&&(l+=` max-width: ${N.size.maxWidth};
2648
- `),l+=`}
2649
-
2650
- `}),_.breakpoints&&Object.entries(_.breakpoints).forEach(([N,w])=>{const p=_.regions.filter(x=>{var v;return(v=x.responsive)==null?void 0:v[N]});p.length>0&&(l+=`@media (max-width: ${w}) {
2651
- `,p.forEach(x=>{var u,h;const v=x.responsive[N];l+=` .${_.id}__${x.id} {
2652
- `,(u=v.size)!=null&&u.width&&(l+=` width: ${v.size.width};
2653
- `),(h=v.size)!=null&&h.height&&(l+=` height: ${v.size.height};
2654
- `),l+=` }
2655
- `}),l+=`}
2656
-
2657
- `)}),l},[]),T=o.useCallback(_=>{const l=_.regions.map(N=>` <div className="${_.id}__${N.id}">{/* ${N.type} */}</div>`).join(`
2603
+ }`,h=await v.chat({messages:[{role:"system",content:u},{role:"user",content:`Create a ${i} layout: ${_}${o?` (type: ${o})`:""}`}],temperature:.5,maxTokens:2048}),$=Hi(h),E={layout:$||void 0,rawResponse:(b=(p=h.choices[0])==null?void 0:p.message)==null?void 0:b.content,latencyMs:performance.now()-k,error:$?void 0:"Failed to generate layout",suggestions:Wi($)};return $&&(r==null||r($)),g(E),E}catch(v){const u=v instanceof Error?v.message:"Layout generation failed",h={error:u,latencyMs:performance.now()-k};return g(h),n==null||n(u),h}finally{l(!1)}},[w,i,r,n]),S=d.useCallback(_=>{let o=`.${_.id} {
2604
+ `;if(o+=` display: ${_.container.direction==="grid"?"grid":"flex"};
2605
+ `,_.container.direction==="grid"){if(_.container.gridColumns){const k=typeof _.container.gridColumns=="number"?`repeat(${_.container.gridColumns}, 1fr)`:_.container.gridColumns;o+=` grid-template-columns: ${k};
2606
+ `}_.container.gridRows&&(o+=` grid-template-rows: ${_.container.gridRows};
2607
+ `)}else o+=` flex-direction: ${_.container.direction};
2608
+ `,_.container.wrap&&(o+=` flex-wrap: wrap;
2609
+ `);return _.container.gap&&(o+=` gap: ${_.container.gap};
2610
+ `),_.container.padding&&(o+=` padding: ${_.container.padding};
2611
+ `),_.container.align&&(o+=` align-items: ${_.container.align};
2612
+ `),_.container.justify&&(o+=` justify-content: ${{start:"flex-start",end:"flex-end",center:"center",between:"space-between",around:"space-around",evenly:"space-evenly"}[_.container.justify]||_.container.justify};
2613
+ `),o+=`}
2614
+
2615
+ `,_.regions.forEach(k=>{var y,p,b,v,u,h;o+=`.${_.id}__${k.id} {
2616
+ `,(y=k.position)!=null&&y.gridColumn&&(o+=` grid-column: ${k.position.gridColumn};
2617
+ `),(p=k.position)!=null&&p.gridRow&&(o+=` grid-row: ${k.position.gridRow};
2618
+ `),(b=k.size)!=null&&b.width&&(o+=` width: ${k.size.width};
2619
+ `),(v=k.size)!=null&&v.height&&(o+=` height: ${k.size.height};
2620
+ `),(u=k.size)!=null&&u.minWidth&&(o+=` min-width: ${k.size.minWidth};
2621
+ `),(h=k.size)!=null&&h.maxWidth&&(o+=` max-width: ${k.size.maxWidth};
2622
+ `),o+=`}
2623
+
2624
+ `}),_.breakpoints&&Object.entries(_.breakpoints).forEach(([k,y])=>{const p=_.regions.filter(b=>{var v;return(v=b.responsive)==null?void 0:v[k]});p.length>0&&(o+=`@media (max-width: ${y}) {
2625
+ `,p.forEach(b=>{var u,h;const v=b.responsive[k];o+=` .${_.id}__${b.id} {
2626
+ `,(u=v.size)!=null&&u.width&&(o+=` width: ${v.size.width};
2627
+ `),(h=v.size)!=null&&h.height&&(o+=` height: ${v.size.height};
2628
+ `),o+=` }
2629
+ `}),o+=`}
2630
+
2631
+ `)}),o},[]),R=d.useCallback(_=>{const o=_.regions.map(k=>` <div className="${_.id}__${k.id}">{/* ${k.type} */}</div>`).join(`
2658
2632
  `);return`import React from 'react';
2659
2633
  import './${_.id}.css';
2660
2634
 
2661
- export function ${$a(_.name)}() {
2635
+ export function ${_a(_.name)}() {
2662
2636
  return (
2663
2637
  <div className="${_.id}">
2664
- ${l}
2638
+ ${o}
2665
2639
  </div>
2666
2640
  );
2667
- }`},[]),j=o.useCallback(()=>{f(null)},[]),A=o.useCallback(()=>{var _;(_=g.current)==null||_.abort(),d(!1)},[]);return o.useEffect(()=>()=>{var _;(_=g.current)==null||_.abort()},[]),{generateLayout:k,toCSS:M,toReactComponent:T,loading:c,lastResult:m,clearResults:j,abort:A,isConfigured:!!y}}function ki(i){var a,r,t;try{const n=((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"",c=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,d=JSON.parse(c);if(d.regions||d.container)return{id:d.id||`layout_${Date.now()}`,name:d.name||"Generated Layout",description:d.description,type:d.type||"dashboard",container:{direction:"grid",gap:"16px",padding:"20px",gridColumns:12,...d.container},regions:d.regions||[],breakpoints:d.breakpoints||{xs:"320px",sm:"640px",md:"768px",lg:"1024px",xl:"1280px","2xl":"1536px"},cssGrid:d.cssGrid,cssVariables:d.cssVariables}}catch{}return null}function Ni(i){if(!i)return[];const a=[],r=new Set(i.regions.map(t=>t.type));return r.has("header")||a.push("Consider adding a header region for navigation"),!r.has("sidebar")&&i.type==="dashboard"&&a.push("Add a sidebar for dashboard navigation"),i.regions.some(t=>!t.responsive)&&a.push("Add responsive breakpoints for mobile compatibility"),a.slice(0,3)}function $a(i){return i.replace(/[^a-zA-Z0-9]+(.)/g,(a,r)=>r.toUpperCase()).replace(/^./,a=>a.toUpperCase())}const Ci=[{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:r,showTypeSelector:t=!0,showPreview:n=!0,className:s,style:c,renderLayout:d}){const[m,f]=o.useState(""),[g,y]=o.useState(null),{generateLayout:k,toCSS:M,toReactComponent:T,loading:j,lastResult:A,isConfigured:_}=Pa({config:i,targetDevice:a,onLayoutGenerated:r}),l=async()=>{!m.trim()||j||await k(m,g||void 0)},N=()=>{if(!(A!=null&&A.layout))return;const p=M(A.layout),x=new Blob([p],{type:"text/css"}),v=URL.createObjectURL(x),u=document.createElement("a");u.href=v,u.download=`${A.layout.id}.css`,u.click(),URL.revokeObjectURL(v)},w=()=>{if(!(A!=null&&A.layout))return;const p=T(A.layout),x=new Blob([p],{type:"text/javascript"}),v=URL.createObjectURL(x),u=document.createElement("a");u.href=v,u.download=`${$a(A.layout.name)}.tsx`,u.click(),URL.revokeObjectURL(v)};return _?e.jsxs("div",{className:`nice-layout-ai ${s||""}`,style:c,children:[t&&e.jsx("div",{className:"nice-layout-ai__types",children:Ci.map(({type:p,icon:x,label:v})=>e.jsxs("button",{type:"button",className:`nice-layout-ai__type ${g===p?"nice-layout-ai__type--selected":""}`,onClick:()=>y(g===p?null:p),children:[e.jsx("span",{className:"nice-layout-ai__type-icon",children:e.jsx($,{name:x,size:20})}),e.jsx("span",{className:"nice-layout-ai__type-label",children:v})]},p))}),e.jsxs("div",{className:"nice-layout-ai__input-section",children:[e.jsx("textarea",{value:m,onChange:p=>f(p.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:j}),e.jsx("button",{type:"button",onClick:l,className:"nice-layout-ai__submit",disabled:j||!m.trim(),children:j?e.jsx("span",{className:"nice-layout-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx($,{name:"palette",size:14})," Generate Layout"]})})]}),A&&A.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:A.layout.name}),e.jsx("span",{className:"nice-layout-ai__layout-type",children:A.layout.type})]}),e.jsxs("div",{className:"nice-layout-ai__actions",children:[e.jsxs("button",{type:"button",onClick:()=>r==null?void 0:r(A.layout),children:[e.jsx($,{name:"check",size:14})," Use Layout"]}),e.jsxs("button",{type:"button",onClick:N,children:[e.jsx($,{name:"download",size:14})," CSS"]}),e.jsxs("button",{type:"button",onClick:w,children:[e.jsx($,{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:A.layout.regions.map(p=>e.jsx("span",{className:`nice-layout-ai__region nice-layout-ai__region--${p.type}`,children:p.type},p.id))})]}),n&&e.jsx("div",{className:"nice-layout-ai__preview",children:d?d(A.layout):e.jsx(Si,{layout:A.layout})}),e.jsxs("details",{className:"nice-layout-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(A.layout,null,2)})]})]}),e.jsx("style",{children:`
2641
+ }`},[]),j=d.useCallback(()=>{g(null)},[]),I=d.useCallback(()=>{var _;(_=x.current)==null||_.abort(),l(!1)},[]);return d.useEffect(()=>()=>{var _;(_=x.current)==null||_.abort()},[]),{generateLayout:N,toCSS:S,toReactComponent:R,loading:c,lastResult:m,clearResults:j,abort:I,isConfigured:!!w}}function Hi(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 Wi(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 _a(t){return t.replace(/[^a-zA-Z0-9]+(.)/g,(a,i)=>i.toUpperCase()).replace(/^./,a=>a.toUpperCase())}const Gi=[{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 Vi({config:t,targetDevice:a="responsive",onGenerate:i,showTypeSelector:r=!0,showPreview:n=!0,className:s,style:c,renderLayout:l}){const[m,g]=d.useState(""),[x,w]=d.useState(null),{generateLayout:N,toCSS:S,toReactComponent:R,loading:j,lastResult:I,isConfigured:_}=ya({config:t,targetDevice:a,onLayoutGenerated:i}),o=async()=>{!m.trim()||j||await N(m,x||void 0)},k=()=>{if(!(I!=null&&I.layout))return;const p=S(I.layout),b=new Blob([p],{type:"text/css"}),v=URL.createObjectURL(b),u=document.createElement("a");u.href=v,u.download=`${I.layout.id}.css`,u.click(),URL.revokeObjectURL(v)},y=()=>{if(!(I!=null&&I.layout))return;const p=R(I.layout),b=new Blob([p],{type:"text/javascript"}),v=URL.createObjectURL(b),u=document.createElement("a");u.href=v,u.download=`${_a(I.layout.name)}.tsx`,u.click(),URL.revokeObjectURL(v)};return _?e.jsxs("div",{className:`nice-layout-ai ${s||""}`,style:c,children:[r&&e.jsx("div",{className:"nice-layout-ai__types",children:Gi.map(({type:p,icon:b,label:v})=>e.jsxs("button",{type:"button",className:`nice-layout-ai__type ${x===p?"nice-layout-ai__type--selected":""}`,onClick:()=>w(x===p?null:p),children:[e.jsx("span",{className:"nice-layout-ai__type-icon",children:e.jsx(L.NiceIcon,{name:b,size:20})}),e.jsx("span",{className:"nice-layout-ai__type-label",children:v})]},p))}),e.jsxs("div",{className:"nice-layout-ai__input-section",children:[e.jsx("textarea",{value:m,onChange:p=>g(p.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:j}),e.jsx("button",{type:"button",onClick:o,className:"nice-layout-ai__submit",disabled:j||!m.trim(),children:j?e.jsx("span",{className:"nice-layout-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx(L.NiceIcon,{name:"palette",size:14})," Generate Layout"]})})]}),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:k,children:[e.jsx(L.NiceIcon,{name:"download",size:14})," CSS"]}),e.jsxs("button",{type:"button",onClick:y,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(p=>e.jsx("span",{className:`nice-layout-ai__region nice-layout-ai__region--${p.type}`,children:p.type},p.id))})]}),n&&e.jsx("div",{className:"nice-layout-ai__preview",children:l?l(I.layout):e.jsx(Ki,{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:`
2668
2642
  .nice-layout-ai {
2669
2643
  font-family: var(--nice-font-family, system-ui, sans-serif);
2670
2644
  }
@@ -2888,7 +2862,7 @@ ${l}
2888
2862
  font-size: 12px;
2889
2863
  overflow-x: auto;
2890
2864
  }
2891
- `})]}):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 Si({layout:i}){const a=r=>({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-bg, #fce4ec)"})[r]||"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(r=>{var t,n,s,c,d,m;return e.jsx("div",{className:"layout-preview__region",style:{gridColumn:(t=r.position)==null?void 0:t.gridColumn,gridRow:(n=r.position)==null?void 0:n.gridRow,width:(s=r.size)==null?void 0:s.width,height:((c=r.size)==null?void 0:c.height)||"80px",minWidth:(d=r.size)==null?void 0:d.minWidth,maxWidth:(m=r.size)==null?void 0:m.maxWidth,background:a(r.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:r.type},r.id)})})}function Ia(i={}){const{config:a,wcagLevel:r="AA",onAuditComplete:t,onError:n}=i,s=ee(),[c,d]=o.useState(!1),[m,f]=o.useState(null),g=o.useRef(null),y=a||(s==null?void 0:s.config),k=o.useCallback(async(l,N)=>{var w;if(!y){const p="AI not configured";return n==null||n(p),Me("html",r,p)}d(!0),(w=g.current)==null||w.abort(),g.current=new AbortController;try{const p=K(y),x=`You are a WCAG accessibility expert. Analyze the provided HTML code for accessibility issues at WCAG ${r} level.
2865
+ `})]}):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 Ki({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-bg, #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,m;return e.jsx("div",{className:"layout-preview__region",style:{gridColumn:(r=i.position)==null?void 0:r.gridColumn,gridRow:(n=i.position)==null?void 0:n.gridRow,width:(s=i.size)==null?void 0:s.width,height:((c=i.size)==null?void 0:c.height)||"80px",minWidth:(l=i.size)==null?void 0:l.minWidth,maxWidth:(m=i.size)==null?void 0:m.maxWidth,background:a(i.type),borderRadius:"6px",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:500,color:"var(--nice-text-secondary, #666)",border:"1px dashed var(--nice-border, #ccc)"},children:i.type},i.id)})})}function wa(t={}){const{config:a,wcagLevel:i="AA",onAuditComplete:r,onError:n}=t,s=Q(),[c,l]=d.useState(!1),[m,g]=d.useState(null),x=d.useRef(null),w=a||(s==null?void 0:s.config),N=d.useCallback(async(o,k)=>{var y;if(!w){const p="AI not configured";return n==null||n(p),ke("html",i,p)}l(!0),(y=x.current)==null||y.abort(),x.current=new AbortController;try{const p=V(w),b=`You are a WCAG accessibility expert. Analyze the provided HTML code for accessibility issues at WCAG ${i} level.
2892
2866
 
2893
2867
  Return JSON with this exact structure:
2894
2868
  {
@@ -2922,10 +2896,10 @@ Focus on:
2922
2896
  7. Heading hierarchy
2923
2897
  8. Landmark regions
2924
2898
  9. Semantic HTML usage
2925
- 10. Language attributes`,v=await p.chat({messages:[{role:"system",content:x},{role:"user",content:`Analyze this HTML for accessibility:
2926
- ${N?`Context: ${N}
2899
+ 10. Language attributes`,v=await p.chat({messages:[{role:"system",content:b},{role:"user",content:`Analyze this HTML for accessibility:
2900
+ ${k?`Context: ${k}
2927
2901
 
2928
- `:""}${l}`}],temperature:.3,maxTokens:4096}),u=zi(v,"html",r);return f(u),t==null||t(u),u}catch(p){const x=p instanceof Error?p.message:"Audit failed";return n==null||n(x),Me("html",r,x)}finally{d(!1)}},[y,r,t,n]),M=o.useCallback((l,N)=>{const w=ye(ge(l)),p=ye(ge(N)),x=(Math.max(w,p)+.05)/(Math.min(w,p)+.05),v={foreground:l,background:N,ratio:Math.round(x*100)/100,passesAA:x>=4.5,passesAALarge:x>=3,passesAAA:x>=7,passesAAALarge:x>=4.5};return v.passesAA||(v.suggestions=Ai(l,N,4.5)),v},[]),T=o.useCallback(async l=>{var N,w;if(!y)return n==null||n("AI not configured"),[];try{const h=(((w=(N=(await K(y).chat({messages:[{role:"system",content:`Analyze the HTML for ARIA attribute issues.
2902
+ `:""}${o}`}],temperature:.3,maxTokens:4096}),u=Yi(v,"html",i);return g(u),r==null||r(u),u}catch(p){const b=p instanceof Error?p.message:"Audit failed";return n==null||n(b),ke("html",i,b)}finally{l(!1)}},[w,i,r,n]),S=d.useCallback((o,k)=>{const y=he(me(o)),p=he(me(k)),b=(Math.max(y,p)+.05)/(Math.min(y,p)+.05),v={foreground:o,background:k,ratio:Math.round(b*100)/100,passesAA:b>=4.5,passesAALarge:b>=3,passesAAA:b>=7,passesAAALarge:b>=4.5};return v.passesAA||(v.suggestions=Qi(o,k,4.5)),v},[]),R=d.useCallback(async o=>{var k,y;if(!w)return n==null||n("AI not configured"),[];try{const h=(((y=(k=(await V(w).chat({messages:[{role:"system",content:`Analyze the HTML for ARIA attribute issues.
2929
2903
  Return JSON array:
2930
2904
  [{
2931
2905
  "element": "<button>...",
@@ -2936,10 +2910,10 @@ Return JSON array:
2936
2910
  "issues": ["Missing aria-label"],
2937
2911
  "suggestions": ["Add aria-label='Submit form'"]
2938
2912
  }]`},{role:"user",content:`Validate ARIA in:
2939
- ${l}`}],temperature:.2,maxTokens:2048})).choices[0])==null?void 0:N.message)==null?void 0:w.content)||"").match(/\[[\s\S]*\]/);if(h)return JSON.parse(h[0])}catch{}return[]},[y,n]),j=o.useCallback(async l=>{var N,w;if(!y)return n==null||n("AI not configured"),l;try{const v=((w=(N=(await K(y).chat({messages:[{role:"system",content:`You are an accessibility expert. Improve the HTML to be fully WCAG ${r} compliant.
2913
+ ${o}`}],temperature:.2,maxTokens:2048})).choices[0])==null?void 0:k.message)==null?void 0:y.content)||"").match(/\[[\s\S]*\]/);if(h)return JSON.parse(h[0])}catch{}return[]},[w,n]),j=d.useCallback(async o=>{var k,y;if(!w)return n==null||n("AI not configured"),o;try{const v=((y=(k=(await V(w).chat({messages:[{role:"system",content:`You are an accessibility expert. Improve the HTML to be fully WCAG ${i} compliant.
2940
2914
  Add proper ARIA attributes, semantic HTML, keyboard handlers, focus management.
2941
2915
  Return only the improved HTML code.`},{role:"user",content:`Make this accessible:
2942
- ${l}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:N.message)==null?void 0:w.content)||"",u=v.match(/```(?:html)?\s*([\s\S]*?)```/);return u?u[1].trim():v.trim()}catch{return l}},[y,r,n]),A=o.useCallback(()=>{f(null)},[]),_=o.useCallback(()=>{var l;(l=g.current)==null||l.abort(),d(!1)},[]);return o.useEffect(()=>()=>{var l;(l=g.current)==null||l.abort()},[]),{analyzeHTML:k,checkContrast:M,validateARIA:T,suggestAccessibleCode:j,loading:c,lastAudit:m,clearAudit:A,abort:_,isConfigured:!!y}}function Me(i,a,r){return{timestamp:new Date,target:i,wcagLevel:a,issues:r?[{id:"error",category:"semantic-html",severity:"critical",wcagCriteria:"N/A",wcagLevel:"A",title:"Audit Error",description:r,impact:"Audit could not complete",suggestion:"Try again or check configuration"}]:[],score:r?0:100,summary:{critical:r?1:0,serious:0,moderate:0,minor:0,passed:0},recommendations:[]}}function zi(i,a,r){var t,n,s;try{const c=((n=(t=i.choices[0])==null?void 0:t.message)==null?void 0:n.content)||"",m=((s=(c.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,c])[1])==null?void 0:s.trim())||c,f=JSON.parse(m),g=(f.issues||[]).map((k,M)=>({id:k.id||`issue_${M}`,category:k.category||"semantic-html",severity:k.severity||"moderate",wcagCriteria:k.wcagCriteria||"N/A",wcagLevel:k.wcagLevel||"A",title:k.title||"Unknown Issue",description:k.description||"",element:k.element,selector:k.selector,impact:k.impact||"",suggestion:k.suggestion||"",codeExample:k.codeExample})),y={critical:g.filter(k=>k.severity==="critical").length,serious:g.filter(k=>k.severity==="serious").length,moderate:g.filter(k=>k.severity==="moderate").length,minor:g.filter(k=>k.severity==="minor").length,passed:0};return{timestamp:new Date,target:a,wcagLevel:r,issues:g,score:f.score??Ti(y),summary:y,recommendations:f.recommendations||[]}}catch{return Me(a,r,"Failed to parse audit results")}}function Ti(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 ye(i){const[a,r,t]=[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*r+.0722*t}function Ai(i,a,r){const t=[],n=ge(i),s=ge(a),c={r:Math.max(0,n.r-40),g:Math.max(0,n.g-40),b:Math.max(0,n.b-40)},d=`#${c.r.toString(16).padStart(2,"0")}${c.g.toString(16).padStart(2,"0")}${c.b.toString(16).padStart(2,"0")}`,m=ye(c),f=ye(s);(Math.max(m,f)+.05)/(Math.min(m,f)+.05)>=r&&t.push(`Try darker foreground: ${d}`);const y={r:Math.min(255,s.r+40),g:Math.min(255,s.g+40),b:Math.min(255,s.b+40)},k=`#${y.r.toString(16).padStart(2,"0")}${y.g.toString(16).padStart(2,"0")}${y.b.toString(16).padStart(2,"0")}`;return t.push(`Try lighter background: ${k}`),t}const we={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 Ri({config:i,wcagLevel:a="AA",onAuditComplete:r,showContrastChecker:t=!0,className:n,style:s,renderIssue:c}){const[d,m]=o.useState(""),[f,g]=o.useState("var(--nice-text, #333333)"),[y,k]=o.useState("var(--nice-bg, #fff)"),[M,T]=o.useState(null),{analyzeHTML:j,checkContrast:A,suggestAccessibleCode:_,loading:l,lastAudit:N,isConfigured:w}=Ia({config:i,wcagLevel:a,onAuditComplete:r}),p=async()=>{!d.trim()||l||await j(d)},x=()=>{const u=A(f,y);T(u)},v=async()=>{if(!d.trim())return;const u=await _(d);m(u)};return w?e.jsxs("div",{className:`nice-a11y-ai ${n||""}`,style:s,children:[t&&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=>k(u.target.value)}),e.jsx("input",{type:"text",value:y,onChange:u=>k(u.target.value)})]}),e.jsx("button",{type:"button",onClick:x,children:"Check"})]}),M&&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:[M.ratio,":1"]}),e.jsxs("div",{className:"nice-a11y-ai__passes",children:[e.jsxs("span",{className:M.passesAA?"pass":"fail",children:["AA: ",e.jsx($,{name:M.passesAA?"check":"close",size:14})]}),e.jsxs("span",{className:M.passesAALarge?"pass":"fail",children:["AA Large:"," ",e.jsx($,{name:M.passesAALarge?"check":"close",size:14})]}),e.jsxs("span",{className:M.passesAAA?"pass":"fail",children:["AAA: ",e.jsx($,{name:M.passesAAA?"check":"close",size:14})]})]})]}),M.suggestions&&M.suggestions.length>0&&e.jsx("div",{className:"nice-a11y-ai__suggestions",children:M.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:d,onChange:u=>m(u.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:p,disabled:l||!d.trim(),children:l?e.jsx("span",{className:"nice-a11y-ai__spinner"}):e.jsxs(e.Fragment,{children:[e.jsx($,{name:"search",size:14})," Analyze"]})}),e.jsxs("button",{type:"button",onClick:v,disabled:l||!d.trim(),children:[e.jsx($,{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:we[u.severity].bg,borderLeftColor:we[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($,{name:we[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:`
2916
+ ${o}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:k.message)==null?void 0:y.content)||"",u=v.match(/```(?:html)?\s*([\s\S]*?)```/);return u?u[1].trim():v.trim()}catch{return o}},[w,i,n]),I=d.useCallback(()=>{g(null)},[]),_=d.useCallback(()=>{var o;(o=x.current)==null||o.abort(),l(!1)},[]);return d.useEffect(()=>()=>{var o;(o=x.current)==null||o.abort()},[]),{analyzeHTML:N,checkContrast:S,validateARIA:R,suggestAccessibleCode:j,loading:c,lastAudit:m,clearAudit:I,abort:_,isConfigured:!!w}}function ke(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 Yi(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)||"",m=((s=(c.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,c])[1])==null?void 0:s.trim())||c,g=JSON.parse(m),x=(g.issues||[]).map((N,S)=>({id:N.id||`issue_${S}`,category:N.category||"semantic-html",severity:N.severity||"moderate",wcagCriteria:N.wcagCriteria||"N/A",wcagLevel:N.wcagLevel||"A",title:N.title||"Unknown Issue",description:N.description||"",element:N.element,selector:N.selector,impact:N.impact||"",suggestion:N.suggestion||"",codeExample:N.codeExample})),w={critical:x.filter(N=>N.severity==="critical").length,serious:x.filter(N=>N.severity==="serious").length,moderate:x.filter(N=>N.severity==="moderate").length,minor:x.filter(N=>N.severity==="minor").length,passed:0};return{timestamp:new Date,target:a,wcagLevel:i,issues:x,score:g.score??Xi(w),summary:w,recommendations:g.recommendations||[]}}catch{return ke(a,i,"Failed to parse audit results")}}function Xi(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 Qi(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")}`,m=he(c),g=he(s);(Math.max(m,g)+.05)/(Math.min(m,g)+.05)>=i&&r.push(`Try darker foreground: ${l}`);const w={r:Math.min(255,s.r+40),g:Math.min(255,s.g+40),b:Math.min(255,s.b+40)},N=`#${w.r.toString(16).padStart(2,"0")}${w.g.toString(16).padStart(2,"0")}${w.b.toString(16).padStart(2,"0")}`;return r.push(`Try lighter background: ${N}`),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 Zi({config:t,wcagLevel:a="AA",onAuditComplete:i,showContrastChecker:r=!0,className:n,style:s,renderIssue:c}){const[l,m]=d.useState(""),[g,x]=d.useState("var(--nice-text, #333333)"),[w,N]=d.useState("var(--nice-bg, #fff)"),[S,R]=d.useState(null),{analyzeHTML:j,checkContrast:I,suggestAccessibleCode:_,loading:o,lastAudit:k,isConfigured:y}=wa({config:t,wcagLevel:a,onAuditComplete:i}),p=async()=>{!l.trim()||o||await j(l)},b=()=>{const u=I(g,w);R(u)},v=async()=>{if(!l.trim())return;const u=await _(l);m(u)};return y?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:g,onChange:u=>x(u.target.value)}),e.jsx("input",{type:"text",value:g,onChange:u=>x(u.target.value)})]}),e.jsxs("label",{children:["Background",e.jsx("input",{type:"color",value:w,onChange:u=>N(u.target.value)}),e.jsx("input",{type:"text",value:w,onChange:u=>N(u.target.value)})]}),e.jsx("button",{type:"button",onClick:b,children:"Check"})]}),S&&e.jsxs("div",{className:"nice-a11y-ai__contrast-result",children:[e.jsx("div",{className:"nice-a11y-ai__contrast-preview",style:{color:g,background:w},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=>m(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:p,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:v,disabled:o||!l.trim(),children:[e.jsx(L.NiceIcon,{name:"settings",size:14})," Auto-Fix"]})]})]}),k&&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:k.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:[k.summary.critical," Critical"]}),e.jsxs("span",{className:"serious",children:[k.summary.serious," Serious"]}),e.jsxs("span",{className:"moderate",children:[k.summary.moderate," Moderate"]}),e.jsxs("span",{className:"minor",children:[k.summary.minor," Minor"]})]})]}),e.jsx("div",{className:"nice-a11y-ai__issues",children:k.issues.map(u=>c?c(u):e.jsxs("div",{className:"nice-a11y-ai__issue",style:{background:ve[u.severity].bg,borderLeftColor:ve[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:ve[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))}),k.recommendations.length>0&&e.jsxs("div",{className:"nice-a11y-ai__recommendations",children:[e.jsx("h4",{children:"General Recommendations"}),e.jsx("ul",{children:k.recommendations.map((u,h)=>e.jsx("li",{children:u},h))})]})]}),e.jsx("style",{children:`
2943
2917
  .nice-a11y-ai {
2944
2918
  font-family: var(--nice-font-family, system-ui, sans-serif);
2945
2919
  }
@@ -3237,14 +3211,14 @@ ${l}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:N.message)==nu
3237
3211
  margin-bottom: var(--nice-space-1-5, 6px);
3238
3212
  font-size: 14px;
3239
3213
  }
3240
- `})]}):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 je=[{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 Oa(i={}){const{config:a,defaultLibrary:r="lucide",defaultStyle:t="outline",maxSuggestions:n=10,onSuggestion:s,onError:c}=i,d=ee(),[m,f]=o.useState(!1),[g,y]=o.useState(null),k=o.useRef(null),M=a||(d==null?void 0:d.config),T=o.useCallback(w=>{const p=w.toLowerCase(),x=p.split(/\s+/);return je.map(v=>{let u=0;return v.name===p?u+=100:v.name.includes(p)&&(u+=50),x.forEach(h=>{v.keywords.forEach(I=>{I===h?u+=30:(I.includes(h)||h.includes(I))&&(u+=15)})}),v.category===p&&(u+=20),{id:`icon_${v.name}`,name:v.name,displayName:v.name.replace(/-/g," ").replace(/\b\w/g,h=>h.toUpperCase()),category:v.category,style:t,library:r,relevanceScore:u,keywords:v.keywords,svgPath:v.svgPath}}).filter(v=>v.relevanceScore>0).sort((v,u)=>u.relevanceScore-v.relevanceScore).slice(0,n)},[r,t,n]),j=o.useCallback(async(w,p)=>{var u,h,I,H;const x=performance.now(),v=T(w);if(!M){const C={query:w,suggestions:v,latencyMs:performance.now()-x};return y(C),s==null||s(C),C}f(!0),(u=k.current)==null||u.abort(),k.current=new AbortController;try{const C=K(M),z=p?`
3214
+ `})]}):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 ye=[{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 ja(t={}){const{config:a,defaultLibrary:i="lucide",defaultStyle:r="outline",maxSuggestions:n=10,onSuggestion:s,onError:c}=t,l=Q(),[m,g]=d.useState(!1),[x,w]=d.useState(null),N=d.useRef(null),S=a||(l==null?void 0:l.config),R=d.useCallback(y=>{const p=y.toLowerCase(),b=p.split(/\s+/);return ye.map(v=>{let u=0;return v.name===p?u+=100:v.name.includes(p)&&(u+=50),b.forEach(h=>{v.keywords.forEach($=>{$===h?u+=30:($.includes(h)||h.includes($))&&(u+=15)})}),v.category===p&&(u+=20),{id:`icon_${v.name}`,name:v.name,displayName:v.name.replace(/-/g," ").replace(/\b\w/g,h=>h.toUpperCase()),category:v.category,style:r,library:i,relevanceScore:u,keywords:v.keywords,svgPath:v.svgPath}}).filter(v=>v.relevanceScore>0).sort((v,u)=>u.relevanceScore-v.relevanceScore).slice(0,n)},[i,r,n]),j=d.useCallback(async(y,p)=>{var u,h,$,E;const b=performance.now(),v=R(y);if(!S){const C={query:y,suggestions:v,latencyMs:performance.now()-b};return w(C),s==null||s(C),C}g(!0),(u=N.current)==null||u.abort(),N.current=new AbortController;try{const C=V(S),A=p?`
3241
3215
  Context:
3242
3216
  - Component type: ${p.componentType||"any"}
3243
3217
  - Purpose: ${p.purpose||"general"}
3244
3218
  - Related icons: ${((h=p.relatedIcons)==null?void 0:h.join(", "))||"none"}
3245
3219
  - Theme: ${p.theme||"light"}
3246
- - Preferred style: ${p.preferredStyle||t}
3247
- - Preferred library: ${p.preferredLibrary||r}`:"",b=(((H=(I=(await C.chat({messages:[{role:"system",content:`You are an icon recommendation expert. Suggest icons based on user query.
3220
+ - Preferred style: ${p.preferredStyle||r}
3221
+ - Preferred library: ${p.preferredLibrary||i}`:"",f=(((E=($=(await C.chat({messages:[{role:"system",content:`You are an icon recommendation expert. Suggest icons based on user query.
3248
3222
  Return JSON array of 5-10 icon suggestions:
3249
3223
  [{
3250
3224
  "name": "icon-name",
@@ -3255,7 +3229,7 @@ Return JSON array of 5-10 icon suggestions:
3255
3229
  "usage": "Brief usage description"
3256
3230
  }]
3257
3231
 
3258
- Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Suggest icons for: "${w}"${z}`}],temperature:.5,maxTokens:1024})).choices[0])==null?void 0:I.message)==null?void 0:H.content)||"").match(/\[[\s\S]*\]/);let R=[];if(b)try{R=JSON.parse(b[0]).map((V,J)=>({id:V.id||`ai_icon_${J}`,name:V.name||"unknown",displayName:V.displayName||V.name||"Unknown",category:V.category||"action",style:(p==null?void 0:p.preferredStyle)||t,library:(p==null?void 0:p.preferredLibrary)||r,relevanceScore:V.relevanceScore||50,keywords:V.keywords||[],usage:V.usage}))}catch{}const q=Li(v,R,n),U={query:w,suggestions:q,latencyMs:performance.now()-x};return y(U),s==null||s(U),U}catch(C){const z=C instanceof Error?C.message:"Suggestion failed",O={query:w,suggestions:v,latencyMs:performance.now()-x,error:z};return y(O),c==null||c(z),O}finally{f(!1)}},[M,r,t,n,T,s,c]),A=o.useCallback(w=>je.filter(p=>p.category===w).map(p=>({id:`icon_${p.name}`,name:p.name,displayName:p.name.replace(/-/g," ").replace(/\b\w/g,x=>x.toUpperCase()),category:p.category,style:t,library:r,relevanceScore:100,keywords:p.keywords,svgPath:p.svgPath})),[r,t]),_=o.useMemo(()=>{const w=new Set;return je.forEach(p=>w.add(p.category)),Array.from(w)},[]),l=o.useCallback(()=>{y(null)},[]),N=o.useCallback(()=>{var w;(w=k.current)==null||w.abort(),f(!1)},[]);return o.useEffect(()=>()=>{var w;(w=k.current)==null||w.abort()},[]),{suggestIcons:j,localSearch:T,getByCategory:A,categories:_,loading:m,lastResult:g,clearResults:l,abort:N,isConfigured:!!M}}function Li(i,a,r){const t=new Set,n=[];for(const s of i)t.has(s.name)||(t.add(s.name),n.push(s));for(const s of a)!t.has(s.name)&&n.length<r&&(t.add(s.name),n.push(s));return n.slice(0,r)}function Pi({config:i,defaultLibrary:a="lucide",defaultStyle:r="outline",maxSuggestions:t=10,onSelect:n,showCategories:s=!0,showPreview:c=!0,className:d,style:m}){const[f,g]=o.useState(""),[y,k]=o.useState(null),[M,T]=o.useState(null),{suggestIcons:j,getByCategory:A,categories:_,loading:l,lastResult:N}=Oa({config:i,defaultLibrary:a,defaultStyle:r,maxSuggestions:t}),w=async()=>{f.trim()&&(k(null),await j(f))},p=h=>{h.key==="Enter"&&w()},x=h=>{y===h?k(null):(k(h),g(""))},v=h=>{T(h),n==null||n(h)},u=y?A(y):(N==null?void 0:N.suggestions)||[];return e.jsxs("div",{className:`nice-icon-ai ${d||""}`,style:m,children:[e.jsxs("div",{className:"nice-icon-ai__search",children:[e.jsx("input",{type:"text",value:f,onChange:h=>g(h.target.value),onKeyDown:p,placeholder:"Search icons... (e.g., 'save', 'notification', 'user profile')",className:"nice-icon-ai__input",disabled:l}),e.jsx("button",{type:"button",onClick:w,className:"nice-icon-ai__search-btn",disabled:l||!f.trim(),children:l?e.jsx("span",{className:"nice-icon-ai__spinner"}):e.jsx($,{name:"search",size:16})})]}),s&&e.jsx("div",{className:"nice-icon-ai__categories",children:_.map(h=>e.jsx("button",{type:"button",className:`nice-icon-ai__category ${y===h?"nice-icon-ai__category--selected":""}`,onClick:()=>x(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 ${(M==null?void 0:M.id)===h.id?"nice-icon-ai__icon--selected":""}`,onClick:()=>v(h),title:h.displayName,children:[e.jsx(qe,{icon:h}),e.jsx("span",{className:"nice-icon-ai__icon-name",children:h.displayName})]},h.id))}),c&&M&&e.jsxs("div",{className:"nice-icon-ai__preview",children:[e.jsx("div",{className:"nice-icon-ai__preview-icon",children:e.jsx(qe,{icon:M,size:64})}),e.jsxs("div",{className:"nice-icon-ai__preview-info",children:[e.jsx("div",{className:"nice-icon-ai__preview-name",children:M.displayName}),e.jsxs("div",{className:"nice-icon-ai__preview-details",children:[e.jsxs("span",{children:["Category: ",M.category]}),e.jsxs("span",{children:["Library: ",M.library]})]}),e.jsx("div",{className:"nice-icon-ai__preview-keywords",children:M.keywords.map(h=>e.jsx("span",{className:"nice-icon-ai__keyword",children:h},h))}),M.usage&&e.jsx("div",{className:"nice-icon-ai__preview-usage",children:M.usage}),e.jsxs("div",{className:"nice-icon-ai__preview-actions",children:[e.jsxs("button",{type:"button",onClick:()=>n==null?void 0:n(M),children:[e.jsx($,{name:"check",size:14})," Use Icon"]}),e.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(M.name)},children:[e.jsx($,{name:"clipboard",size:14})," Copy Name"]}),M.svgPath&&e.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(`<svg viewBox="0 0 24 24"><path d="${M.svgPath}" /></svg>`)},children:[e.jsx($,{name:"clipboard",size:14})," Copy SVG"]})]})]})]}),e.jsx("style",{children:`
3232
+ Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Suggest icons for: "${y}"${A}`}],temperature:.5,maxTokens:1024})).choices[0])==null?void 0:$.message)==null?void 0:E.content)||"").match(/\[[\s\S]*\]/);let z=[];if(f)try{z=JSON.parse(f[0]).map((J,q)=>({id:J.id||`ai_icon_${q}`,name:J.name||"unknown",displayName:J.displayName||J.name||"Unknown",category:J.category||"action",style:(p==null?void 0:p.preferredStyle)||r,library:(p==null?void 0:p.preferredLibrary)||i,relevanceScore:J.relevanceScore||50,keywords:J.keywords||[],usage:J.usage}))}catch{}const U=et(v,z,n),H={query:y,suggestions:U,latencyMs:performance.now()-b};return w(H),s==null||s(H),H}catch(C){const A=C instanceof Error?C.message:"Suggestion failed",O={query:y,suggestions:v,latencyMs:performance.now()-b,error:A};return w(O),c==null||c(A),O}finally{g(!1)}},[S,i,r,n,R,s,c]),I=d.useCallback(y=>ye.filter(p=>p.category===y).map(p=>({id:`icon_${p.name}`,name:p.name,displayName:p.name.replace(/-/g," ").replace(/\b\w/g,b=>b.toUpperCase()),category:p.category,style:r,library:i,relevanceScore:100,keywords:p.keywords,svgPath:p.svgPath})),[i,r]),_=d.useMemo(()=>{const y=new Set;return ye.forEach(p=>y.add(p.category)),Array.from(y)},[]),o=d.useCallback(()=>{w(null)},[]),k=d.useCallback(()=>{var y;(y=N.current)==null||y.abort(),g(!1)},[]);return d.useEffect(()=>()=>{var y;(y=N.current)==null||y.abort()},[]),{suggestIcons:j,localSearch:R,getByCategory:I,categories:_,loading:m,lastResult:x,clearResults:o,abort:k,isConfigured:!!S}}function et(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 at({config:t,defaultLibrary:a="lucide",defaultStyle:i="outline",maxSuggestions:r=10,onSelect:n,showCategories:s=!0,showPreview:c=!0,className:l,style:m}){const[g,x]=d.useState(""),[w,N]=d.useState(null),[S,R]=d.useState(null),{suggestIcons:j,getByCategory:I,categories:_,loading:o,lastResult:k}=ja({config:t,defaultLibrary:a,defaultStyle:i,maxSuggestions:r}),y=async()=>{g.trim()&&(N(null),await j(g))},p=h=>{h.key==="Enter"&&y()},b=h=>{w===h?N(null):(N(h),x(""))},v=h=>{R(h),n==null||n(h)},u=w?I(w):(k==null?void 0:k.suggestions)||[];return e.jsxs("div",{className:`nice-icon-ai ${l||""}`,style:m,children:[e.jsxs("div",{className:"nice-icon-ai__search",children:[e.jsx("input",{type:"text",value:g,onChange:h=>x(h.target.value),onKeyDown:p,placeholder:"Search icons... (e.g., 'save', 'notification', 'user profile')",className:"nice-icon-ai__input",disabled:o}),e.jsx("button",{type:"button",onClick:y,className:"nice-icon-ai__search-btn",disabled:o||!g.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:_.map(h=>e.jsx("button",{type:"button",className:`nice-icon-ai__category ${w===h?"nice-icon-ai__category--selected":""}`,onClick:()=>b(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:()=>v(h),title:h.displayName,children:[e.jsx(Be,{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(Be,{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:`
3259
3233
  .nice-icon-ai {
3260
3234
  font-family: var(--nice-font-family, system-ui, sans-serif);
3261
3235
  }
@@ -3452,4 +3426,4 @@ Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Sugges
3452
3426
  color: white;
3453
3427
  border: none;
3454
3428
  }
3455
- `})]})}function qe({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=ke;exports.AnthropicProvider=ba;exports.AzureOpenAIProvider=xa;exports.CHART_CONFIG_TEMPLATE=ue;exports.CODE_COMPLETION_TEMPLATE=pe;exports.CostTracker=ja;exports.DATA_GRID_FILTER_TEMPLATE=oe;exports.DATA_GRID_SORT_TEMPLATE=le;exports.FORM_BUILDER_TEMPLATE=de;exports.GroqProvider=_a;exports.InMemoryCostStorage=$e;exports.LocalStorageCostStorage=wa;exports.NiceAIHintBubble=ze;exports.NiceAIProvider=Ha;exports.NiceAccessibilityAI=Ri;exports.NiceChartAI=ei;exports.NiceCodeEditorAI=ci;exports.NiceDataGridAI=Gr;exports.NiceDataLabeler=Or;exports.NiceFormBuilderAI=Yr;exports.NiceIconSuggestorAI=Pi;exports.NiceLayoutAI=Mi;exports.NiceMLStudio=$r;exports.NiceModelInference=Er;exports.NiceReportBuilderAI=bi;exports.NiceThemeGeneratorAI=wi;exports.NiceWorkflowDesignerAI=pi;exports.OllamaProvider=va;exports.OpenAIProvider=ya;exports.PROMPT_TEMPLATES=be;exports.REPORT_LAYOUT_TEMPLATE=fe;exports.RateLimiter=Ue;exports.ResilientLLMClient=ka;exports.SUMMARIZE_DATA_TEMPLATE=Ce;exports.THEME_GENERATOR_TEMPLATE=he;exports.TRANSLATION_TEMPLATE=Ne;exports.WORKFLOW_GENERATOR_TEMPLATE=me;exports.build3DSceneContext=la;exports.buildAudioContext=oa;exports.buildChartContext=lr;exports.buildCodeEditorContext=sa;exports.buildColorPickerContext=Pe;exports.buildDataGridContext=or;exports.buildDatePickerContext=Le;exports.buildDiagramLayoutContext=ma;exports.buildFormFillContext=ta;exports.buildGameEngineContext=pa;exports.buildGraphicsContext=da;exports.buildHtmlEditorContext=ca;exports.buildIconSearchContext=ua;exports.buildNumberInputContext=Ae;exports.buildPresentationGenerateContext=fa;exports.buildSelectContext=Re;exports.buildSlideDesignContext=ha;exports.buildTextInputContext=Te;exports.buildValidationContext=na;exports.colorControlContext=Rr;exports.compileTemplate=re;exports.createLLMProvider=ne;exports.createProviderFromConfig=K;exports.createResilientClient=Na;exports.createResilientClientWithDefaults=qr;exports.dateControlContext=Ar;exports.getTemplate=Dr;exports.getTemplatesByCategory=Br;exports.listTemplates=Fr;exports.numberControlContext=zr;exports.parseJSONResponse=Ke;exports.parseSSEStream=Ge;exports.selectControlContext=Tr;exports.textControlContext=Sr;exports.useAI3DHint=vr;exports.useAIAudioHint=xr;exports.useAICodeHint=yr;exports.useAIColorHint=fr;exports.useAIContext=ee;exports.useAIDateHint=mr;exports.useAIDiagramLayout=kr;exports.useAIFormFill=gr;exports.useAIGraphicsHint=_r;exports.useAIHtmlHint=br;exports.useAIIconSearch=wr;exports.useAINpcHint=jr;exports.useAINumberHint=ur;exports.useAIPresentationGenerate=Nr;exports.useAISelectHint=pr;exports.useAISlideDesign=Cr;exports.useAITextHint=dr;exports.useAIValidation=hr;exports.useAccessibilityAI=Ia;exports.useChartAI=Sa;exports.useCodeEditorAI=za;exports.useCostTracker=Vr;exports.useDataGridAI=Ca;exports.useFormBuilderAI=Ma;exports.useIconSuggestorAI=Oa;exports.useLayoutAI=Pa;exports.useNiceAIHint=Q;exports.useReportBuilderAI=Aa;exports.useThemeGeneratorAI=La;exports.useWorkflowDesignerAI=Ta;exports.withAIHint=Mr;
3429
+ `})]})}function Be({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=_e;exports.AnthropicProvider=ra;exports.AzureOpenAIProvider=na;exports.CHART_CONFIG_TEMPLATE=oe;exports.CODE_COMPLETION_TEMPLATE=le;exports.CostTracker=la;exports.DATA_GRID_FILTER_TEMPLATE=ne;exports.DATA_GRID_SORT_TEMPLATE=se;exports.FORM_BUILDER_TEMPLATE=ce;exports.GroqProvider=ca;exports.InMemoryCostStorage=Ie;exports.LocalStorageCostStorage=oa;exports.NiceAIHintBubble=Ne;exports.NiceAIProvider=Na;exports.NiceAccessibilityAI=Zi;exports.NiceChartAI=_i;exports.NiceCodeEditorAI=Ti;exports.NiceDataGridAI=gi;exports.NiceDataLabeler=ri;exports.NiceFormBuilderAI=xi;exports.NiceIconSuggestorAI=at;exports.NiceLayoutAI=Vi;exports.NiceMLStudio=ii;exports.NiceModelInference=si;exports.NiceReportBuilderAI=Di;exports.NiceThemeGeneratorAI=qi;exports.NiceWorkflowDesignerAI=Mi;exports.OllamaProvider=sa;exports.OpenAIProvider=ta;exports.PROMPT_TEMPLATES=ge;exports.REPORT_LAYOUT_TEMPLATE=ue;exports.RateLimiter=Fe;exports.ResilientLLMClient=da;exports.SUMMARIZE_DATA_TEMPLATE=je;exports.THEME_GENERATOR_TEMPLATE=pe;exports.TRANSLATION_TEMPLATE=we;exports.WORKFLOW_GENERATOR_TEMPLATE=de;exports.build3DSceneContext=Ye;exports.buildAudioContext=Ke;exports.buildChartContext=Ra;exports.buildCodeEditorContext=Ge;exports.buildColorPickerContext=Re;exports.buildDataGridContext=Aa;exports.buildDatePickerContext=Ae;exports.buildDiagramLayoutContext=ea;exports.buildFormFillContext=He;exports.buildGameEngineContext=Ze;exports.buildGraphicsContext=Xe;exports.buildHtmlEditorContext=Ve;exports.buildIconSearchContext=Qe;exports.buildNumberInputContext=Se;exports.buildPresentationGenerateContext=aa;exports.buildSelectContext=Te;exports.buildSlideDesignContext=ia;exports.buildTextInputContext=Ce;exports.buildValidationContext=We;exports.colorControlContext=Za;exports.compileTemplate=ee;exports.createLLMProvider=ie;exports.createProviderFromConfig=V;exports.createResilientClient=ua;exports.createResilientClientWithDefaults=pi;exports.dateControlContext=Qa;exports.getTemplate=ci;exports.getTemplatesByCategory=oi;exports.listTemplates=li;exports.numberControlContext=Ya;exports.parseJSONResponse=Ue;exports.parseSSEStream=qe;exports.selectControlContext=Xa;exports.textControlContext=Ka;exports.useAI3DHint=Fa;exports.useAIAudioHint=Ba;exports.useAICodeHint=Ea;exports.useAIColorHint=Pa;exports.useAIContext=Q;exports.useAIDateHint=La;exports.useAIDiagramLayout=Ha;exports.useAIFormFill=Oa;exports.useAIGraphicsHint=Ja;exports.useAIHtmlHint=Da;exports.useAIIconSearch=qa;exports.useAINpcHint=Ua;exports.useAINumberHint=za;exports.useAIPresentationGenerate=Wa;exports.useAISelectHint=Ma;exports.useAISlideDesign=Ga;exports.useAITextHint=Ia;exports.useAIValidation=$a;exports.useAccessibilityAI=wa;exports.useChartAI=ha;exports.useCodeEditorAI=ga;exports.useCostTracker=di;exports.useDataGridAI=pa;exports.useFormBuilderAI=ma;exports.useIconSuggestorAI=ja;exports.useLayoutAI=ya;exports.useNiceAIHint=X;exports.useReportBuilderAI=xa;exports.useThemeGeneratorAI=va;exports.useWorkflowDesignerAI=fa;exports.withAIHint=Va;