@nice2dev/ui-ai 1.0.20 → 1.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,21 +1,47 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),o=require("react");class Be{constructor(a={},t){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1,this.config={maxRequestsPerMinute:a.maxRequestsPerMinute??30,maxTokensPerSession:a.maxTokensPerSession??1e4,warnThresholdPercent:a.warnThresholdPercent??80},this.onWarning=t}canRequest(){return this.pruneOldTimestamps(),!(this.timestamps.length>=this.config.maxRequestsPerMinute||this.tokenCount>=this.config.maxTokensPerSession)}recordRequest(){return this.canRequest()?(this.timestamps.push(Date.now()),!0):!1}recordTokens(a){this.tokenCount+=a,this.checkWarning()}getStatus(){this.pruneOldTimestamps();const a=this.config.maxTokensPerSession>0?this.tokenCount/this.config.maxTokensPerSession*100:0,t=this.config.maxRequestsPerMinute>0?this.timestamps.length/this.config.maxRequestsPerMinute*100:0;return{requestsThisMinute:this.timestamps.length,tokensThisSession:this.tokenCount,isLimited:!this.canRequest(),isWarning:a>=this.config.warnThresholdPercent||t>=this.config.warnThresholdPercent}}reset(){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1}pruneOldTimestamps(){const a=Date.now()-6e4;this.timestamps=this.timestamps.filter(t=>t>a)}checkWarning(){var t;if(this.warningEmitted)return;this.getStatus().isWarning&&(this.warningEmitted=!0,(t=this.onWarning)==null||t.call(this))}}const Fe=o.createContext(null);function ja({config:i,rateLimits:a,enabled:t=!0,onRateLimitWarning:r,children:n}){const s=o.useRef(null);s.current||(s.current=new Be(a,r));const m=o.useCallback(()=>s.current.getStatus(),[]),c=o.useMemo(()=>({config:i,enabled:t,rateLimiter:s.current,getRateLimitStatus:m}),[i,t,m]);return e.jsx(Fe.Provider,{value:c,children:n})}function X(){return o.useContext(Fe)}async function*Je(i,a){var s,m,c,g,f,j,w,N,S;const t=(s=i.body)==null?void 0:s.getReader();if(!t)throw new Error("Response body is not readable");const r=new TextDecoder;let n="";try{for(;!(a!=null&&a.aborted);){const{done:$,value:k}=await t.read();if($)break;n+=r.decode(k,{stream:!0});const P=n.split(`
2
- `);n=P.pop()??"";for(const h of P){const d=h.trim();if(!(!d||d===":")){if(d.startsWith("data:")){const v=d.slice(5).trim();if(v==="[DONE]"){yield{token:"",done:!0};return}try{const C=JSON.parse(v),p=((g=(c=(m=C.choices)==null?void 0:m[0])==null?void 0:c.delta)==null?void 0:g.content)??"",_=((j=(f=C.choices)==null?void 0:f[0])==null?void 0:j.finish_reason)==="stop";(p||_)&&(yield{token:p,done:_,usage:C.usage})}catch{v&&(yield{token:v,done:!1})}continue}try{const v=JSON.parse(d),C=v.text??v.content??v.token??"";C&&(yield{token:C,done:!1})}catch{d&&(yield{token:d,done:!1})}}}}if(n.trim()){const $=n.trim();if($.startsWith("data:")){const k=$.slice(5).trim();if(k&&k!=="[DONE]")try{const h=((S=(N=(w=JSON.parse(k).choices)==null?void 0:w[0])==null?void 0:N.delta)==null?void 0:S.content)??"";h&&(yield{token:h,done:!0})}catch{yield{token:k,done:!0}}}}}finally{t.releaseLock()}}async function qe(i){var t,r,n,s;const a=await i.json();if((n=(r=(t=a.choices)==null?void 0:t[0])==null?void 0:r.message)!=null&&n.content)return{text:a.choices[0].message.content,usage:a.usage};if((s=a.message)!=null&&s.content)return{text:a.message.content};if(typeof a.text=="string")return{text:a.text};if(typeof a.content=="string")return{text:a.content};if(typeof a.response=="string")return{text:a.response};throw new Error("Unrecognized AI response format")}const ie=new Map;function $e(i,a){const t=a?{...i,fieldValue:void 0,formContext:void 0}:i;return JSON.stringify(t)}function ka(i,a){const t=[],r=a.systemPrompt??"You are a helpful assistant providing concise contextual hints for form fields. Keep responses short (1-3 sentences). Be specific and actionable.";t.push({role:"system",content:r});const n=[];if(i.fieldLabel&&n.push(`Field: "${i.fieldLabel}"`),i.fieldType&&n.push(`Type: ${i.fieldType}`),!a.privacyMode&&i.fieldValue!==void 0){const m=typeof i.fieldValue=="string"?i.fieldValue:JSON.stringify(i.fieldValue);n.push(`Current value: ${m}`)}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"),c=require("react");class qe{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=c.createContext(null);function za({config:i,rateLimits:a,enabled:r=!0,onRateLimitWarning:t,children:n}){const s=c.useRef(null);s.current||(s.current=new qe(a,t));const l=c.useCallback(()=>s.current.getStatus(),[]),o=c.useMemo(()=>({config:i,enabled:r,rateLimiter:s.current,getRateLimitStatus:l}),[i,r,l]);return e.jsx(We.Provider,{value:o,children:n})}function Q(){return c.useContext(We)}async function*Ge(i,a){var s,l,o,f,h,y,w,C,S;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:P,value:k}=await r.read();if(P)break;n+=t.decode(k,{stream:!0});const $=n.split(`
2
+ `);n=$.pop()??"";for(const g of $){const d=g.trim();if(!(!d||d===":")){if(d.startsWith("data:")){const j=d.slice(5).trim();if(j==="[DONE]"){yield{token:"",done:!0};return}try{const N=JSON.parse(j),m=((f=(o=(l=N.choices)==null?void 0:l[0])==null?void 0:o.delta)==null?void 0:f.content)??"",v=((y=(h=N.choices)==null?void 0:h[0])==null?void 0:y.finish_reason)==="stop";(m||v)&&(yield{token:m,done:v,usage:N.usage})}catch{j&&(yield{token:j,done:!1})}continue}try{const j=JSON.parse(d),N=j.text??j.content??j.token??"";N&&(yield{token:N,done:!1})}catch{d&&(yield{token:d,done:!1})}}}}if(n.trim()){const P=n.trim();if(P.startsWith("data:")){const k=P.slice(5).trim();if(k&&k!=="[DONE]")try{const g=((S=(C=(w=JSON.parse(k).choices)==null?void 0:w[0])==null?void 0:C.delta)==null?void 0:S.content)??"";g&&(yield{token:g,done:!0})}catch{yield{token:k,done:!0}}}}}finally{r.releaseLock()}}async function Ve(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 se=new Map;function Oe(i,a){const r=a?{...i,fieldValue:void 0,formContext:void 0}:i;return JSON.stringify(r)}function La(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 l=typeof i.fieldValue=="string"?i.fieldValue:JSON.stringify(i.fieldValue);n.push(`Current value: ${l}`)}i.validationRules&&Object.keys(i.validationRules).length>0&&n.push(`Validation: ${JSON.stringify(i.validationRules)}`),i.schema&&Object.keys(i.schema).length>0&&n.push(`Schema: ${JSON.stringify(i.schema)}`),!a.privacyMode&&i.formContext&&Object.keys(i.formContext).length>0&&n.push(`Form context: ${JSON.stringify(i.formContext)}`),i.customPrompt&&n.push(i.customPrompt);const s=n.length>0?`Provide a helpful hint for this field:
3
3
  ${n.join(`
4
- `)}`:"Provide a helpful suggestion.";return t.push({role:"user",content:s}),t}function V(i={},a={}){i=i??{},a=a??{};const{debounceMs:t=500,disabled:r=!1}=a,n=X(),[s,m]=o.useState(""),[c,g]=o.useState(!1),[f,j]=o.useState(null),[w,N]=o.useState(!1),S=o.useRef(null),$=o.useRef(0),k=o.useCallback(async()=>{var y,A,R;if(!n||!n.enabled||r)return;const{config:d,rateLimiter:v}=n;if(!v.recordRequest()){j("Rate limit exceeded. Please wait before requesting another hint.");return}const C=$e(i,d.privacyMode??!1),p=ie.get(C);if(p){m(p),g(!1),j(null),N(!1);return}(y=S.current)==null||y.abort();const _=new AbortController;S.current=_,g(!0),j(null),m(""),N(!1);const b=ka(i,d),u=d.stream!==!1;try{const l={"Content-Type":"application/json",...d.headers};d.apiKey&&(l.Authorization=`Bearer ${d.apiKey}`);const x=JSON.stringify({model:d.model??"gpt-3.5-turbo",messages:b,temperature:d.temperature??.7,max_tokens:d.maxTokens??256,stream:u}),M=await fetch(d.endpoint,{method:"POST",headers:l,body:x,signal:_.signal});if(!M.ok){const z=await M.text().catch(()=>M.statusText);throw new Error(`AI request failed (${M.status}): ${z}`)}if(u){N(!0);let z="";for await(const D of Je(M,_.signal))if(_.signal.aborted||(z+=D.token,m(z),(A=D.usage)!=null&&A.completion_tokens&&v.recordTokens(D.usage.completion_tokens),D.done))break;if(z.length>0){const D=Math.ceil(z.length/4);v.recordTokens(D)}ie.set(C,z)}else{const z=await qe(M);m(z.text),ie.set(C,z.text),(R=z.usage)!=null&&R.completion_tokens?v.recordTokens(z.usage.completion_tokens):v.recordTokens(Math.ceil(z.text.length/4))}}catch(l){if(l instanceof DOMException&&l.name==="AbortError")return;j(l instanceof Error?l.message:"AI hint request failed")}finally{_.signal.aborted||(g(!1),N(!1))}},[n,i,r]);o.useEffect(()=>{if(!n||!n.enabled||r)return;const d=setTimeout(k,t);return()=>clearTimeout(d)},[i==null?void 0:i.fieldLabel,i==null?void 0:i.fieldType,i==null?void 0:i.fieldValue,i==null?void 0:i.customPrompt,t,r,n==null?void 0:n.enabled,$.current]),o.useEffect(()=>()=>{var d;(d=S.current)==null||d.abort()},[]);const P=o.useCallback(()=>{var d;(d=S.current)==null||d.abort(),g(!1),N(!1)},[]),h=o.useCallback(()=>{if(n){const d=$e(i,n.config.privacyMode??!1);ie.delete(d)}$.current+=1,k()},[n,i,k]);return!n||!n.enabled?{text:"",loading:!1,error:null,streaming:!1,abort:()=>{},refresh:()=>{},hint:null,fetchHint:async()=>{}}:{text:s,loading:c,error:f,streaming:w,abort:P,refresh:h,hint:s?{content:s}:null,fetchHint:async()=>{await k()}}}function Na(){return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("path",{d:"M12 3l1.5 5.5L19 10l-5.5 1.5L12 17l-1.5-5.5L5 10l5.5-1.5z"}),e.jsx("path",{d:"M19 15l.5 2 2 .5-2 .5-.5 2-.5-2-2-.5 2-.5z"}),e.jsx("path",{d:"M5 19l.5 1.5 1.5.5-1.5.5-.5 1.5-.5-1.5-1.5-.5 1.5-.5z"})]})}function Ca(i,a){if(i!=="auto"||!a)return i==="auto"?"top":i;const t=a.top,r=window.innerHeight-a.bottom,n=a.left,s=window.innerWidth-a.right,m=Math.max(t,r,n,s);return m===t?"top":m===r?"bottom":m===s?"right":"left"}function Sa(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 ke=o.forwardRef(({context:i,position:a="auto",debounceMs:t=500,showOnHover:r=!1,triggerIcon:n,className:s,style:m},c)=>{var C;const g=X(),[f,j]=o.useState(!1),[w,N]=o.useState(!1),S=o.useRef(null),$=o.useRef(null),k=V(i,{debounceMs:t,disabled:!w});o.useEffect(()=>{if(!f)return;const p=_=>{var u,y;const b=_.target;(u=S.current)!=null&&u.contains(b)||(y=$.current)!=null&&y.contains(b)||(j(!1),N(!1))};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[f]),o.useEffect(()=>{if(!f)return;const p=_=>{_.key==="Escape"&&(j(!1),N(!1),k.abort())};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[f,k]);const P=o.useCallback(p=>{if(p.stopPropagation(),r)return;const _=!f;j(_),N(_)},[f,r]),h=o.useCallback(()=>{r&&(j(!0),N(!0))},[r]),d=o.useCallback(()=>{r&&(j(!1),N(!1))},[r]);if(!g||!g.enabled)return null;const v=Ca(a,((C=S.current)==null?void 0:C.getBoundingClientRect())??null);return e.jsxs("span",{ref:c,className:s,style:{position:"relative",display:"inline-flex",...m},onMouseEnter:h,onMouseLeave:d,children:[e.jsx("button",{ref:S,type:"button",onClick:P,"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(Na,{})}),f&&e.jsxs("div",{ref:$,role:"tooltip",className:"ntd-ai-popover",style:Sa(v),children:[k.loading&&!k.text&&e.jsxs("div",{className:"ntd-ai-loading",style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{display:"inline-block",width:12,height:12,border:"2px solid var(--ntd-ai-border, #45475a)",borderTopColor:"var(--ntd-ai-trigger-color, #a78bfa)",borderRadius:"50%",animation:"ntd-ai-spin 0.8s linear infinite"}}),e.jsx("span",{style:{opacity:.6},children:"Thinking..."})]}),k.text&&e.jsxs("div",{className:"ntd-ai-content",children:[k.text,k.streaming&&e.jsx("span",{className:"ntd-ai-cursor",style:{display:"inline-block",width:2,height:"1em",backgroundColor:"var(--ntd-ai-trigger-color, #a78bfa)",marginLeft:1,animation:"ntd-ai-blink 0.8s step-end infinite",verticalAlign:"text-bottom"}})]}),k.error&&e.jsx("div",{className:"ntd-ai-error",style:{color:"var(--ntd-ai-error, #f38ba8)"},children:k.error}),k.text&&!k.streaming&&e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:4,marginTop:6,paddingTop:6,borderTop:"1px solid var(--ntd-ai-border, #45475a)"},children:[e.jsx("button",{type:"button",onClick:()=>k.refresh(),className:"ntd-ai-action",style:{fontSize:11,padding:"2px 6px",border:"1px solid var(--ntd-ai-border, #45475a)",borderRadius:4,background:"transparent",color:"inherit",cursor:"pointer"},children:"↻ Refresh"}),e.jsx("button",{type:"button",onClick:()=>{var p;(p=navigator.clipboard)==null||p.writeText(k.text)},className:"ntd-ai-action",style:{fontSize:11,padding:"2px 6px",border:"1px solid var(--ntd-ai-border, #45475a)",borderRadius:4,background:"transparent",color:"inherit",cursor:"pointer"},children:"⎘ Copy"})]})]})]})});ke.displayName="NiceAIHintBubble";function Ne(i,a,t){return{fieldLabel:i,fieldType:"text",fieldValue:a,validationRules:{...(t==null?void 0:t.maxLength)!=null?{maxLength:t.maxLength}:{},...t!=null&&t.pattern?{pattern:t.pattern}:{}},customPrompt:t!=null&&t.placeholder?`Placeholder: "${t.placeholder}". Suggest content or correct grammar.`:"Suggest content, correct grammar, or auto-complete the text."}}function Ce(i,a,t){return{fieldLabel:i,fieldType:"number",fieldValue:a,validationRules:{...(t==null?void 0:t.min)!=null?{min:t.min}:{},...(t==null?void 0:t.max)!=null?{max:t.max}:{},...(t==null?void 0:t.step)!=null?{step:t.step}:{}},customPrompt:t!=null&&t.unit?`Unit: ${t.unit}. Suggest a reasonable value or range for this field.`:"Suggest a reasonable value or range for this field based on the label and constraints."}}function Se(i,a,t){return{fieldLabel:i,fieldType:t!=null&&t.multiple?"multi-select":"select",fieldValue:a,schema:t!=null&&t.options?{availableOptions:t.options.slice(0,20).map(r=>r.label)}:{},customPrompt:"Suggest the most likely selection. Explain why this option is recommended."}}function Te(i,a,t){const r=a instanceof Date?a.toISOString().split("T")[0]:a;return{fieldLabel:i,fieldType:"date",fieldValue:r,validationRules:{...t!=null&&t.min?{min:t.min}:{},...t!=null&&t.max?{max:t.max}:{},...t!=null&&t.disableWeekends?{noWeekends:!0}:{}},customPrompt:'Suggest a date. For example: "next business day", "end of month", "in 2 weeks". Explain your suggestion briefly.'}}function Ae(i,a,t){return{fieldLabel:i,fieldType:"color",fieldValue:a,schema:t!=null&&t.palette?{currentPalette:t.palette}:{},customPrompt:t!=null&&t.industry?`Industry: ${t.industry}. Suggest a color palette (3-5 hex colors) suitable for this context.`:"Suggest a color or palette of colors that works well for this context. Provide hex values."}}function Ta(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 Aa(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 Ue(i,a){return{fieldLabel:"Form auto-fill",fieldType:"form",schema:{fields:a},customPrompt:`User description: "${i}"
5
- Parse this description and return suggested values for each field as JSON: { ${a.map(t=>`"${t.label}": "value"`).join(", ")} }`}}function He(i,a,t,r,n){return{fieldLabel:i,fieldType:a,fieldValue:t,validationRules:n==null?void 0:n.rules,customPrompt:`Current validation error: "${r}". Provide a friendly, specific error message with an example of a valid value. Do NOT say "field is required" — instead explain what the user should enter.`}}function Ra(i,a,t){const r=o.useMemo(()=>Ne(i,a,t),[i,a,t==null?void 0:t.placeholder,t==null?void 0:t.maxLength,t==null?void 0:t.pattern]);return V(r,t)}function Ma(i,a,t){const r=o.useMemo(()=>Ce(i,a,t),[i,a,t==null?void 0:t.min,t==null?void 0:t.max,t==null?void 0:t.step,t==null?void 0:t.unit]);return V(r,t)}function Pa(i,a,t){const r=o.useMemo(()=>Se(i,a,t),[i,a,t==null?void 0:t.multiple]);return V(r,t)}function $a(i,a,t){const r=o.useMemo(()=>Te(i,a,t),[i,a,t==null?void 0:t.min,t==null?void 0:t.max,t==null?void 0:t.disableWeekends]);return V(r,t)}function Ia(i,a,t){const r=o.useMemo(()=>Ae(i,a,t),[i,a,t==null?void 0:t.industry]);return V(r,t)}function za(i,a,t,r,n){const s=o.useMemo(()=>r?He(i,a,t,r,n):{fieldLabel:i,fieldType:a},[i,a,t,r]);return V(s,{...n,disabled:!r||(n==null?void 0:n.disabled)})}function La(i,a,t){const r=o.useMemo(()=>i?Ue(i,a):{fieldLabel:"Form"},[i,a]);return V(r,{...t,disabled:!i||(t==null?void 0:t.disabled)})}function We(i,a,t){const n=(a==null?void 0:a.split(`
6
- `))??[],s=(t==null?void 0:t.cursorLine)!=null?n.slice(Math.max(0,t.cursorLine-8),t.cursorLine+3).join(`
4
+ `)}`:"Provide a helpful suggestion.";return r.push({role:"user",content:s}),r}function X(i={},a={}){i=i??{},a=a??{};const{debounceMs:r=500,disabled:t=!1}=a,n=Q(),[s,l]=c.useState(""),[o,f]=c.useState(!1),[h,y]=c.useState(null),[w,C]=c.useState(!1),S=c.useRef(null),P=c.useRef(0),k=c.useCallback(async()=>{var _,M,R;if(!n||!n.enabled||t)return;const{config:d,rateLimiter:j}=n;if(!j.recordRequest()){y("Rate limit exceeded. Please wait before requesting another hint.");return}const N=Oe(i,d.privacyMode??!1),m=se.get(N);if(m){l(m),f(!1),y(null),C(!1);return}(_=S.current)==null||_.abort();const v=new AbortController;S.current=v,f(!0),y(null),l(""),C(!1);const x=La(i,d),p=d.stream!==!1;try{const T={"Content-Type":"application/json",...d.headers};d.apiKey&&(T.Authorization=`Bearer ${d.apiKey}`);const u=JSON.stringify({model:d.model??"gpt-3.5-turbo",messages:x,temperature:d.temperature??.7,max_tokens:d.maxTokens??256,stream:p}),b=await fetch(d.endpoint,{method:"POST",headers:T,body:u,signal:v.signal});if(!b.ok){const I=await b.text().catch(()=>b.statusText);throw new Error(`AI request failed (${b.status}): ${I}`)}if(p){C(!0);let I="";for await(const D of Ge(b,v.signal))if(v.signal.aborted||(I+=D.token,l(I),(M=D.usage)!=null&&M.completion_tokens&&j.recordTokens(D.usage.completion_tokens),D.done))break;if(I.length>0){const D=Math.ceil(I.length/4);j.recordTokens(D)}se.set(N,I)}else{const I=await Ve(b);l(I.text),se.set(N,I.text),(R=I.usage)!=null&&R.completion_tokens?j.recordTokens(I.usage.completion_tokens):j.recordTokens(Math.ceil(I.text.length/4))}}catch(T){if(T instanceof DOMException&&T.name==="AbortError")return;y(T instanceof Error?T.message:"AI hint request failed")}finally{v.signal.aborted||(f(!1),C(!1))}},[n,i,t]);c.useEffect(()=>{if(!n||!n.enabled||t)return;const d=setTimeout(k,r);return()=>clearTimeout(d)},[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,P.current]),c.useEffect(()=>()=>{var d;(d=S.current)==null||d.abort()},[]);const $=c.useCallback(()=>{var d;(d=S.current)==null||d.abort(),f(!1),C(!1)},[]),g=c.useCallback(()=>{if(n){const d=Oe(i,n.config.privacyMode??!1);se.delete(d)}P.current+=1,k()},[n,i,k]);return!n||!n.enabled?{text:"",loading:!1,error:null,streaming:!1,abort:()=>{},refresh:()=>{},hint:null,fetchHint:async()=>{}}:{text:s,loading:o,error:h,streaming:w,abort:$,refresh:g,hint:s?{content:s}:null,fetchHint:async()=>{await k()}}}function Oa(){return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("path",{d:"M12 3l1.5 5.5L19 10l-5.5 1.5L12 17l-1.5-5.5L5 10l5.5-1.5z"}),e.jsx("path",{d:"M19 15l.5 2 2 .5-2 .5-.5 2-.5-2-2-.5 2-.5z"}),e.jsx("path",{d:"M5 19l.5 1.5 1.5.5-1.5.5-.5 1.5-.5-1.5-1.5-.5 1.5-.5z"})]})}function Ea(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,l=Math.max(r,t,n,s);return l===r?"top":l===t?"bottom":l===s?"right":"left"}function Da(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 Se=c.forwardRef(({context:i,position:a="auto",debounceMs:r=500,showOnHover:t=!1,triggerIcon:n,className:s,style:l},o)=>{var N;const f=Q(),[h,y]=c.useState(!1),[w,C]=c.useState(!1),S=c.useRef(null),P=c.useRef(null),k=X(i,{debounceMs:r,disabled:!w});c.useEffect(()=>{if(!h)return;const m=v=>{var p,_;const x=v.target;(p=S.current)!=null&&p.contains(x)||(_=P.current)!=null&&_.contains(x)||(y(!1),C(!1))};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[h]),c.useEffect(()=>{if(!h)return;const m=v=>{v.key==="Escape"&&(y(!1),C(!1),k.abort())};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[h,k]);const $=c.useCallback(m=>{if(m.stopPropagation(),t)return;const v=!h;y(v),C(v)},[h,t]),g=c.useCallback(()=>{t&&(y(!0),C(!0))},[t]),d=c.useCallback(()=>{t&&(y(!1),C(!1))},[t]);if(!f||!f.enabled)return null;const j=Ea(a,((N=S.current)==null?void 0:N.getBoundingClientRect())??null);return e.jsxs("span",{ref:o,className:s,style:{position:"relative",display:"inline-flex",...l},onMouseEnter:g,onMouseLeave:d,children:[e.jsx("button",{ref:S,type:"button",onClick:$,"aria-label":"AI hint","aria-expanded":h,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(Oa,{})}),h&&e.jsxs("div",{ref:P,role:"tooltip",className:"ntd-ai-popover",style:Da(j),children:[k.loading&&!k.text&&e.jsxs("div",{className:"ntd-ai-loading",style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{display:"inline-block",width:12,height:12,border:"2px solid var(--ntd-ai-border, #45475a)",borderTopColor:"var(--ntd-ai-trigger-color, #a78bfa)",borderRadius:"50%",animation:"ntd-ai-spin 0.8s linear infinite"}}),e.jsx("span",{style:{opacity:.6},children:"Thinking..."})]}),k.text&&e.jsxs("div",{className:"ntd-ai-content",children:[k.text,k.streaming&&e.jsx("span",{className:"ntd-ai-cursor",style:{display:"inline-block",width:2,height:"1em",backgroundColor:"var(--ntd-ai-trigger-color, #a78bfa)",marginLeft:1,animation:"ntd-ai-blink 0.8s step-end infinite",verticalAlign:"text-bottom"}})]}),k.error&&e.jsx("div",{className:"ntd-ai-error",style:{color:"var(--ntd-ai-error, #f38ba8)"},children:k.error}),k.text&&!k.streaming&&e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:4,marginTop:6,paddingTop:6,borderTop:"1px solid var(--ntd-ai-border, #45475a)"},children:[e.jsx("button",{type:"button",onClick:()=>k.refresh(),className:"ntd-ai-action",style:{fontSize:11,padding:"2px 6px",border:"1px solid var(--ntd-ai-border, #45475a)",borderRadius:4,background:"transparent",color:"inherit",cursor:"pointer"},children:"↻ Refresh"}),e.jsx("button",{type:"button",onClick:()=>{var m;(m=navigator.clipboard)==null||m.writeText(k.text)},className:"ntd-ai-action",style:{fontSize:11,padding:"2px 6px",border:"1px solid var(--ntd-ai-border, #45475a)",borderRadius:4,background:"transparent",color:"inherit",cursor:"pointer"},children:"⎘ Copy"})]})]})]})});Se.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 Me(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 Ha(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 Ba(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 Ke(i,a){return{fieldLabel:"Form auto-fill",fieldType:"form",schema:{fields:a},customPrompt:`User description: "${i}"
5
+ Parse this description and return suggested values for each field as JSON: { ${a.map(r=>`"${r.label}": "value"`).join(", ")} }`}}function Ye(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 Fa(i,a,r){const t=c.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 X(t,r)}function Ja(i,a,r){const t=c.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 X(t,r)}function Ua(i,a,r){const t=c.useMemo(()=>Re(i,a,r),[i,a,r==null?void 0:r.multiple]);return X(t,r)}function qa(i,a,r){const t=c.useMemo(()=>Me(i,a,r),[i,a,r==null?void 0:r.min,r==null?void 0:r.max,r==null?void 0:r.disableWeekends]);return X(t,r)}function Wa(i,a,r){const t=c.useMemo(()=>Pe(i,a,r),[i,a,r==null?void 0:r.industry]);return X(t,r)}function Ga(i,a,r,t,n){const s=c.useMemo(()=>t?Ye(i,a,r,t,n):{fieldLabel:i,fieldType:a},[i,a,r,t]);return X(s,{...n,disabled:!t||(n==null?void 0:n.disabled)})}function Va(i,a,r){const t=c.useMemo(()=>i?Ke(i,a):{fieldLabel:"Form"},[i,a]);return X(t,{...r,disabled:!i||(r==null?void 0:r.disabled)})}function Xe(i,a,r){const n=(a==null?void 0:a.split(`
6
+ `))??[],s=(r==null?void 0:r.cursorLine)!=null?n.slice(Math.max(0,r.cursorLine-8),r.cursorLine+3).join(`
7
7
  `):n.slice(0,8*2).join(`
8
- `);return{fieldLabel:`Code editor (${i})`,fieldType:"code-editor",fieldValue:s||a,schema:{language:i,...t!=null&&t.framework?{framework:t.framework}:{},...(t==null?void 0:t.cursorLine)!=null?{cursorLine:t.cursorLine,cursorCol:t.cursorCol}:{}},customPrompt:`Language: ${i}${t!=null&&t.framework?`, framework: ${t.framework}`:""}.
9
- Provide a concise inline completion or improvement hint for the code near the cursor. Limit response to ${(t==null?void 0:t.maxSuggestLines)??5} lines of code. If unsure, suggest the most idiomatic approach for this language/framework.`}}function Ge(i,a,t){var s;const r=(t==null?void 0:t.mode)??"grammar",n={seo:"Analyze this HTML for SEO: missing meta tags, heading hierarchy (h1→h2→h3), keyword density, image alt attributes. Return a prioritized list of improvements.",accessibility:"Audit this HTML for WCAG 2.1 AA issues: missing aria labels, alt text, heading structure, color contrast hints, keyboard navigation. List specific fixes.",grammar:"Fix grammar, punctuation, and writing style in the visible text content. Return the corrected text only (no HTML tags in response).",cleanup:"Clean up malformed, redundant, or overly nested HTML. Simplify structure while preserving semantics and content."};return{fieldLabel:i,fieldType:"html-editor",fieldValue:a==null?void 0:a.slice(0,2e3),schema:{mode:r,...(s=t==null?void 0:t.targetKeywords)!=null&&s.length?{targetKeywords:t.targetKeywords}:{},...t!=null&&t.locale?{locale:t.locale}:{}},customPrompt:n[r]}}function Ve(i,a){const t=(a==null?void 0:a.mode)??"tag",r=`"${i}"`+((a==null?void 0:a.bpm)!=null?`, BPM: ${a.bpm}`:"")+(a!=null&&a.key?`, Key: ${a.key}`:"")+(a!=null&&a.genre?`, Genre: ${a.genre}`:"")+((a==null?void 0:a.duration)!=null?`, Duration: ${a.duration}s`:""),n={tag:`Audio: ${r}. Suggest genre tags, mood descriptors and playlist categories. Return as JSON array of strings.`,bpm:`Audio: ${r}. Suggest likely BPM range and musical key based on metadata. Return as JSON: { bpm: number, key: string }.`,mix:`Track: ${r}. Suggest EQ curve (JSON array of {freq, gain, q}), compression settings, and 2-3 compatible tracks for mixing.`,transcribe:"Return a transcription of the spoken audio content as JSON: { transcript: string, language: string, confidence: number }."};return{fieldLabel:`Audio: ${i}`,fieldType:"audio",schema:{mode:t,...(a==null?void 0:a.bpm)!=null?{bpm:a.bpm}:{},...a!=null&&a.key?{key:a.key}:{},...(a==null?void 0:a.duration)!=null?{duration:a.duration}:{},...a!=null&&a.genre?{genre:a.genre}:{}},customPrompt:n[t]}}function Ke(i,a){var s;const t=(a==null?void 0:a.mode)??"material",r=(a==null?void 0:a.targetDevice)??"web",n={material:`Scene "${i}", ${(a==null?void 0:a.meshCount)??"?"} meshes. Materials: ${((s=a==null?void 0:a.materials)==null?void 0:s.join(", "))||"none"}. Suggest PBR properties (roughness, metalness, baseColor) and texture maps for each material.`,optimize:`Scene "${i}", triangles: ${(a==null?void 0:a.triangleCount)??"?"}, target: ${r}. Identify budget issues and suggest LOD levels, mesh merging, and texture atlas strategy.`,lighting:`Scene "${i}", target: ${r}. Suggest a complete lighting setup (types, intensity, color, shadow settings) for realistic rendering.`,animation:`Rig in scene "${i}". Suggest animation approach (FK/IK, bone count), keyframe timing and easing curves for natural movement.`};return{fieldLabel:`3D scene: ${i}`,fieldType:"3d-scene",schema:{mode:t,...(a==null?void 0:a.meshCount)!=null?{meshes:a.meshCount}:{},...(a==null?void 0:a.triangleCount)!=null?{triangles:a.triangleCount}:{},...a!=null&&a.targetDevice?{target:a.targetDevice}:{}},customPrompt:n[t]}}function Ye(i,a){const t=(a==null?void 0:a.mode)??"palette",r=(a==null?void 0:a.width)!=null?`${a.width}×${a.height??"?"}px`:"unknown dimensions",n={filter:`Image "${i}" (${r}). Suggest CSS/SVG filter parameters (brightness, contrast, saturate, hue-rotate, blur) as JSON: { brightness, contrast, saturate, hueRotate, blur }.`,palette:`Image "${i}". Extract or suggest a harmonious 5-color palette as JSON: { primary, secondary, accent, background, text }.`,upscale:`Image "${i}" at ${r}. Recommend upscaling strategy: model (ESRGAN/RealSR/SRCNN), scale factor, and expected quality gain.`,"style-transfer":`Image "${i}", target style: "${(a==null?void 0:a.targetStyle)??"artistic"}". Suggest style-transfer settings as JSON: { contentWeight, styleWeight, iterations, patchSize }.`};return{fieldLabel:`Graphics: ${i}`,fieldType:"graphics",schema:{mode:t,...(a==null?void 0:a.width)!=null?{width:a.width,height:a.height}:{},...a!=null&&a.targetStyle?{targetStyle:a.targetStyle}:{}},customPrompt:n[t]}}function Xe(i,a){var t;return{fieldLabel:"Icon search",fieldType:"icon-picker",fieldValue:i,schema:{...a!=null&&a.style?{iconStyle:a.style}:{},...(a==null?void 0:a.limit)!=null?{maxResults:a.limit}:{},...(t=a==null?void 0:a.availableIcons)!=null&&t.length?{sampleIcons:a.availableIcons.slice(0,30)}:{}},customPrompt:`User query: "${i}"
10
- Return the ${(a==null?void 0:a.limit)??5} most semantically relevant icon names from the available set as a JSON array of strings, ordered by relevance. Prefer specific over generic names.`}}function Oa(i,a,t){const r=o.useMemo(()=>We(i,a,t),[i,a,t==null?void 0:t.cursorLine,t==null?void 0:t.cursorCol,t==null?void 0:t.framework]);return V(r,t)}function Ea(i,a,t){const r=o.useMemo(()=>Ge(i,a,t),[i,a,t==null?void 0:t.mode,t==null?void 0:t.locale]);return V(r,t)}function Da(i,a){const t=o.useMemo(()=>Ve(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 V(t,a)}function Ba(i,a){const t=o.useMemo(()=>Ke(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 V(t,a)}function Fa(i,a){const t=o.useMemo(()=>Ye(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 V(t,a)}function Ja(i,a){const t=o.useMemo(()=>Xe(i,a),[i,a==null?void 0:a.limit,a==null?void 0:a.style]);return V(t,{...a,disabled:!i||(a==null?void 0:a.disabled)})}function Qe(i,a){var s;const t=(a==null?void 0:a.mode)??"npc-decision",r=(a==null?void 0:a.genre)??"fantasy",n={"npc-decision":`You are an AI game director. The NPC "${i}" must make a decision. Available BT nodes: ${JSON.stringify((a==null?void 0:a.btStatus)??[])}. Game state: ${JSON.stringify((a==null?void 0:a.gameState)??{})}. Return the name of the BT node to activate next, and one sentence of reasoning.`,dialogue:`You are a ${r} RPG writer. Write a short in-character dialogue line for NPC "${i}". Game state: ${JSON.stringify((a==null?void 0:a.gameState)??{})}. Max 2 sentences, no narrative descriptions.`,"procedural-level":`You are a ${r} game designer. Suggest a procedural level layout for a zone containing "${i}". Describe room count, enemy placement, loot, and one unique mechanic. Keep it under 150 words.`,"quest-description":`You are a ${r} quest designer. Write a compelling quest description involving "${i}". Include: objective, giver NPC, rewards, and a short flavour paragraph. Keep it under 120 words.`,"item-description":`You are a ${r} lore writer. Write a short item description for an item related to "${i}". Include: item name, rarity, flavour text, and one special property. Keep it under 80 words.`};return{fieldLabel:i,fieldType:`game-engine:${t}`,fieldValue:a==null?void 0:a.gameState,customPrompt:n[t],schema:{genre:r,mode:t,btNodes:(s=a==null?void 0:a.btStatus)==null?void 0:s.map(m=>m.node)}}}function qa(i,a){const t=o.useMemo(()=>Qe(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 V(t,a)}function Ze(i,a,t){const r=(t==null?void 0:t.mode)??"layout",n=(t==null?void 0:t.diagramType)??"flowchart",s={layout:`You are a diagram layout optimizer. Given this ${n} with ${i.length} nodes and ${a.length} edges, suggest optimal positions for each node to minimize edge crossings and improve readability. Return JSON: { suggestions: [{ id: string, x: number, y: number, reason: string }] }. Consider flow direction (top-to-bottom or left-to-right) and grouping related nodes.`,structure:`You are a diagram analyst. Analyze this ${n} structure. Identify: 1) Missing connections, 2) Potential bottlenecks, 3) Orphan nodes, 4) Cycles or loops. Return JSON: { issues: [{ type: string, description: string, nodeIds: string[] }], score: number }`,simplify:`You are a diagram simplifier. Suggest how to simplify this ${n} while preserving meaning. Identify: nodes that could be merged, redundant edges, or overly complex branches. Return JSON: { simplifications: [{ action: 'merge'|'remove'|'group', ids: string[], reason: string }] }`,group:`You are a diagram organizer. Suggest logical groupings for nodes in this ${n}. Consider semantic relationships, data flow patterns, and visual clustering. Return JSON: { groups: [{ name: string, nodeIds: string[], color?: string }] }`},m=i.map(g=>{var f;return{id:g.id,type:g.type,label:(f=g.label)==null?void 0:f.slice(0,30),pos:[Math.round(g.x),Math.round(g.y)]}}),c=a.map(g=>({id:g.id,src:g.source,tgt:g.target}));return{fieldLabel:`Diagram (${n})`,fieldType:`diagram:${r}`,fieldValue:JSON.stringify({nodes:m,edges:c}),schema:{diagramType:n,mode:r,nodeCount:i.length,edgeCount:a.length,containerSize:t==null?void 0:t.containerSize},customPrompt:s[r]}}function Ua(i,a,t){const r=o.useMemo(()=>Ze(i,a,t),[JSON.stringify(i),JSON.stringify(a),t==null?void 0:t.mode,t==null?void 0:t.diagramType]);return V(r,{...t,disabled:i.length===0||(t==null?void 0:t.disabled)})}function ea(i,a){const t=(a==null?void 0:a.mode)??"generate",r=(a==null?void 0:a.presentationType)??"business",n=(a==null?void 0:a.duration)??15,s=Math.ceil(n/2),m={generate:`You are a presentation designer. Create a ${r} presentation outline based on: "${i}". Target audience: ${(a==null?void 0:a.audience)??"general"}. Duration: ${n} minutes (~${s} slides). Return JSON: { title: string, slides: [{ title: string, layout: 'title'|'content'|'two-column'|'chart'|'image', bullets?: string[], chartType?: string, speakerNotes?: string }] }. Include: clear slide titles, 3-5 bullet points per content slide, and brief speaker notes.`,summarize:`You are a presentation optimizer. Summarize this presentation to be more concise: "${i}". Reduce slide count by 30% while preserving key messages. Return JSON: { summary: string, reducedSlides: [{ title: string, keyPoints: string[] }] }`,expand:`You are a presentation expert. Expand this brief outline into a detailed presentation: "${i}". Add supporting details, examples, and transitions. Target: ${s} slides. Return JSON: { slides: [{ title: string, content: string, transitions?: string, animations?: string[] }] }`,improve:`You are a presentation coach. Review and improve this presentation structure: "${i}". Suggest: better flow, stronger opening/closing, clearer data visualization. Return JSON: { improvements: [{ slide: number, issue: string, suggestion: string }], score: number }`};return{fieldLabel:`Presentation (${r})`,fieldType:`presentation:${t}`,fieldValue:i,schema:{presentationType:r,mode:t,duration:n,slideCount:s,audience:a==null?void 0:a.audience,hasData:(a==null?void 0:a.dataContext)!=null},customPrompt:m[t]}}function Ha(i,a){const t=o.useMemo(()=>ea(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 V(t,{...a,disabled:!i||(a==null?void 0:a.disabled)})}function aa(i,a){var n;const t=(a==null?void 0:a.mode)??"all",r={alignment:"Analyze element alignment on this slide. Suggest adjustments to create visual harmony. Return JSON: { suggestions: [{ elementIndex: number, issue: string, fixX?: number, fixY?: number }] }",contrast:"Analyze color contrast and readability. Suggest improvements for accessibility (WCAG AA). Return JSON: { suggestions: [{ area: string, currentContrast: number, suggestedFix: string }] }",spacing:"Analyze whitespace and element spacing. Apply the rule of thirds and consistent margins. Return JSON: { suggestions: [{ elementIndex: number, issue: string, suggestedMargin: number }] }",typography:"Analyze typography: hierarchy, font sizes, line heights, readability. Return JSON: { suggestions: [{ area: string, issue: string, suggestedFontSize?: number }] }",all:"Perform a complete design review of this slide. Check alignment, contrast, spacing, and typography. Return JSON: { score: number, suggestions: [{ category: string, issue: string, fix: string }] }. Prioritize issues by impact on visual clarity."};return{fieldLabel:i.title??"Slide Design",fieldType:`slide-design:${t}`,fieldValue:JSON.stringify(i),schema:{mode:t,hasElements:(((n=i.elements)==null?void 0:n.length)??0)>0,layout:i.layout,brandColors:a==null?void 0:a.brandColors},customPrompt:r[t]}}function Wa(i,a){const t=o.useMemo(()=>aa(i,a),[JSON.stringify(i),a==null?void 0:a.mode,JSON.stringify(a==null?void 0:a.brandColors)]);return V(t,a)}function Ga(i,a,t){const r=o.forwardRef((n,s)=>{const{aiEnabled:m=!0,aiPosition:c="right",aiPrompt:g,aiDebounceMs:f=500,aiShowOnHover:j=!1,aiTriggerIcon:w,...N}=n,S=o.useMemo(()=>{const $=a(N);return g&&($.customPrompt=g),$},[N,g]);return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(i,{...N,ref:s}),m&&e.jsx(ke,{context:S,position:c,debounceMs:f,showOnHover:j,triggerIcon:w})]})});return r.displayName=t??`withAIHint(${i.displayName??i.name??"Component"})`,r}function Va(i){return Ne(i.label??"Text",i.value,{placeholder:i.placeholder,maxLength:i.maxLength})}function Ka(i){return Ce(i.label??"Number",i.value,{min:i.min,max:i.max,step:i.step})}function Ya(i){return Se(i.label??"Select",i.value,{options:i.options,multiple:i.multiple})}function Xa(i){return Te(i.label??"Date",i.value,{min:i.min,max:i.max})}function Qa(i){return Ae(i.label??"Color",i.value)}const Za={id:crypto.randomUUID(),name:"New ML Project",type:"classification",status:"draft",datasets:[],experiments:[],models:[],createdAt:new Date,updatedAt:new Date},Ie={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"}]},ze={classification:["accuracy","precision","recall","f1-score","auc-roc"],regression:["mse","rmse","mae","r2"],clustering:["silhouette","calinski-harabasz","davies-bouldin"]},et=({project:i,onProjectChange:a,onExperimentRun:t,onModelDeploy:r,className:n=""})=>{var R;const[s,m]=o.useState(i||Za),[c,g]=o.useState("data"),[f,j]=o.useState(null),[w,N]=o.useState(null),[S,$]=o.useState(null),[k,P]=o.useState(!1),[h,d]=o.useState({algorithm:"",hyperparameters:{},preprocessing:[]}),v=o.useCallback(l=>{const x={...s,...l,updatedAt:new Date};m(x),a==null||a(x)},[s,a]),C=async l=>{for(const x of Array.from(l)){const M={id:crypto.randomUUID(),name:x.name.replace(/\.[^.]+$/,""),type:"tabular",source:{type:"file",uri:x.name},size:x.size,rowCount:0,columns:[],splits:[{name:"train",ratio:.8,rowCount:0},{name:"validation",ratio:.1,rowCount:0},{name:"test",ratio:.1,rowCount:0}],createdAt:new Date};if(x.name.endsWith(".csv")){const D=(await x.text()).split(`
11
- `),J=D[0].split(",").map(H=>H.trim());M.rowCount=D.length-1,M.columns=J.map(H=>({name:H,type:"text",nullable:!0,unique:0,missing:0})),M.splits=M.splits.map(H=>({...H,rowCount:Math.floor(M.rowCount*H.ratio)}))}v({datasets:[...s.datasets,M]})}},p=l=>{v({datasets:s.datasets.filter(x=>x.id!==l)}),f===l&&j(null)},_=async()=>{if(!h.algorithm||!f)return;const l={id:crypto.randomUUID(),name:`Experiment ${s.experiments.length+1}`,status:"pending",config:h,metrics:[],artifacts:[],logs:[]};if(v({experiments:[...s.experiments,l]}),P(!1),t){v({experiments:s.experiments.map(x=>x.id===l.id?{...x,status:"running",startedAt:new Date}:x)});try{await t(l);const x=(ze[s.type]||ze.classification).map(M=>({name:M,value:Math.random()*.3+.7,split:"validation"}));v({experiments:s.experiments.map(M=>M.id===l.id?{...M,status:"completed",completedAt:new Date,metrics:x}:M)})}catch{v({experiments:s.experiments.map(x=>x.id===l.id?{...x,status:"failed"}:x)})}}},b=l=>{const x=s.experiments.find(z=>z.id===l);if(!x)return;const M={id:crypto.randomUUID(),name:`Model from ${x.name}`,version:"1.0.0",algorithm:x.config.algorithm,experimentId:l,status:"registered",metrics:x.metrics,size:Math.floor(Math.random()*100)*1024*1024,artifacts:[],deployments:[],createdAt:new Date};v({models:[...s.models,M]})},u=async l=>{const x=s.models.find(z=>z.id===l);if(!x||!r)return;const M=await r(x);v({models:s.models.map(z=>z.id===l?{...z,status:"production",deployments:[...z.deployments,M]}:z)})},y=l=>l<1024?`${l} B`:l<1024*1024?`${(l/1024).toFixed(1)} KB`:l<1024*1024*1024?`${(l/1024/1024).toFixed(1)} MB`:`${(l/1024/1024/1024).toFixed(1)} GB`,A=l=>{switch(l){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""}};return e.jsxs("div",{className:`nice-ml-studio ${n}`,children:[e.jsxs("header",{className:"ml-studio__header",children:[e.jsxs("div",{className:"header__info",children:[e.jsx("input",{type:"text",value:s.name,onChange:l=>v({name:l.target.value}),className:"project-name-input"}),e.jsxs("select",{value:s.type,onChange:l=>v({type:l.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"})]})]}),e.jsx("div",{className:"header__tabs",children:["data","experiments","models","deploy"].map(l=>e.jsx("button",{className:`tab-button ${c===l?"tab-button--active":""}`,onClick:()=>g(l),children:l.charAt(0).toUpperCase()+l.slice(1)},l))})]}),e.jsxs("div",{className:"ml-studio__content",children:[c==="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:l=>l.target.files&&C(l.target.files),hidden:!0}),"+ Upload Dataset"]})]}),e.jsx("div",{className:"datasets-grid",children:s.datasets.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:"📊"}),e.jsx("p",{children:"No datasets uploaded yet"}),e.jsx("p",{className:"hint",children:"Upload CSV, JSON, or Parquet files to get started"})]}):s.datasets.map(l=>e.jsxs("div",{className:`dataset-card ${f===l.id?"dataset-card--selected":""}`,onClick:()=>j(l.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("span",{className:"dataset-icon",children:"📁"}),e.jsx("h3",{children:l.name}),e.jsx("button",{className:"remove-button",onClick:x=>{x.stopPropagation(),p(l.id)},children:"×"})]}),e.jsxs("div",{className:"card-stats",children:[e.jsxs("span",{children:[l.rowCount.toLocaleString()," rows"]}),e.jsxs("span",{children:[l.columns.length," columns"]}),e.jsx("span",{children:y(l.size)})]}),e.jsx("div",{className:"splits-bar",children:l.splits.map(x=>e.jsx("div",{className:`split split--${x.name}`,style:{width:`${x.ratio*100}%`},title:`${x.name}: ${(x.ratio*100).toFixed(0)}%`},x.name))})]},l.id))}),f&&e.jsx("div",{className:"dataset-details",children:(()=>{const l=s.datasets.find(x=>x.id===f);return l?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:l.columns.map(x=>e.jsxs("tr",{children:[e.jsx("td",{children:x.name}),e.jsx("td",{children:e.jsxs("select",{value:x.type,onChange:M=>{v({datasets:s.datasets.map(z=>z.id===l.id?{...z,columns:z.columns.map(D=>D.name===x.name?{...D,type:M.target.value}:D)}:z)})},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:x.missing}),e.jsx("td",{children:x.unique})]},x.name))})]})]}):null})()})]}),c==="experiments"&&e.jsxs("div",{className:"experiments-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:"Experiments"}),e.jsx("button",{className:"primary-button",onClick:()=>P(!0),disabled:s.datasets.length===0,children:"+ New Experiment"})]}),k&&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:f||"",onChange:l=>j(l.target.value),children:[e.jsx("option",{value:"",children:"Select dataset..."}),s.datasets.map(l=>e.jsx("option",{value:l.id,children:l.name},l.id))]})]}),e.jsxs("label",{children:["Algorithm",e.jsxs("select",{value:h.algorithm,onChange:l=>d({...h,algorithm:l.target.value}),children:[e.jsx("option",{value:"",children:"Select algorithm..."}),(Ie[s.type]||Ie.classification).map(l=>e.jsx("option",{value:l.id,children:l.name},l.id))]})]}),f&&e.jsxs("label",{children:["Target Column",e.jsxs("select",{value:h.targetColumn||"",onChange:l=>d({...h,targetColumn:l.target.value}),children:[e.jsx("option",{value:"",children:"Select target..."}),(R=s.datasets.find(l=>l.id===f))==null?void 0:R.columns.map(l=>e.jsx("option",{value:l.name,children:l.name},l.name))]})]})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{className:"secondary-button",onClick:()=>P(!1),children:"Cancel"}),e.jsx("button",{className:"primary-button",onClick:_,disabled:!h.algorithm||!f,children:"Run Experiment"})]})]}),e.jsx("div",{className:"experiments-list",children:s.experiments.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:"🧪"}),e.jsx("p",{children:"No experiments yet"}),e.jsx("p",{className:"hint",children:"Create an experiment to train and evaluate models"})]}):s.experiments.map(l=>e.jsxs("div",{className:`experiment-card ${w===l.id?"experiment-card--selected":""}`,onClick:()=>N(l.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:l.name}),e.jsx("span",{className:`status-badge ${A(l.status)}`,children:l.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Algorithm: ",l.config.algorithm]}),l.duration&&e.jsxs("span",{children:["Duration: ",Math.round(l.duration),"s"]})]}),l.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:l.metrics.slice(0,3).map(x=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:x.name}),e.jsxs("span",{className:"metric-value",children:[(x.value*100).toFixed(1),"%"]})]},x.name))}),l.status==="completed"&&e.jsx("button",{className:"action-button",onClick:x=>{x.stopPropagation(),b(l.id)},children:"Register Model"})]},l.id))})]}),c==="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:s.models.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:"🤖"}),e.jsx("p",{children:"No models registered yet"}),e.jsx("p",{className:"hint",children:"Complete experiments and register models"})]}):s.models.map(l=>e.jsxs("div",{className:`model-card ${S===l.id?"model-card--selected":""}`,onClick:()=>$(l.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:l.name}),e.jsx("span",{className:`status-badge ${A(l.status)}`,children:l.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Algorithm: ",l.algorithm]}),e.jsxs("span",{children:["Version: ",l.version]}),e.jsxs("span",{children:["Size: ",y(l.size)]})]}),l.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:l.metrics.slice(0,3).map(x=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:x.name}),e.jsxs("span",{className:"metric-value",children:[(x.value*100).toFixed(1),"%"]})]},x.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:x=>{x.stopPropagation(),u(l.id)},disabled:l.status==="production",children:l.status==="production"?"Deployed":"Deploy"})]})]},l.id))})]}),c==="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:s.models.filter(l=>l.deployments.length>0).length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:"🚀"}),e.jsx("p",{children:"No deployments yet"}),e.jsx("p",{className:"hint",children:"Deploy a model to create inference endpoints"})]}):s.models.filter(l=>l.deployments.length>0).flatMap(l=>l.deployments.map(x=>({model:l,deployment:x}))).map(({model:l,deployment:x})=>e.jsxs("div",{className:"deployment-card",children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:x.name}),e.jsx("span",{className:`status-badge ${A(x.status)}`,children:x.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Model: ",l.name]}),e.jsxs("span",{children:["Endpoint: ",x.endpoint]})]}),e.jsxs("div",{className:"resources-info",children:[e.jsxs("span",{children:["CPU: ",x.resources.cpu," cores"]}),e.jsxs("span",{children:["Memory: ",x.resources.memory," GB"]}),e.jsxs("span",{children:["Replicas: ",x.resources.replicas]})]})]},x.id))})]})]})]})},at={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},Le=["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)"],tt=({project:i,onProjectChange:a,onLabelSave:t,onExport:r,className:n=""})=>{var Q;const[s,m]=o.useState(i||at),[c,g]=o.useState("label"),[f,j]=o.useState(0),[w,N]=o.useState(null),[S,$]=o.useState("select"),[k,P]=o.useState(!1),[h,d]=o.useState(null),[v,C]=o.useState(1),[p,_]=o.useState(!1),[b,u]=o.useState("all"),y=o.useRef(null),A=o.useRef(null),R=s.items[f];o.useEffect(()=>{i&&m(i)},[i]);const l=o.useCallback(T=>{const L={...s,...T};L.statistics={totalItems:L.items.length,labeled:L.items.filter(E=>E.status!=="pending").length,reviewed:L.items.filter(E=>E.status==="review"||E.status==="approved").length,approved:L.items.filter(E=>E.status==="approved").length,byClass:L.labelSchema.classes.map(E=>({classId:E.id,count:L.items.flatMap(O=>O.labels).filter(O=>O.classId===E.id).length}))},m(L),a==null||a(L)},[s,a]),x=()=>{const T={id:crypto.randomUUID(),name:`Class ${s.labelSchema.classes.length+1}`,color:Le[s.labelSchema.classes.length%Le.length],shortcut:String(s.labelSchema.classes.length+1)};l({labelSchema:{...s.labelSchema,classes:[...s.labelSchema.classes,T]}})},M=T=>{l({labelSchema:{...s.labelSchema,classes:s.labelSchema.classes.filter(L=>L.id!==T)},items:s.items.map(L=>({...L,labels:L.labels.filter(E=>E.classId!==T)}))})},z=(T,L)=>{l({labelSchema:{...s.labelSchema,classes:s.labelSchema.classes.map(E=>E.id===T?{...E,...L}:E)}})},D=(T,L)=>{if(!R)return;const E={id:crypto.randomUUID(),classId:T,type:s.type==="classification"?"class":s.type==="bounding-box"?"bbox":"class",data:L||{},createdBy:"current-user",createdAt:new Date},O={...R,labels:[...R.labels,E],status:"labeled"};l({items:s.items.map(B=>B.id===R.id?O:B)}),t==null||t(O)},J=T=>{if(!R)return;const L={...R,labels:R.labels.filter(E=>E.id!==T),status:R.labels.length<=1?"pending":"labeled"};l({items:s.items.map(E=>E.id===R.id?L:E)})},H=T=>{var B;if(S!=="bbox"||!w)return;const L=(B=y.current)==null?void 0:B.getBoundingClientRect();if(!L)return;const E=(T.clientX-L.left)/v,O=(T.clientY-L.top)/v;P(!0),d({x:E,y:O,width:0,height:0})},Y=T=>{var B;if(!k||!h)return;const L=(B=y.current)==null?void 0:B.getBoundingClientRect();if(!L)return;const E=(T.clientX-L.left)/v,O=(T.clientY-L.top)/v;d({...h,width:E-h.x,height:O-h.y})},I=()=>{!k||!h||!w||(P(!1),Math.abs(h.width)>10&&Math.abs(h.height)>10&&D(w,{x:h.width<0?h.x+h.width:h.x,y:h.height<0?h.y+h.height:h.y,width:Math.abs(h.width),height:Math.abs(h.height)}),d(null))},F=T=>{const L=b==="all"?s.items:s.items.filter(O=>O.status===b),E=L.findIndex(O=>O.id===(R==null?void 0:R.id));if(T==="prev"&&E>0){const O=L[E-1];j(s.items.findIndex(B=>B.id===O.id))}else if(T==="next"&&E<L.length-1){const O=L[E+1];j(s.items.findIndex(B=>B.id===O.id))}},q=()=>{if(!R)return;const T={...R,status:"approved"};l({items:s.items.map(L=>L.id===R.id?T:L)}),F("next")},W=()=>{if(!R)return;const T={...R,status:"rejected"};l({items:s.items.map(L=>L.id===R.id?T:L)}),F("next")},U=async T=>{r&&await r(T)};o.useEffect(()=>{const T=L=>{const E=L.key,O=s.labelSchema.classes.find(B=>B.shortcut===E);O&&(s.type==="classification"?(D(O.id),F("next")):N(O.id)),L.key==="ArrowLeft"||L.key==="a"?F("prev"):(L.key==="ArrowRight"||L.key==="d")&&F("next"),L.key==="Enter"?q():L.key==="Backspace"&&W()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[R,s.labelSchema.classes,s.type]);const K=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:s.name,onChange:T=>l({name:T.target.value}),className:"project-name-input"}),e.jsxs("div",{className:"progress-bar",children:[e.jsx("div",{className:"progress-fill",style:{width:`${s.statistics.labeled/Math.max(s.statistics.totalItems,1)*100}%`}}),e.jsxs("span",{className:"progress-text",children:[s.statistics.labeled," / ",s.statistics.totalItems," labeled"]})]})]}),e.jsx("div",{className:"header__tabs",children:["label","schema","review","export"].map(T=>e.jsx("button",{className:`tab-button ${c===T?"tab-button--active":""}`,onClick:()=>g(T),children:T.charAt(0).toUpperCase()+T.slice(1)},T))}),e.jsx("button",{className:"shortcuts-button",onClick:()=>_(!p),children:"⌨️ Shortcuts"})]}),e.jsxs("div",{className:"labeler__content",children:[c==="label"&&e.jsxs("div",{className:"label-panel",children:[e.jsxs("div",{className:"label-toolbar",children:[e.jsxs("div",{className:"tool-group",children:[e.jsx("button",{className:`tool-button ${S==="select"?"tool-button--active":""}`,onClick:()=>$("select"),children:"↖️ Select"}),(s.type==="bounding-box"||s.type==="multi-label")&&e.jsx("button",{className:`tool-button ${S==="bbox"?"tool-button--active":""}`,onClick:()=>$("bbox"),children:"⬜ Box"}),s.type==="polygon"&&e.jsx("button",{className:`tool-button ${S==="polygon"?"tool-button--active":""}`,onClick:()=>$("polygon"),children:"⬡ Polygon"})]}),e.jsxs("div",{className:"zoom-group",children:[e.jsx("button",{onClick:()=>C(Math.max(.25,v-.25)),children:"-"}),e.jsxs("span",{children:[Math.round(v*100),"%"]}),e.jsx("button",{onClick:()=>C(Math.min(4,v+.25)),children:"+"})]}),e.jsxs("div",{className:"navigation-group",children:[e.jsx("button",{onClick:()=>F("prev"),disabled:f===0,children:"← Prev"}),e.jsxs("span",{children:[f+1," / ",s.items.length]}),e.jsx("button",{onClick:()=>F("next"),disabled:f>=s.items.length-1,children:"Next →"})]})]}),e.jsxs("div",{className:"label-workspace",children:[e.jsx("div",{className:"canvas-container",ref:A,children:R?e.jsxs(e.Fragment,{children:[R.data.type==="image"&&e.jsxs(e.Fragment,{children:[e.jsx("img",{src:R.data.url,alt:"Labeling item",className:"labeling-image",style:{transform:`scale(${v})`}}),e.jsx("canvas",{ref:y,className:"labeling-canvas",onMouseDown:H,onMouseMove:Y,onMouseUp:I,onMouseLeave:I,style:{transform:`scale(${v})`,cursor:S==="bbox"?"crosshair":"default"}}),e.jsxs("div",{className:"annotations-overlay",style:{transform:`scale(${v})`},children:[R.labels.filter(T=>T.type==="bbox"&&T.data.x!==void 0).map(T=>{const L=s.labelSchema.classes.find(E=>E.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:(L==null?void 0:L.color)||"var(--nice-danger, #ff0000)"},children:[e.jsx("span",{className:"bbox-label",style:{backgroundColor:(L==null?void 0:L.color)||"var(--nice-danger, #ff0000)"},children:L==null?void 0:L.name}),e.jsx("button",{className:"bbox-remove",onClick:()=>J(T.id),children:"×"})]},T.id)}),h&&e.jsx("div",{className:"bbox-drawing",style:{left:h.width<0?h.x+h.width:h.x,top:h.height<0?h.y+h.height:h.y,width:Math.abs(h.width),height:Math.abs(h.height),borderColor:(Q=s.labelSchema.classes.find(T=>T.id===w))==null?void 0:Q.color}})]})]}),R.data.type==="text"&&e.jsx("div",{className:"text-labeling",children:e.jsx("p",{className:"text-content",children:R.data.text})})]}):e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:"📋"}),e.jsx("p",{children:"No items to label"})]})}),e.jsxs("aside",{className:"class-sidebar",children:[e.jsx("h3",{children:"Classes"}),e.jsx("div",{className:"class-list",children:s.labelSchema.classes.map(T=>e.jsxs("button",{className:`class-button ${w===T.id?"class-button--active":""}`,style:{borderLeftColor:T.color},onClick:()=>{s.type==="classification"?(D(T.id),F("next")):N(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))}),R&&R.labels.length>0&&e.jsxs("div",{className:"current-labels",children:[e.jsx("h4",{children:"Labels"}),R.labels.map(T=>{const L=s.labelSchema.classes.find(E=>E.id===T.classId);return e.jsxs("div",{className:"label-item",children:[e.jsx("span",{className:"label-color",style:{backgroundColor:L==null?void 0:L.color}}),e.jsx("span",{className:"label-name",children:L==null?void 0:L.name}),e.jsx("button",{onClick:()=>J(T.id),children:"×"})]},T.id)})]}),c==="label"&&R&&e.jsxs("div",{className:"label-actions",children:[e.jsx("button",{className:"approve-button",onClick:q,children:"✓ Approve"}),e.jsx("button",{className:"reject-button",onClick:W,children:"✗ Reject"})]})]})]})]}),c==="schema"&&e.jsxs("div",{className:"schema-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:"Label Schema"}),e.jsx("button",{className:"primary-button",onClick:x,children:"+ Add Class"})]}),e.jsxs("div",{className:"schema-settings",children:[e.jsxs("label",{children:["Labeling Type",e.jsxs("select",{value:s.type,onChange:T=>l({type:T.target.value}),children:[e.jsx("option",{value:"classification",children:"Single Classification"}),e.jsx("option",{value:"multi-label",children:"Multi-Label Classification"}),e.jsx("option",{value:"bounding-box",children:"Bounding Box"}),e.jsx("option",{value:"polygon",children:"Polygon"}),e.jsx("option",{value:"segmentation",children:"Segmentation"}),e.jsx("option",{value:"ner",children:"Named Entity Recognition"})]})]}),e.jsxs("label",{children:["Data Type",e.jsxs("select",{value:s.dataType,onChange:T=>l({dataType:T.target.value}),children:[e.jsx("option",{value:"image",children:"Image"}),e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"audio",children:"Audio"}),e.jsx("option",{value:"video",children:"Video"})]})]})]}),e.jsx("div",{className:"classes-list",children:s.labelSchema.classes.map((T,L)=>e.jsxs("div",{className:"class-editor",children:[e.jsx("input",{type:"color",value:T.color,onChange:E=>z(T.id,{color:E.target.value}),className:"color-picker"}),e.jsx("input",{type:"text",value:T.name,onChange:E=>z(T.id,{name:E.target.value}),className:"class-name-input",placeholder:"Class name"}),e.jsx("input",{type:"text",value:T.shortcut||"",onChange:E=>z(T.id,{shortcut:E.target.value}),className:"shortcut-input",placeholder:"Key",maxLength:1}),e.jsx("button",{className:"remove-class-button",onClick:()=>M(T.id),children:"🗑️"})]},T.id))}),e.jsxs("div",{className:"guidelines-section",children:[e.jsx("h3",{children:"Labeling Guidelines"}),e.jsx("textarea",{value:s.guidelines||"",onChange:T=>l({guidelines:T.target.value}),placeholder:"Enter labeling guidelines for annotators...",rows:6})]})]}),c==="review"&&e.jsxs("div",{className:"review-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:"Review Labels"}),e.jsx("div",{className:"filter-group",children:e.jsxs("select",{value:b,onChange:T=>u(T.target.value),children:[e.jsx("option",{value:"all",children:"All Items"}),e.jsx("option",{value:"labeled",children:"Labeled"}),e.jsx("option",{value:"review",children:"Needs Review"}),e.jsx("option",{value:"approved",children:"Approved"}),e.jsx("option",{value:"rejected",children:"Rejected"})]})})]}),e.jsx("div",{className:"items-grid",children:s.items.filter(T=>b==="all"||T.status===b).map((T,L)=>{var E;return e.jsxs("div",{className:`item-card ${f===s.items.indexOf(T)?"item-card--active":""}`,onClick:()=>{j(s.items.indexOf(T)),g("label")},children:[T.data.type==="image"&&e.jsx("img",{src:T.data.url,alt:`Item ${L+1}`,className:"item-thumbnail"}),T.data.type==="text"&&e.jsxs("p",{className:"item-text-preview",children:[(E=T.data.text)==null?void 0:E.slice(0,100),"..."]}),e.jsxs("div",{className:"item-footer",children:[e.jsx("span",{className:"status-dot",style:{backgroundColor:K(T.status)}}),e.jsxs("span",{children:[T.labels.length," labels"]})]})]},T.id)})})]}),c==="export"&&e.jsxs("div",{className:"export-panel",children:[e.jsx("div",{className:"panel-header",children:e.jsx("h2",{children:"Export Labels"})}),e.jsxs("div",{className:"export-stats",children:[e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:s.statistics.totalItems}),e.jsx("span",{className:"stat-label",children:"Total Items"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:s.statistics.labeled}),e.jsx("span",{className:"stat-label",children:"Labeled"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:s.statistics.approved}),e.jsx("span",{className:"stat-label",children:"Approved"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:s.labelSchema.classes.length}),e.jsx("span",{className:"stat-label",children:"Classes"})]})]}),e.jsxs("div",{className:"export-formats",children:[e.jsx("h3",{children:"Export Format"}),e.jsxs("div",{className:"format-grid",children:[e.jsxs("button",{className:"format-button",onClick:()=>U("coco"),children:[e.jsx("span",{className:"format-icon",children:"📦"}),e.jsx("span",{className:"format-name",children:"COCO JSON"}),e.jsx("span",{className:"format-desc",children:"Common format for object detection"})]}),e.jsxs("button",{className:"format-button",onClick:()=>U("voc"),children:[e.jsx("span",{className:"format-icon",children:"📄"}),e.jsx("span",{className:"format-name",children:"Pascal VOC"}),e.jsx("span",{className:"format-desc",children:"XML format for bounding boxes"})]}),e.jsxs("button",{className:"format-button",onClick:()=>U("yolo"),children:[e.jsx("span",{className:"format-icon",children:"⚡"}),e.jsx("span",{className:"format-name",children:"YOLO"}),e.jsx("span",{className:"format-desc",children:"Text format for YOLO models"})]}),e.jsxs("button",{className:"format-button",onClick:()=>U("csv"),children:[e.jsx("span",{className:"format-icon",children:"📊"}),e.jsx("span",{className:"format-name",children:"CSV"}),e.jsx("span",{className:"format-desc",children:"Tabular format for classification"})]})]})]}),e.jsxs("div",{className:"class-distribution",children:[e.jsx("h3",{children:"Class Distribution"}),e.jsx("div",{className:"distribution-bars",children:s.statistics.byClass.map(T=>{const L=s.labelSchema.classes.find(O=>O.id===T.classId),E=T.count/Math.max(s.statistics.labeled,1)*100;return e.jsxs("div",{className:"distribution-row",children:[e.jsx("span",{className:"class-name",style:{color:L==null?void 0:L.color},children:L==null?void 0:L.name}),e.jsx("div",{className:"bar-container",children:e.jsx("div",{className:"bar-fill",style:{width:`${E}%`,backgroundColor:L==null?void 0:L.color}})}),e.jsx("span",{className:"count",children:T.count})]},T.classId)})})]})]})]}),p&&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:"Keyboard Shortcuts"}),e.jsx("button",{onClick:()=>_(!1),children:"×"})]}),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:"Previous item"})]}),e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:"→ / D"}),e.jsx("span",{className:"description",children:"Next item"})]}),e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:"Enter"}),e.jsx("span",{className:"description",children:"Approve item"})]}),e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:"Backspace"}),e.jsx("span",{className:"description",children:"Reject item"})]}),s.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))]})]})})]})},it={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:[]},rt=({endpoint:i,onInference:a,showMetrics:t=!0,showLogs:r=!0,className:n=""})=>{const[s,m]=o.useState(i||it),[c,g]=o.useState("test"),[f,j]=o.useState("text"),[w,N]=o.useState(""),[S,$]=o.useState("{}"),[k,P]=o.useState(null),[h,d]=o.useState({temperature:.7,topK:50,topP:.9,maxTokens:256,threshold:.5}),[v,C]=o.useState(null),[p,_]=o.useState(!1),[b,u]=o.useState(null),[y,A]=o.useState([]),[R,l]=o.useState(null),x=o.useRef(null),M=I=>{var q;const F=(q=I.target.files)==null?void 0:q[0];if(F){const W=new FileReader;W.onload=U=>{var K;P((K=U.target)==null?void 0:K.result)},W.readAsDataURL(F)}},z=async()=>{if(!a){u("No inference handler provided");return}_(!0),u(null),C(null);const I=[];switch(f){case"text":I.push({type:"text",data:w});break;case"image":k&&I.push({type:"image",data:k});break;case"json":try{I.push({type:"json",data:JSON.parse(S)})}catch{u("Invalid JSON input"),_(!1);return}break;case"tabular":try{I.push({type:"tabular",data:JSON.parse(S)})}catch{u("Invalid tabular data"),_(!1);return}break}const F={inputs:I,parameters:h};try{const q=Date.now(),W=await a(F),U=Date.now()-q;C(W),m(K=>({...K,metrics:{...K.metrics,requestsTotal:K.metrics.requestsTotal+1,latencyP50:(K.metrics.latencyP50+U)/2},logs:[{timestamp:new Date,requestId:W.requestId,duration:U,status:"success",inputSize:JSON.stringify(I).length,outputSize:JSON.stringify(W.predictions).length},...K.logs.slice(0,99)]}))}catch(q){const W=q instanceof Error?q.message:"Inference failed";u(W),m(U=>({...U,metrics:{...U.metrics,requestsTotal:U.metrics.requestsTotal+1,errorRate:(U.metrics.errorRate*U.metrics.requestsTotal+1)/(U.metrics.requestsTotal+1)},logs:[{timestamp:new Date,requestId:crypto.randomUUID(),duration:0,status:"error",inputSize:JSON.stringify(I).length,outputSize:0,error:W},...U.logs.slice(0,99)]}))}finally{_(!1)}},D=async I=>{if(a){l(0),A([]);for(let F=0;F<I.length;F++){const q={inputs:[I[F]],parameters:h};try{const W=await a(q);A(U=>[...U,W])}catch(W){console.error("Batch item failed:",W)}l((F+1)/I.length*100)}l(null)}},J=I=>I<1e3?`${I.toFixed(0)}ms`:`${(I/1e3).toFixed(2)}s`,H=I=>I.toLocaleTimeString(),Y=(I,F)=>e.jsxs("div",{className:"prediction-item",children:[I.label&&e.jsxs("div",{className:"prediction-label",children:[e.jsx("span",{className:"label-name",children:I.label}),I.confidence!==void 0&&e.jsxs("span",{className:"confidence-badge",style:{backgroundColor:`hsl(${I.confidence*120}, 70%, 40%)`},children:[(I.confidence*100).toFixed(1),"%"]})]}),I.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:I.score.toFixed(4)})]}),I.text&&e.jsx("div",{className:"prediction-text",children:e.jsx("pre",{children:I.text})}),I.bbox&&e.jsx("div",{className:"prediction-bbox",children:e.jsxs("span",{children:["Box: (",I.bbox.x,", ",I.bbox.y,") - ",I.bbox.width,"×",I.bbox.height]})}),I.raw!==void 0&&I.raw!==null&&e.jsxs("details",{className:"raw-output",children:[e.jsx("summary",{children:"Raw Output"}),e.jsx("pre",{children:JSON.stringify(I.raw,null,2)})]})]},F);return e.jsxs("div",{className:`nice-model-inference ${n}`,children:[e.jsxs("header",{className:"inference__header",children:[e.jsxs("div",{className:"header__info",children:[e.jsx("h2",{children:s.name}),e.jsx("span",{className:`status-badge status-badge--${s.status}`,children:s.status})]}),e.jsxs("div",{className:"header__tabs",children:[e.jsx("button",{className:`tab-button ${c==="test"?"tab-button--active":""}`,onClick:()=>g("test"),children:"Test"}),e.jsx("button",{className:`tab-button ${c==="batch"?"tab-button--active":""}`,onClick:()=>g("batch"),children:"Batch"}),t&&e.jsx("button",{className:`tab-button ${c==="metrics"?"tab-button--active":""}`,onClick:()=>g("metrics"),children:"Metrics"}),r&&e.jsx("button",{className:`tab-button ${c==="logs"?"tab-button--active":""}`,onClick:()=>g("logs"),children:"Logs"})]})]}),e.jsxs("div",{className:"inference__content",children:[c==="test"&&e.jsxs("div",{className:"test-panel",children:[e.jsxs("div",{className:"input-section",children:[e.jsx("div",{className:"input-type-selector",children:["text","image","json","tabular"].map(I=>e.jsx("button",{className:`type-button ${f===I?"type-button--active":""}`,onClick:()=>j(I),children:I.charAt(0).toUpperCase()+I.slice(1)},I))}),e.jsxs("div",{className:"input-area",children:[f==="text"&&e.jsx("textarea",{value:w,onChange:I=>N(I.target.value),placeholder:"Enter text input...",rows:6,className:"text-input"}),f==="image"&&e.jsx("div",{className:"image-input",children:k?e.jsxs("div",{className:"image-preview",children:[e.jsx("img",{src:k,alt:"Input preview"}),e.jsx("button",{className:"clear-button",onClick:()=>P(null),children:"Clear"})]}):e.jsxs("label",{className:"upload-zone",children:[e.jsx("input",{ref:x,type:"file",accept:"image/*",onChange:M,hidden:!0}),e.jsx("span",{className:"upload-icon",children:"🖼️"}),e.jsx("span",{children:"Click or drag to upload image"})]})}),(f==="json"||f==="tabular")&&e.jsx("textarea",{value:S,onChange:I=>$(I.target.value),placeholder:f==="json"?`{
8
+ `);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}`:""}.
9
+ 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 Ze(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 Qe(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 ea(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 aa(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 ra(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}"
10
+ Return the ${(a==null?void 0:a.limit)??5} most semantically relevant icon names from the available set as a JSON array of strings, ordered by relevance. Prefer specific over generic names.`}}function Ka(i,a,r){const t=c.useMemo(()=>Xe(i,a,r),[i,a,r==null?void 0:r.cursorLine,r==null?void 0:r.cursorCol,r==null?void 0:r.framework]);return X(t,r)}function Ya(i,a,r){const t=c.useMemo(()=>Ze(i,a,r),[i,a,r==null?void 0:r.mode,r==null?void 0:r.locale]);return X(t,r)}function Xa(i,a){const r=c.useMemo(()=>Qe(i,a),[i,a==null?void 0:a.bpm,a==null?void 0:a.key,a==null?void 0:a.duration,a==null?void 0:a.mode]);return X(r,a)}function Za(i,a){const r=c.useMemo(()=>ea(i,a),[i,a==null?void 0:a.meshCount,a==null?void 0:a.triangleCount,a==null?void 0:a.targetDevice,a==null?void 0:a.mode]);return X(r,a)}function Qa(i,a){const r=c.useMemo(()=>aa(i,a),[i,a==null?void 0:a.width,a==null?void 0:a.height,a==null?void 0:a.mode,a==null?void 0:a.targetStyle]);return X(r,a)}function er(i,a){const r=c.useMemo(()=>ra(i,a),[i,a==null?void 0:a.limit,a==null?void 0:a.style]);return X(r,{...a,disabled:!i||(a==null?void 0:a.disabled)})}function ia(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(l=>l.node)}}}function ar(i,a){const r=c.useMemo(()=>ia(i,a),[i,a==null?void 0:a.mode,a==null?void 0:a.genre,JSON.stringify(a==null?void 0:a.btStatus),JSON.stringify(a==null?void 0:a.gameState)]);return X(r,a)}function ta(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 }] }`},l=i.map(f=>{var h;return{id:f.id,type:f.type,label:(h=f.label)==null?void 0:h.slice(0,30),pos:[Math.round(f.x),Math.round(f.y)]}}),o=a.map(f=>({id:f.id,src:f.source,tgt:f.target}));return{fieldLabel:`Diagram (${n})`,fieldType:`diagram:${t}`,fieldValue:JSON.stringify({nodes:l,edges:o}),schema:{diagramType:n,mode:t,nodeCount:i.length,edgeCount:a.length,containerSize:r==null?void 0:r.containerSize},customPrompt:s[t]}}function rr(i,a,r){const t=c.useMemo(()=>ta(i,a,r),[JSON.stringify(i),JSON.stringify(a),r==null?void 0:r.mode,r==null?void 0:r.diagramType]);return X(t,{...r,disabled:i.length===0||(r==null?void 0:r.disabled)})}function na(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),l={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:l[r]}}function ir(i,a){const r=c.useMemo(()=>na(i,a),[i,a==null?void 0:a.mode,a==null?void 0:a.presentationType,a==null?void 0:a.duration,a==null?void 0:a.audience]);return X(r,{...a,disabled:!i||(a==null?void 0:a.disabled)})}function sa(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 tr(i,a){const r=c.useMemo(()=>sa(i,a),[JSON.stringify(i),a==null?void 0:a.mode,JSON.stringify(a==null?void 0:a.brandColors)]);return X(r,a)}function nr(i,a,r){const t=c.forwardRef((n,s)=>{const{aiEnabled:l=!0,aiPosition:o="right",aiPrompt:f,aiDebounceMs:h=500,aiShowOnHover:y=!1,aiTriggerIcon:w,...C}=n,S=c.useMemo(()=>{const P=a(C);return f&&(P.customPrompt=f),P},[C,f]);return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(i,{...C,ref:s}),l&&e.jsx(Se,{context:S,position:o,debounceMs:h,showOnHover:y,triggerIcon:w})]})});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 cr(i){return Ae(i.label??"Number",i.value,{min:i.min,max:i.max,step:i.step})}function or(i){return Re(i.label??"Select",i.value,{options:i.options,multiple:i.multiple})}function lr(i){return Me(i.label??"Date",i.value,{min:i.min,max:i.max})}function dr(i){return Pe(i.label??"Color",i.value)}const ur=(i,a)=>a,pr=c.createContext(ur);function mr(){return{t:c.useContext(pr)}}c.createContext({dir:"ltr",isRTL:!1,flip:i=>i,value:i=>i.ltr});c.createContext(null);c.createContext(null);const fr={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"};c.createContext({displayStyle:"default",variantConfig:fr,setDisplayStyle:()=>{}});c.createContext({});c.createContext({direction:"ltr",isRTL:!1,flip:i=>i,flipStyle:(i,a)=>({[i]:a})});c.createContext({permissions:{},getAccessMode:()=>"full"});c.createContext(null);const hr=process.env.NODE_ENV==="development";let ca={enabled:hr,slowRenderThreshold:16};const oa=[],$e=new Map,la=new Map;function gr(){oa.length=0,$e.clear(),la.clear()}function yr(i){const a=ca.slowRenderThreshold;return oa.filter(r=>r.actualDuration>a)}function ie(i){return i<1?`${(i*1e3).toFixed(0)}μs`:i<1e3?`${i.toFixed(2)}ms`:`${(i/1e3).toFixed(2)}s`}function br(){const i=Array.from($e.values()),a=yr(),r=i.reduce((s,l)=>s+l.renderCount,0),t=i.length>0?i.reduce((s,l)=>s+l.avgRenderTime,0)/i.length:0,n=Array.from(la.values());return{stats:i,slowRenders:a,totalRenders:r,avgRenderTime:t,marks:n}}function xr(){const i=br();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: ${ie(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":ie(a.avgRenderTime),"Max Time":ie(a.maxRenderTime),"Total Time":ie(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:ie(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:ie(a.duration)}))),console.groupEnd()),console.groupEnd()}const vr=c.memo(({position:i="bottom-right",defaultCollapsed:a=!0})=>{const[r,t]=c.useState(a),[n,s]=c.useState([]),[l,o]=c.useState({used:0,total:0});if(c.useEffect(()=>{const h=()=>{const w=Array.from($e.values());s(w.sort((S,P)=>P.totalRenderTime-S.totalRenderTime).slice(0,10));const C=window.performance;C.memory&&o({used:C.memory.usedJSHeapSize/1024/1024,total:C.memory.totalJSHeapSize/1024/1024})};h();const y=setInterval(h,2e3);return()=>clearInterval(y)},[]),!ca.enabled)return null;const f={position:"fixed",zIndex:99999,...i.includes("top")?{top:8}:{bottom:8},...i.includes("left")?{left:8}:{right:8}};return e.jsxs("div",{style:{...f,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(h=>!h),children:[e.jsx("span",{style:{color:"var(--color-success, #22c55e)"},children:"●"}),e.jsx("span",{children:"Profiler"}),l.used>0&&e.jsxs("span",{style:{color:l.used>100?"var(--color-warning, #f59e0b)":"var(--text-muted, #64748b)"},children:[l.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(h=>e.jsxs("div",{style:{marginBottom:4,display:"flex",gap:8},children:[e.jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis"},children:h.componentName}),e.jsx("span",{style:{color:h.avgRenderTime>16?"var(--color-warning, #f59e0b)":"var(--color-success, #22c55e)"},children:ie(h.avgRenderTime)}),e.jsxs("span",{style:{color:"var(--text-muted, #64748b)",minWidth:30,textAlign:"right"},children:["x",h.renderCount]})]},h.componentName)),e.jsxs("div",{style:{marginTop:8,display:"flex",gap:8},children:[e.jsx("button",{onClick:xr,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:gr,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"})]})]})]})});vr.displayName="ProfilerOverlay";process.env.NODE_ENV;c.createContext(null);const _r=c.createContext({enabled:!0,active:!1,run:()=>{}});function wr(){return c.useContext(_r)}function jr(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 kr(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 Nr=({steps:i,autoStart:a,label:r,size:t="md",className:n,style:s,"data-testid":l})=>{const{enabled:o,run:f}=wr(),{t:h}=mr();if(!o||!i||i.length===0)return null;const y=r??h("tutorial.startAria","Start tutorial");return e.jsx("button",{type:"button",className:`nice-tutorial-button nice-tutorial-button--${t}`+(n?` ${n}`:""),style:s,"data-testid":l,"aria-label":y,title:y,onClick:()=>f(kr(i,h),{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=`
11
+ .nice-tutorial-button {
12
+ display: inline-flex;
13
+ align-items: center;
14
+ justify-content: center;
15
+ border: 1px solid var(--nice-border, #cbd5e1);
16
+ background: var(--nice-bg, #fff);
17
+ color: var(--nice-text-secondary, #475569);
18
+ border-radius: var(--nice-radius-full, 9999px);
19
+ cursor: help;
20
+ font-weight: 700;
21
+ line-height: 1;
22
+ padding: 0;
23
+ transition: background var(--nice-transition, 200ms ease), color var(--nice-transition, 200ms ease), border-color var(--nice-transition, 200ms ease);
24
+ }
25
+ .nice-tutorial-button:hover {
26
+ background: var(--nice-primary, #2563eb);
27
+ border-color: var(--nice-primary, #2563eb);
28
+ color: var(--nice-text-inverse, #fff);
29
+ }
30
+ .nice-tutorial-button:focus-visible {
31
+ outline: none;
32
+ box-shadow: 0 0 0 2px var(--nice-bg, #fff), 0 0 0 4px var(--nice-primary, #2563eb);
33
+ }
34
+ .nice-tutorial-button--sm { width: 16px; height: 16px; font-size: 11px; }
35
+ .nice-tutorial-button--md { width: 20px; height: 20px; font-size: 12px; }
36
+ `,document.head.appendChild(i)}c.createContext(null);c.createContext(null);c.createContext(null);const da={space1:"4px",space2:"8px",space3:"12px",space4:"16px",space5:"20px",space6:"24px",space8:"32px"},ua={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},pa={fast:"120ms ease",normal:"200ms ease",slow:"300ms ease"},ma=i=>({color:i,radiusSm:"4px",radiusMd:"6px",radiusLg:"8px",radiusXl:"12px",radiusFull:"9999px"}),Cr={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)"},Sr={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 E(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:ma(n),shadows:Cr,spacing:da,typography:ua,transitions:pa}}function K(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:ma(n),shadows:Sr,spacing:da,typography:ua,transitions:pa}}E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");K("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");K("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");K("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");K("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");K("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");K("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");K("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");K("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");K("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");K("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");K("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");E("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");K("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");K("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");K("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");K("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");E("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");K("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");E("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");E("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");K("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");K("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");K("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");E("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");K("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");E("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");K("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");E("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");E("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");E("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");K("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");K("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");E("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");E("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");c.createContext(null);const Tr={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"}]},He={classification:["accuracy","precision","recall","f1-score","auc-roc"],regression:["mse","rmse","mae","r2"],clustering:["silhouette","calinski-harabasz","davies-bouldin"]},Ar=[{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"}],Rr=({project:i,onProjectChange:a,onExperimentRun:r,onModelDeploy:t,className:n="",tutorial:s})=>{var T;const[l,o]=c.useState(i||Tr),[f,h]=c.useState("data"),[y,w]=c.useState(null),[C,S]=c.useState(null),[P,k]=c.useState(null),[$,g]=c.useState(!1),[d,j]=c.useState({algorithm:"",hyperparameters:{},preprocessing:[]}),N=c.useCallback(u=>{const b={...l,...u,updatedAt:new Date};o(b),a==null||a(b)},[l,a]),m=async u=>{for(const b of Array.from(u)){const I={id:crypto.randomUUID(),name:b.name.replace(/\.[^.]+$/,""),type:"tabular",source:{type:"file",uri:b.name},size:b.size,rowCount:0,columns:[],splits:[{name:"train",ratio:.8,rowCount:0},{name:"validation",ratio:.1,rowCount:0},{name:"test",ratio:.1,rowCount:0}],createdAt:new Date};if(b.name.endsWith(".csv")){const J=(await b.text()).split(`
37
+ `),Y=J[0].split(",").map(V=>V.trim());I.rowCount=J.length-1,I.columns=Y.map(V=>({name:V,type:"text",nullable:!0,unique:0,missing:0})),I.splits=I.splits.map(V=>({...V,rowCount:Math.floor(I.rowCount*V.ratio)}))}N({datasets:[...l.datasets,I]})}},v=u=>{N({datasets:l.datasets.filter(b=>b.id!==u)}),y===u&&w(null)},x=async()=>{if(!d.algorithm||!y)return;const u={id:crypto.randomUUID(),name:`Experiment ${l.experiments.length+1}`,status:"pending",config:d,metrics:[],artifacts:[],logs:[]};if(N({experiments:[...l.experiments,u]}),g(!1),r){N({experiments:l.experiments.map(b=>b.id===u.id?{...b,status:"running",startedAt:new Date}:b)});try{await r(u);const b=(He[l.type]||He.classification).map(I=>({name:I,value:Math.random()*.3+.7,split:"validation"}));N({experiments:l.experiments.map(I=>I.id===u.id?{...I,status:"completed",completedAt:new Date,metrics:b}:I)})}catch{N({experiments:l.experiments.map(b=>b.id===u.id?{...b,status:"failed"}:b)})}}},p=u=>{const b=l.experiments.find(D=>D.id===u);if(!b)return;const I={id:crypto.randomUUID(),name:`Model from ${b.name}`,version:"1.0.0",algorithm:b.config.algorithm,experimentId:u,status:"registered",metrics:b.metrics,size:Math.floor(Math.random()*100)*1024*1024,artifacts:[],deployments:[],createdAt:new Date};N({models:[...l.models,I]})},_=async u=>{const b=l.models.find(D=>D.id===u);if(!b||!t)return;const I=await t(b);N({models:l.models.map(D=>D.id===u?{...D,status:"production",deployments:[...D.deployments,I]}:D)})},M=u=>u<1024?`${u} B`:u<1024*1024?`${(u/1024).toFixed(1)} KB`:u<1024*1024*1024?`${(u/1024/1024).toFixed(1)} MB`:`${(u/1024/1024/1024).toFixed(1)} GB`,R=u=>{switch(u){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""}};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(Nr,{steps:jr(s,Ar)})}),e.jsxs("header",{className:"ml-studio__header",children:[e.jsxs("div",{className:"header__info",children:[e.jsx("input",{type:"text",value:l.name,onChange:u=>N({name:u.target.value}),className:"project-name-input"}),e.jsxs("select",{value:l.type,onChange:u=>N({type:u.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"})]})]}),e.jsx("div",{className:"header__tabs",children:["data","experiments","models","deploy"].map(u=>e.jsx("button",{className:`tab-button ${f===u?"tab-button--active":""}`,onClick:()=>h(u),children:u.charAt(0).toUpperCase()+u.slice(1)},u))})]}),e.jsxs("div",{className:"ml-studio__content",children:[f==="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:u=>u.target.files&&m(u.target.files),hidden:!0}),"+ Upload Dataset"]})]}),e.jsx("div",{className:"datasets-grid",children:l.datasets.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:"📊"}),e.jsx("p",{children:"No datasets uploaded yet"}),e.jsx("p",{className:"hint",children:"Upload CSV, JSON, or Parquet files to get started"})]}):l.datasets.map(u=>e.jsxs("div",{className:`dataset-card ${y===u.id?"dataset-card--selected":""}`,onClick:()=>w(u.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("span",{className:"dataset-icon",children:"📁"}),e.jsx("h3",{children:u.name}),e.jsx("button",{className:"remove-button",onClick:b=>{b.stopPropagation(),v(u.id)},children:"×"})]}),e.jsxs("div",{className:"card-stats",children:[e.jsxs("span",{children:[u.rowCount.toLocaleString()," rows"]}),e.jsxs("span",{children:[u.columns.length," columns"]}),e.jsx("span",{children:M(u.size)})]}),e.jsx("div",{className:"splits-bar",children:u.splits.map(b=>e.jsx("div",{className:`split split--${b.name}`,style:{width:`${b.ratio*100}%`},title:`${b.name}: ${(b.ratio*100).toFixed(0)}%`},b.name))})]},u.id))}),y&&e.jsx("div",{className:"dataset-details",children:(()=>{const u=l.datasets.find(b=>b.id===y);return u?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:u.columns.map(b=>e.jsxs("tr",{children:[e.jsx("td",{children:b.name}),e.jsx("td",{children:e.jsxs("select",{value:b.type,onChange:I=>{N({datasets:l.datasets.map(D=>D.id===u.id?{...D,columns:D.columns.map(J=>J.name===b.name?{...J,type:I.target.value}:J)}:D)})},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:b.missing}),e.jsx("td",{children:b.unique})]},b.name))})]})]}):null})()})]}),f==="experiments"&&e.jsxs("div",{className:"experiments-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:"Experiments"}),e.jsx("button",{className:"primary-button",onClick:()=>g(!0),disabled:l.datasets.length===0,children:"+ New Experiment"})]}),$&&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:y||"",onChange:u=>w(u.target.value),children:[e.jsx("option",{value:"",children:"Select dataset..."}),l.datasets.map(u=>e.jsx("option",{value:u.id,children:u.name},u.id))]})]}),e.jsxs("label",{children:["Algorithm",e.jsxs("select",{value:d.algorithm,onChange:u=>j({...d,algorithm:u.target.value}),children:[e.jsx("option",{value:"",children:"Select algorithm..."}),(De[l.type]||De.classification).map(u=>e.jsx("option",{value:u.id,children:u.name},u.id))]})]}),y&&e.jsxs("label",{children:["Target Column",e.jsxs("select",{value:d.targetColumn||"",onChange:u=>j({...d,targetColumn:u.target.value}),children:[e.jsx("option",{value:"",children:"Select target..."}),(T=l.datasets.find(u=>u.id===y))==null?void 0:T.columns.map(u=>e.jsx("option",{value:u.name,children:u.name},u.name))]})]})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{className:"secondary-button",onClick:()=>g(!1),children:"Cancel"}),e.jsx("button",{className:"primary-button",onClick:x,disabled:!d.algorithm||!y,children:"Run Experiment"})]})]}),e.jsx("div",{className:"experiments-list",children:l.experiments.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:"🧪"}),e.jsx("p",{children:"No experiments yet"}),e.jsx("p",{className:"hint",children:"Create an experiment to train and evaluate models"})]}):l.experiments.map(u=>e.jsxs("div",{className:`experiment-card ${C===u.id?"experiment-card--selected":""}`,onClick:()=>S(u.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:u.name}),e.jsx("span",{className:`status-badge ${R(u.status)}`,children:u.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Algorithm: ",u.config.algorithm]}),u.duration&&e.jsxs("span",{children:["Duration: ",Math.round(u.duration),"s"]})]}),u.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:u.metrics.slice(0,3).map(b=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:b.name}),e.jsxs("span",{className:"metric-value",children:[(b.value*100).toFixed(1),"%"]})]},b.name))}),u.status==="completed"&&e.jsx("button",{className:"action-button",onClick:b=>{b.stopPropagation(),p(u.id)},children:"Register Model"})]},u.id))})]}),f==="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:l.models.length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:"🤖"}),e.jsx("p",{children:"No models registered yet"}),e.jsx("p",{className:"hint",children:"Complete experiments and register models"})]}):l.models.map(u=>e.jsxs("div",{className:`model-card ${P===u.id?"model-card--selected":""}`,onClick:()=>k(u.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:u.name}),e.jsx("span",{className:`status-badge ${R(u.status)}`,children:u.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Algorithm: ",u.algorithm]}),e.jsxs("span",{children:["Version: ",u.version]}),e.jsxs("span",{children:["Size: ",M(u.size)]})]}),u.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:u.metrics.slice(0,3).map(b=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:b.name}),e.jsxs("span",{className:"metric-value",children:[(b.value*100).toFixed(1),"%"]})]},b.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:b=>{b.stopPropagation(),_(u.id)},disabled:u.status==="production",children:u.status==="production"?"Deployed":"Deploy"})]})]},u.id))})]}),f==="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:l.models.filter(u=>u.deployments.length>0).length===0?e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:"🚀"}),e.jsx("p",{children:"No deployments yet"}),e.jsx("p",{className:"hint",children:"Deploy a model to create inference endpoints"})]}):l.models.filter(u=>u.deployments.length>0).flatMap(u=>u.deployments.map(b=>({model:u,deployment:b}))).map(({model:u,deployment:b})=>e.jsxs("div",{className:"deployment-card",children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:b.name}),e.jsx("span",{className:`status-badge ${R(b.status)}`,children:b.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Model: ",u.name]}),e.jsxs("span",{children:["Endpoint: ",b.endpoint]})]}),e.jsxs("div",{className:"resources-info",children:[e.jsxs("span",{children:["CPU: ",b.resources.cpu," cores"]}),e.jsxs("span",{children:["Memory: ",b.resources.memory," GB"]}),e.jsxs("span",{children:["Replicas: ",b.resources.replicas]})]})]},b.id))})]})]})]})},Mr={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},Be=["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)"],Pr=({project:i,onProjectChange:a,onLabelSave:r,onExport:t,className:n=""})=>{var ee;const[s,l]=c.useState(i||Mr),[o,f]=c.useState("label"),[h,y]=c.useState(0),[w,C]=c.useState(null),[S,P]=c.useState("select"),[k,$]=c.useState(!1),[g,d]=c.useState(null),[j,N]=c.useState(1),[m,v]=c.useState(!1),[x,p]=c.useState("all"),_=c.useRef(null),M=c.useRef(null),R=s.items[h];c.useEffect(()=>{i&&l(i)},[i]);const T=c.useCallback(A=>{const L={...s,...A};L.statistics={totalItems:L.items.length,labeled:L.items.filter(H=>H.status!=="pending").length,reviewed:L.items.filter(H=>H.status==="review"||H.status==="approved").length,approved:L.items.filter(H=>H.status==="approved").length,byClass:L.labelSchema.classes.map(H=>({classId:H.id,count:L.items.flatMap(O=>O.labels).filter(O=>O.classId===H.id).length}))},l(L),a==null||a(L)},[s,a]),u=()=>{const A={id:crypto.randomUUID(),name:`Class ${s.labelSchema.classes.length+1}`,color:Be[s.labelSchema.classes.length%Be.length],shortcut:String(s.labelSchema.classes.length+1)};T({labelSchema:{...s.labelSchema,classes:[...s.labelSchema.classes,A]}})},b=A=>{T({labelSchema:{...s.labelSchema,classes:s.labelSchema.classes.filter(L=>L.id!==A)},items:s.items.map(L=>({...L,labels:L.labels.filter(H=>H.classId!==A)}))})},I=(A,L)=>{T({labelSchema:{...s.labelSchema,classes:s.labelSchema.classes.map(H=>H.id===A?{...H,...L}:H)}})},D=(A,L)=>{if(!R)return;const H={id:crypto.randomUUID(),classId:A,type:s.type==="classification"?"class":s.type==="bounding-box"?"bbox":"class",data:L||{},createdBy:"current-user",createdAt:new Date},O={...R,labels:[...R.labels,H],status:"labeled"};T({items:s.items.map(B=>B.id===R.id?O:B)}),r==null||r(O)},J=A=>{if(!R)return;const L={...R,labels:R.labels.filter(H=>H.id!==A),status:R.labels.length<=1?"pending":"labeled"};T({items:s.items.map(H=>H.id===R.id?L:H)})},Y=A=>{var B;if(S!=="bbox"||!w)return;const L=(B=_.current)==null?void 0:B.getBoundingClientRect();if(!L)return;const H=(A.clientX-L.left)/j,O=(A.clientY-L.top)/j;$(!0),d({x:H,y:O,width:0,height:0})},V=A=>{var B;if(!k||!g)return;const L=(B=_.current)==null?void 0:B.getBoundingClientRect();if(!L)return;const H=(A.clientX-L.left)/j,O=(A.clientY-L.top)/j;d({...g,width:H-g.x,height:O-g.y})},z=()=>{!k||!g||!w||($(!1),Math.abs(g.width)>10&&Math.abs(g.height)>10&&D(w,{x:g.width<0?g.x+g.width:g.x,y:g.height<0?g.y+g.height:g.y,width:Math.abs(g.width),height:Math.abs(g.height)}),d(null))},F=A=>{const L=x==="all"?s.items:s.items.filter(O=>O.status===x),H=L.findIndex(O=>O.id===(R==null?void 0:R.id));if(A==="prev"&&H>0){const O=L[H-1];y(s.items.findIndex(B=>B.id===O.id))}else if(A==="next"&&H<L.length-1){const O=L[H+1];y(s.items.findIndex(B=>B.id===O.id))}},U=()=>{if(!R)return;const A={...R,status:"approved"};T({items:s.items.map(L=>L.id===R.id?A:L)}),F("next")},W=()=>{if(!R)return;const A={...R,status:"rejected"};T({items:s.items.map(L=>L.id===R.id?A:L)}),F("next")},q=async A=>{t&&await t(A)};c.useEffect(()=>{const A=L=>{const H=L.key,O=s.labelSchema.classes.find(B=>B.shortcut===H);O&&(s.type==="classification"?(D(O.id),F("next")):C(O.id)),L.key==="ArrowLeft"||L.key==="a"?F("prev"):(L.key==="ArrowRight"||L.key==="d")&&F("next"),L.key==="Enter"?U():L.key==="Backspace"&&W()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[R,s.labelSchema.classes,s.type]);const Z=A=>{switch(A){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:s.name,onChange:A=>T({name:A.target.value}),className:"project-name-input"}),e.jsxs("div",{className:"progress-bar",children:[e.jsx("div",{className:"progress-fill",style:{width:`${s.statistics.labeled/Math.max(s.statistics.totalItems,1)*100}%`}}),e.jsxs("span",{className:"progress-text",children:[s.statistics.labeled," / ",s.statistics.totalItems," labeled"]})]})]}),e.jsx("div",{className:"header__tabs",children:["label","schema","review","export"].map(A=>e.jsx("button",{className:`tab-button ${o===A?"tab-button--active":""}`,onClick:()=>f(A),children:A.charAt(0).toUpperCase()+A.slice(1)},A))}),e.jsx("button",{className:"shortcuts-button",onClick:()=>v(!m),children:"⌨️ Shortcuts"})]}),e.jsxs("div",{className:"labeler__content",children:[o==="label"&&e.jsxs("div",{className:"label-panel",children:[e.jsxs("div",{className:"label-toolbar",children:[e.jsxs("div",{className:"tool-group",children:[e.jsx("button",{className:`tool-button ${S==="select"?"tool-button--active":""}`,onClick:()=>P("select"),children:"↖️ Select"}),(s.type==="bounding-box"||s.type==="multi-label")&&e.jsx("button",{className:`tool-button ${S==="bbox"?"tool-button--active":""}`,onClick:()=>P("bbox"),children:"⬜ Box"}),s.type==="polygon"&&e.jsx("button",{className:`tool-button ${S==="polygon"?"tool-button--active":""}`,onClick:()=>P("polygon"),children:"⬡ Polygon"})]}),e.jsxs("div",{className:"zoom-group",children:[e.jsx("button",{onClick:()=>N(Math.max(.25,j-.25)),children:"-"}),e.jsxs("span",{children:[Math.round(j*100),"%"]}),e.jsx("button",{onClick:()=>N(Math.min(4,j+.25)),children:"+"})]}),e.jsxs("div",{className:"navigation-group",children:[e.jsx("button",{onClick:()=>F("prev"),disabled:h===0,children:"← Prev"}),e.jsxs("span",{children:[h+1," / ",s.items.length]}),e.jsx("button",{onClick:()=>F("next"),disabled:h>=s.items.length-1,children:"Next →"})]})]}),e.jsxs("div",{className:"label-workspace",children:[e.jsx("div",{className:"canvas-container",ref:M,children:R?e.jsxs(e.Fragment,{children:[R.data.type==="image"&&e.jsxs(e.Fragment,{children:[e.jsx("img",{src:R.data.url,alt:"Labeling item",className:"labeling-image",style:{transform:`scale(${j})`}}),e.jsx("canvas",{ref:_,className:"labeling-canvas",onMouseDown:Y,onMouseMove:V,onMouseUp:z,onMouseLeave:z,style:{transform:`scale(${j})`,cursor:S==="bbox"?"crosshair":"default"}}),e.jsxs("div",{className:"annotations-overlay",style:{transform:`scale(${j})`},children:[R.labels.filter(A=>A.type==="bbox"&&A.data.x!==void 0).map(A=>{const L=s.labelSchema.classes.find(H=>H.id===A.classId);return e.jsxs("div",{className:"bbox-annotation",style:{left:A.data.x,top:A.data.y,width:A.data.width,height:A.data.height,borderColor:(L==null?void 0:L.color)||"var(--nice-danger, #ff0000)"},children:[e.jsx("span",{className:"bbox-label",style:{backgroundColor:(L==null?void 0:L.color)||"var(--nice-danger, #ff0000)"},children:L==null?void 0:L.name}),e.jsx("button",{className:"bbox-remove",onClick:()=>J(A.id),children:"×"})]},A.id)}),g&&e.jsx("div",{className:"bbox-drawing",style:{left:g.width<0?g.x+g.width:g.x,top:g.height<0?g.y+g.height:g.y,width:Math.abs(g.width),height:Math.abs(g.height),borderColor:(ee=s.labelSchema.classes.find(A=>A.id===w))==null?void 0:ee.color}})]})]}),R.data.type==="text"&&e.jsx("div",{className:"text-labeling",children:e.jsx("p",{className:"text-content",children:R.data.text})})]}):e.jsxs("div",{className:"empty-state",children:[e.jsx("span",{className:"icon",children:"📋"}),e.jsx("p",{children:"No items to label"})]})}),e.jsxs("aside",{className:"class-sidebar",children:[e.jsx("h3",{children:"Classes"}),e.jsx("div",{className:"class-list",children:s.labelSchema.classes.map(A=>e.jsxs("button",{className:`class-button ${w===A.id?"class-button--active":""}`,style:{borderLeftColor:A.color},onClick:()=>{s.type==="classification"?(D(A.id),F("next")):C(A.id)},children:[e.jsx("span",{className:"class-color",style:{backgroundColor:A.color}}),e.jsx("span",{className:"class-name",children:A.name}),A.shortcut&&e.jsx("span",{className:"class-shortcut",children:A.shortcut})]},A.id))}),R&&R.labels.length>0&&e.jsxs("div",{className:"current-labels",children:[e.jsx("h4",{children:"Labels"}),R.labels.map(A=>{const L=s.labelSchema.classes.find(H=>H.id===A.classId);return e.jsxs("div",{className:"label-item",children:[e.jsx("span",{className:"label-color",style:{backgroundColor:L==null?void 0:L.color}}),e.jsx("span",{className:"label-name",children:L==null?void 0:L.name}),e.jsx("button",{onClick:()=>J(A.id),children:"×"})]},A.id)})]}),o==="label"&&R&&e.jsxs("div",{className:"label-actions",children:[e.jsx("button",{className:"approve-button",onClick:U,children:"✓ Approve"}),e.jsx("button",{className:"reject-button",onClick:W,children:"✗ Reject"})]})]})]})]}),o==="schema"&&e.jsxs("div",{className:"schema-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:"Label Schema"}),e.jsx("button",{className:"primary-button",onClick:u,children:"+ Add Class"})]}),e.jsxs("div",{className:"schema-settings",children:[e.jsxs("label",{children:["Labeling Type",e.jsxs("select",{value:s.type,onChange:A=>T({type:A.target.value}),children:[e.jsx("option",{value:"classification",children:"Single Classification"}),e.jsx("option",{value:"multi-label",children:"Multi-Label Classification"}),e.jsx("option",{value:"bounding-box",children:"Bounding Box"}),e.jsx("option",{value:"polygon",children:"Polygon"}),e.jsx("option",{value:"segmentation",children:"Segmentation"}),e.jsx("option",{value:"ner",children:"Named Entity Recognition"})]})]}),e.jsxs("label",{children:["Data Type",e.jsxs("select",{value:s.dataType,onChange:A=>T({dataType:A.target.value}),children:[e.jsx("option",{value:"image",children:"Image"}),e.jsx("option",{value:"text",children:"Text"}),e.jsx("option",{value:"audio",children:"Audio"}),e.jsx("option",{value:"video",children:"Video"})]})]})]}),e.jsx("div",{className:"classes-list",children:s.labelSchema.classes.map((A,L)=>e.jsxs("div",{className:"class-editor",children:[e.jsx("input",{type:"color",value:A.color,onChange:H=>I(A.id,{color:H.target.value}),className:"color-picker"}),e.jsx("input",{type:"text",value:A.name,onChange:H=>I(A.id,{name:H.target.value}),className:"class-name-input",placeholder:"Class name"}),e.jsx("input",{type:"text",value:A.shortcut||"",onChange:H=>I(A.id,{shortcut:H.target.value}),className:"shortcut-input",placeholder:"Key",maxLength:1}),e.jsx("button",{className:"remove-class-button",onClick:()=>b(A.id),children:"🗑️"})]},A.id))}),e.jsxs("div",{className:"guidelines-section",children:[e.jsx("h3",{children:"Labeling Guidelines"}),e.jsx("textarea",{value:s.guidelines||"",onChange:A=>T({guidelines:A.target.value}),placeholder:"Enter labeling guidelines for annotators...",rows:6})]})]}),o==="review"&&e.jsxs("div",{className:"review-panel",children:[e.jsxs("div",{className:"panel-header",children:[e.jsx("h2",{children:"Review Labels"}),e.jsx("div",{className:"filter-group",children:e.jsxs("select",{value:x,onChange:A=>p(A.target.value),children:[e.jsx("option",{value:"all",children:"All Items"}),e.jsx("option",{value:"labeled",children:"Labeled"}),e.jsx("option",{value:"review",children:"Needs Review"}),e.jsx("option",{value:"approved",children:"Approved"}),e.jsx("option",{value:"rejected",children:"Rejected"})]})})]}),e.jsx("div",{className:"items-grid",children:s.items.filter(A=>x==="all"||A.status===x).map((A,L)=>{var H;return e.jsxs("div",{className:`item-card ${h===s.items.indexOf(A)?"item-card--active":""}`,onClick:()=>{y(s.items.indexOf(A)),f("label")},children:[A.data.type==="image"&&e.jsx("img",{src:A.data.url,alt:`Item ${L+1}`,className:"item-thumbnail"}),A.data.type==="text"&&e.jsxs("p",{className:"item-text-preview",children:[(H=A.data.text)==null?void 0:H.slice(0,100),"..."]}),e.jsxs("div",{className:"item-footer",children:[e.jsx("span",{className:"status-dot",style:{backgroundColor:Z(A.status)}}),e.jsxs("span",{children:[A.labels.length," labels"]})]})]},A.id)})})]}),o==="export"&&e.jsxs("div",{className:"export-panel",children:[e.jsx("div",{className:"panel-header",children:e.jsx("h2",{children:"Export Labels"})}),e.jsxs("div",{className:"export-stats",children:[e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:s.statistics.totalItems}),e.jsx("span",{className:"stat-label",children:"Total Items"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:s.statistics.labeled}),e.jsx("span",{className:"stat-label",children:"Labeled"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:s.statistics.approved}),e.jsx("span",{className:"stat-label",children:"Approved"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:s.labelSchema.classes.length}),e.jsx("span",{className:"stat-label",children:"Classes"})]})]}),e.jsxs("div",{className:"export-formats",children:[e.jsx("h3",{children:"Export Format"}),e.jsxs("div",{className:"format-grid",children:[e.jsxs("button",{className:"format-button",onClick:()=>q("coco"),children:[e.jsx("span",{className:"format-icon",children:"📦"}),e.jsx("span",{className:"format-name",children:"COCO JSON"}),e.jsx("span",{className:"format-desc",children:"Common format for object detection"})]}),e.jsxs("button",{className:"format-button",onClick:()=>q("voc"),children:[e.jsx("span",{className:"format-icon",children:"📄"}),e.jsx("span",{className:"format-name",children:"Pascal VOC"}),e.jsx("span",{className:"format-desc",children:"XML format for bounding boxes"})]}),e.jsxs("button",{className:"format-button",onClick:()=>q("yolo"),children:[e.jsx("span",{className:"format-icon",children:"⚡"}),e.jsx("span",{className:"format-name",children:"YOLO"}),e.jsx("span",{className:"format-desc",children:"Text format for YOLO models"})]}),e.jsxs("button",{className:"format-button",onClick:()=>q("csv"),children:[e.jsx("span",{className:"format-icon",children:"📊"}),e.jsx("span",{className:"format-name",children:"CSV"}),e.jsx("span",{className:"format-desc",children:"Tabular format for classification"})]})]})]}),e.jsxs("div",{className:"class-distribution",children:[e.jsx("h3",{children:"Class Distribution"}),e.jsx("div",{className:"distribution-bars",children:s.statistics.byClass.map(A=>{const L=s.labelSchema.classes.find(O=>O.id===A.classId),H=A.count/Math.max(s.statistics.labeled,1)*100;return e.jsxs("div",{className:"distribution-row",children:[e.jsx("span",{className:"class-name",style:{color:L==null?void 0:L.color},children:L==null?void 0:L.name}),e.jsx("div",{className:"bar-container",children:e.jsx("div",{className:"bar-fill",style:{width:`${H}%`,backgroundColor:L==null?void 0:L.color}})}),e.jsx("span",{className:"count",children:A.count})]},A.classId)})})]})]})]}),m&&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:"Keyboard Shortcuts"}),e.jsx("button",{onClick:()=>v(!1),children:"×"})]}),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:"Previous item"})]}),e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:"→ / D"}),e.jsx("span",{className:"description",children:"Next item"})]}),e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:"Enter"}),e.jsx("span",{className:"description",children:"Approve item"})]}),e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:"Backspace"}),e.jsx("span",{className:"description",children:"Reject item"})]}),s.labelSchema.classes.map(A=>A.shortcut&&e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:A.shortcut}),e.jsxs("span",{className:"description",children:["Label as ",A.name]})]},A.id))]})]})})]})},$r={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:[]},Ir=({endpoint:i,onInference:a,showMetrics:r=!0,showLogs:t=!0,className:n=""})=>{const[s,l]=c.useState(i||$r),[o,f]=c.useState("test"),[h,y]=c.useState("text"),[w,C]=c.useState(""),[S,P]=c.useState("{}"),[k,$]=c.useState(null),[g,d]=c.useState({temperature:.7,topK:50,topP:.9,maxTokens:256,threshold:.5}),[j,N]=c.useState(null),[m,v]=c.useState(!1),[x,p]=c.useState(null),[_,M]=c.useState([]),[R,T]=c.useState(null),u=c.useRef(null),b=z=>{var U;const F=(U=z.target.files)==null?void 0:U[0];if(F){const W=new FileReader;W.onload=q=>{var Z;$((Z=q.target)==null?void 0:Z.result)},W.readAsDataURL(F)}},I=async()=>{if(!a){p("No inference handler provided");return}v(!0),p(null),N(null);const z=[];switch(h){case"text":z.push({type:"text",data:w});break;case"image":k&&z.push({type:"image",data:k});break;case"json":try{z.push({type:"json",data:JSON.parse(S)})}catch{p("Invalid JSON input"),v(!1);return}break;case"tabular":try{z.push({type:"tabular",data:JSON.parse(S)})}catch{p("Invalid tabular data"),v(!1);return}break}const F={inputs:z,parameters:g};try{const U=Date.now(),W=await a(F),q=Date.now()-U;N(W),l(Z=>({...Z,metrics:{...Z.metrics,requestsTotal:Z.metrics.requestsTotal+1,latencyP50:(Z.metrics.latencyP50+q)/2},logs:[{timestamp:new Date,requestId:W.requestId,duration:q,status:"success",inputSize:JSON.stringify(z).length,outputSize:JSON.stringify(W.predictions).length},...Z.logs.slice(0,99)]}))}catch(U){const W=U instanceof Error?U.message:"Inference failed";p(W),l(q=>({...q,metrics:{...q.metrics,requestsTotal:q.metrics.requestsTotal+1,errorRate:(q.metrics.errorRate*q.metrics.requestsTotal+1)/(q.metrics.requestsTotal+1)},logs:[{timestamp:new Date,requestId:crypto.randomUUID(),duration:0,status:"error",inputSize:JSON.stringify(z).length,outputSize:0,error:W},...q.logs.slice(0,99)]}))}finally{v(!1)}},D=async z=>{if(a){T(0),M([]);for(let F=0;F<z.length;F++){const U={inputs:[z[F]],parameters:g};try{const W=await a(U);M(q=>[...q,W])}catch(W){console.error("Batch item failed:",W)}T((F+1)/z.length*100)}T(null)}},J=z=>z<1e3?`${z.toFixed(0)}ms`:`${(z/1e3).toFixed(2)}s`,Y=z=>z.toLocaleTimeString(),V=(z,F)=>e.jsxs("div",{className:"prediction-item",children:[z.label&&e.jsxs("div",{className:"prediction-label",children:[e.jsx("span",{className:"label-name",children:z.label}),z.confidence!==void 0&&e.jsxs("span",{className:"confidence-badge",style:{backgroundColor:`hsl(${z.confidence*120}, 70%, 40%)`},children:[(z.confidence*100).toFixed(1),"%"]})]}),z.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:z.score.toFixed(4)})]}),z.text&&e.jsx("div",{className:"prediction-text",children:e.jsx("pre",{children:z.text})}),z.bbox&&e.jsx("div",{className:"prediction-bbox",children:e.jsxs("span",{children:["Box: (",z.bbox.x,", ",z.bbox.y,") - ",z.bbox.width,"×",z.bbox.height]})}),z.raw!==void 0&&z.raw!==null&&e.jsxs("details",{className:"raw-output",children:[e.jsx("summary",{children:"Raw Output"}),e.jsx("pre",{children:JSON.stringify(z.raw,null,2)})]})]},F);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 ${o==="test"?"tab-button--active":""}`,onClick:()=>f("test"),children:"Test"}),e.jsx("button",{className:`tab-button ${o==="batch"?"tab-button--active":""}`,onClick:()=>f("batch"),children:"Batch"}),r&&e.jsx("button",{className:`tab-button ${o==="metrics"?"tab-button--active":""}`,onClick:()=>f("metrics"),children:"Metrics"}),t&&e.jsx("button",{className:`tab-button ${o==="logs"?"tab-button--active":""}`,onClick:()=>f("logs"),children:"Logs"})]})]}),e.jsxs("div",{className:"inference__content",children:[o==="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(z=>e.jsx("button",{className:`type-button ${h===z?"type-button--active":""}`,onClick:()=>y(z),children:z.charAt(0).toUpperCase()+z.slice(1)},z))}),e.jsxs("div",{className:"input-area",children:[h==="text"&&e.jsx("textarea",{value:w,onChange:z=>C(z.target.value),placeholder:"Enter text input...",rows:6,className:"text-input"}),h==="image"&&e.jsx("div",{className:"image-input",children:k?e.jsxs("div",{className:"image-preview",children:[e.jsx("img",{src:k,alt:"Input preview"}),e.jsx("button",{className:"clear-button",onClick:()=>$(null),children:"Clear"})]}):e.jsxs("label",{className:"upload-zone",children:[e.jsx("input",{ref:u,type:"file",accept:"image/*",onChange:b,hidden:!0}),e.jsx("span",{className:"upload-icon",children:"🖼️"}),e.jsx("span",{children:"Click or drag to upload image"})]})}),(h==="json"||h==="tabular")&&e.jsx("textarea",{value:S,onChange:z=>P(z.target.value),placeholder:h==="json"?`{
12
38
  "key": "value"
13
39
  }`:`[
14
40
  {"col1": "value1", "col2": "value2"}
15
- ]`,rows:10,className:"json-input"})]}),e.jsxs("div",{className:"parameters-section",children:[e.jsx("h4",{children:"Parameters"}),e.jsxs("div",{className:"parameters-grid",children:[e.jsxs("label",{children:["Temperature",e.jsx("input",{type:"number",value:h.temperature,onChange:I=>d({...h,temperature:parseFloat(I.target.value)}),min:"0",max:"2",step:"0.1"})]}),e.jsxs("label",{children:["Top K",e.jsx("input",{type:"number",value:h.topK,onChange:I=>d({...h,topK:parseInt(I.target.value)}),min:"1",max:"100"})]}),e.jsxs("label",{children:["Top P",e.jsx("input",{type:"number",value:h.topP,onChange:I=>d({...h,topP:parseFloat(I.target.value)}),min:"0",max:"1",step:"0.05"})]}),e.jsxs("label",{children:["Threshold",e.jsx("input",{type:"number",value:h.threshold,onChange:I=>d({...h,threshold:parseFloat(I.target.value)}),min:"0",max:"1",step:"0.05"})]})]})]}),e.jsx("button",{className:"run-button",onClick:z,disabled:p||!w&&!k&&S==="{}",children:p?"Running...":"Run Inference"})]}),e.jsxs("div",{className:"output-section",children:[e.jsx("h3",{children:"Output"}),b&&e.jsxs("div",{className:"error-message",children:[e.jsx("span",{className:"error-icon",children:"⚠️"}),b]}),v&&e.jsxs("div",{className:"result-container",children:[e.jsxs("div",{className:"result-meta",children:[e.jsxs("span",{children:["Request ID: ",v.requestId]}),e.jsxs("span",{children:["Latency: ",J(v.latency)]}),e.jsxs("span",{children:["Model: ",v.modelVersion]})]}),e.jsx("div",{className:"predictions-list",children:v.predictions.map((I,F)=>Y(I,F))})]}),!b&&!v&&e.jsxs("div",{className:"empty-output",children:[e.jsx("span",{className:"icon",children:"📤"}),e.jsx("p",{children:"Run inference to see results"})]})]})]}),c==="batch"&&e.jsxs("div",{className:"batch-panel",children:[e.jsxs("div",{className:"batch-upload",children:[e.jsx("h3",{children:"Batch Inference"}),e.jsx("p",{className:"hint",children:"Upload a file with multiple inputs for batch processing"}),e.jsxs("label",{className:"upload-zone",children:[e.jsx("input",{type:"file",accept:".json,.csv,.txt",onChange:async I=>{var q;const F=(q=I.target.files)==null?void 0:q[0];if(F){const W=await F.text();try{const U=JSON.parse(W);if(Array.isArray(U)){const K=U.map(Q=>({type:"json",data:Q}));D(K)}}catch{u("Invalid batch file format")}}},hidden:!0}),e.jsx("span",{className:"upload-icon",children:"📁"}),e.jsx("span",{children:"Upload JSON array file"})]})]}),R!==null&&e.jsxs("div",{className:"batch-progress",children:[e.jsx("div",{className:"progress-bar",children:e.jsx("div",{className:"progress-fill",style:{width:`${R}%`}})}),e.jsxs("span",{children:[Math.round(R),"%"]})]}),y.length>0&&e.jsxs("div",{className:"batch-results",children:[e.jsxs("h3",{children:["Results (",y.length,")"]}),e.jsx("div",{className:"results-list",children:y.map((I,F)=>e.jsxs("div",{className:"batch-result-item",children:[e.jsxs("span",{className:"result-index",children:["#",F+1]}),I.predictions.map((q,W)=>e.jsxs("span",{className:"result-prediction",children:[q.label,": ",(q.confidence||q.score||0*100).toFixed(1),"%"]},W))]},F))})]})]}),c==="metrics"&&t&&e.jsxs("div",{className:"metrics-panel",children:[e.jsxs("div",{className:"metrics-grid",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:s.metrics.requestsTotal}),e.jsx("span",{className:"metric-label",children:"Total Requests"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:s.metrics.requestsPerSecond.toFixed(1)}),e.jsx("span",{className:"metric-label",children:"Requests/sec"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:J(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:J(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:J(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(I=>e.jsxs("div",{className:"histogram-bar",children:[e.jsx("div",{className:"bar-fill",style:{height:`${Math.min(100,s.metrics.latencyP50*I/100)}px`}}),e.jsxs("span",{className:"percentile-label",children:["P",I]})]},I))})]})]}),c==="logs"&&r&&e.jsxs("div",{className:"logs-panel",children:[e.jsxs("div",{className:"logs-header",children:[e.jsx("h3",{children:"Request Logs"}),e.jsx("button",{className:"clear-logs-button",onClick:()=>m(I=>({...I,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((I,F)=>e.jsxs("tr",{className:`log-row log-row--${I.status}`,children:[e.jsx("td",{children:H(I.timestamp)}),e.jsx("td",{className:"request-id",children:I.requestId.slice(0,8)}),e.jsx("td",{children:J(I.duration)}),e.jsx("td",{children:e.jsx("span",{className:`status-badge status-badge--${I.status}`,children:I.status})}),e.jsxs("td",{children:[I.inputSize," B"]}),e.jsxs("td",{children:[I.outputSize," B"]})]},F))})]})})]})]})]})};class te{constructor(a){this.abortController=null,this.config={timeout:3e4,maxRetries:3,retryDelay:1e3,...a}}async healthCheck(){try{return(await this.chat({messages:[{role:"user",content:"Hi"}],maxTokens:5})).choices.length>0}catch{return!1}}async fetchWithRetry(a,t,r=this.config.maxRetries){let n=null;for(let s=0;s<=r;s++)try{this.abortController=new AbortController;const m=setTimeout(()=>{var g;return(g=this.abortController)==null?void 0:g.abort()},this.config.timeout),c=await fetch(a,{...t,signal:this.abortController.signal});if(clearTimeout(m),c.ok)return c;if(c.status>=400&&c.status<500){const g=await c.text();throw new Error(`API Error ${c.status}: ${g}`)}n=new Error(`HTTP ${c.status}`)}catch(m){n=m,s<r&&await this.delay(this.config.retryDelay*(s+1))}throw n??new Error("Request failed after retries")}delay(a){return new Promise(t=>setTimeout(t,a))}async parseSSEStream(a,t,r,n){var g;const s=(g=a.body)==null?void 0:g.getReader();if(!s){n==null||n(new Error("No response body"));return}const m=new TextDecoder;let c="";try{for(;;){const{done:f,value:j}=await s.read();if(f)break;c+=m.decode(j,{stream:!0});const w=c.split(`
16
- `);c=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 $=JSON.parse(S);t(this.normalizeStreamChunk($))}catch{}}}r==null||r()}catch(f){n==null||n(f)}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,t,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify({...this.buildRequestBody(a),stream:!0})});await this.parseSSEStream(s,t,r,n)}catch(s){n==null||n(s)}}async listModels(){return((await(await this.fetchWithRetry(`${this.baseUrl}/models`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers}})).json()).data||[]).filter(r=>r.id.includes("gpt")).map(r=>r.id)}buildRequestBody(a){return{model:a.model||this.config.model||"gpt-4o-mini",messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024,top_p:a.topP,frequency_penalty:a.frequencyPenalty,presence_penalty:a.presencePenalty,stop:a.stop,functions:a.functions,function_call:a.functionCall}}normalizeResponse(a,t){const r=a;return{id:r.id,model:r.model,choices:r.choices.map(n=>({index:n.index,message:n.message,finishReason:n.finish_reason})),usage:{promptTokens:r.usage.prompt_tokens,completionTokens:r.usage.completion_tokens,totalTokens:r.usage.total_tokens},estimatedCost:this.estimateCost(r.model,r.usage.prompt_tokens,r.usage.completion_tokens)}}normalizeStreamChunk(a){const t=a;return{id:t.id,choices:t.choices.map(r=>({index:r.index,delta:r.delta,finishReason:r.finish_reason}))}}estimateCost(a,t,r){const n={"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4-turbo":{input:10,output:30},"gpt-4":{input:30,output:60},"gpt-3.5-turbo":{input:.5,output:1.5}},s=Object.keys(n).find(c=>a.includes(c)),m=s?n[s]:n["gpt-4o-mini"];return t/1e6*m.input+r/1e6*m.output}}class ia extends te{constructor(a){super(a),this.type="anthropic",this.name="Anthropic Claude",this.baseUrl=a.baseUrl||"https://api.anthropic.com/v1"}async chat(a){const r=await(await this.fetchWithRetry(`${this.baseUrl}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey,"anthropic-version":"2023-06-01",...this.config.headers},body:JSON.stringify(this.buildRequestBody(a))})).json();return this.normalizeResponse(r)}async chatStream(a,t,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey,"anthropic-version":"2023-06-01",...this.config.headers},body:JSON.stringify({...this.buildRequestBody(a),stream:!0})});await this.parseAnthropicStream(s,t,r,n)}catch(s){n==null||n(s)}}buildRequestBody(a){const t=a.messages.find(n=>n.role==="system"),r=a.messages.filter(n=>n.role!=="system");return{model:a.model||this.config.model||"claude-3-5-sonnet-20241022",max_tokens:a.maxTokens??1024,system:t==null?void 0:t.content,messages:r.map(n=>({role:n.role==="assistant"?"assistant":"user",content:n.content})),temperature:a.temperature??.7}}normalizeResponse(a){const t=a,r=t.content.find(n=>n.type==="text");return{id:t.id,model:t.model,choices:[{index:0,message:{role:"assistant",content:(r==null?void 0:r.text)||""},finishReason:t.stop_reason==="end_turn"?"stop":"length"}],usage:{promptTokens:t.usage.input_tokens,completionTokens:t.usage.output_tokens,totalTokens:t.usage.input_tokens+t.usage.output_tokens},estimatedCost:this.estimateCost(t.model,t.usage.input_tokens,t.usage.output_tokens)}}normalizeStreamChunk(a){var r;const t=a;return{id:"",choices:[{index:t.index||0,delta:{content:((r=t.delta)==null?void 0:r.text)||""},finishReason:t.type==="message_stop"?"stop":null}]}}async parseAnthropicStream(a,t,r,n){var g;const s=(g=a.body)==null?void 0:g.getReader();if(!s){n==null||n(new Error("No response body"));return}const m=new TextDecoder;let c="";try{for(;;){const{done:f,value:j}=await s.read();if(f)break;c+=m.decode(j,{stream:!0});const w=c.split(`
17
- `);c=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")t(this.normalizeStreamChunk(S));else if(S.type==="message_stop"){r==null||r();return}}catch{}}r==null||r()}catch(f){n==null||n(f)}finally{s.releaseLock()}}estimateCost(a,t,r){const n={"claude-3-5-sonnet":{input:3,output:15},"claude-3-5-haiku":{input:.25,output:1.25},"claude-3-opus":{input:15,output:75},"claude-3-sonnet":{input:3,output:15},"claude-3-haiku":{input:.25,output:1.25}},s=Object.keys(n).find(c=>a.includes(c)),m=s?n[s]:n["claude-3-5-sonnet"];return t/1e6*m.input+r/1e6*m.output}}class ra extends te{constructor(a){if(super(a),this.type="azure-openai",this.name="Azure OpenAI",!a.baseUrl||!a.deployment)throw new Error("Azure OpenAI requires baseUrl and deployment")}async chat(a){const t=`${this.config.baseUrl}/openai/deployments/${this.config.deployment}/chat/completions?api-version=${this.config.apiVersion||"2024-02-01"}`,n=await(await this.fetchWithRetry(t,{method:"POST",headers:{"Content-Type":"application/json","api-key":this.config.apiKey,...this.config.headers},body:JSON.stringify(this.buildRequestBody(a))})).json();return this.normalizeResponse(n)}async chatStream(a,t,r,n){const s=`${this.config.baseUrl}/openai/deployments/${this.config.deployment}/chat/completions?api-version=${this.config.apiVersion||"2024-02-01"}`;try{const m=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(m,t,r,n)}catch(m){n==null||n(m)}}buildRequestBody(a){return{messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024,top_p:a.topP,frequency_penalty:a.frequencyPenalty,presence_penalty:a.presencePenalty,stop:a.stop}}normalizeResponse(a){const t=a;return{id:t.id,model:t.model,choices:t.choices.map(r=>({index:r.index,message:r.message,finishReason:r.finish_reason})),usage:{promptTokens:t.usage.prompt_tokens,completionTokens:t.usage.completion_tokens,totalTokens:t.usage.total_tokens}}}normalizeStreamChunk(a){const t=a;return{id:t.id,choices:t.choices.map(r=>({index:r.index,delta:r.delta,finishReason:r.finish_reason}))}}}class na extends te{constructor(a){super(a),this.type="ollama",this.name="Ollama (Local)",this.baseUrl=a.baseUrl||"http://localhost:11434"}async chat(a){const r=await(await this.fetchWithRetry(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json",...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama3",messages:a.messages,stream:!1,options:{temperature:a.temperature??.7,num_predict:a.maxTokens??1024}})})).json();return this.normalizeResponse(r)}async chatStream(a,t,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json",...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama3",messages:a.messages,stream:!0,options:{temperature:a.temperature??.7,num_predict:a.maxTokens??1024}})});await this.parseOllamaStream(s,t,r,n)}catch(s){n==null||n(s)}}async listModels(){try{return((await(await this.fetchWithRetry(`${this.baseUrl}/api/tags`,{method:"GET"})).json()).models||[]).map(r=>r.name)}catch{return[]}}normalizeResponse(a){const t=a;return{id:`ollama-${Date.now()}`,model:t.model,choices:[{index:0,message:t.message,finishReason:t.done?"stop":null}],usage:{promptTokens:t.prompt_eval_count||0,completionTokens:t.eval_count||0,totalTokens:(t.prompt_eval_count||0)+(t.eval_count||0)},estimatedCost:0}}normalizeStreamChunk(a){var r;const t=a;return{id:`ollama-${Date.now()}`,choices:[{index:0,delta:{content:((r=t.message)==null?void 0:r.content)||""},finishReason:t.done?"stop":null}]}}async parseOllamaStream(a,t,r,n){var g;const s=(g=a.body)==null?void 0:g.getReader();if(!s){n==null||n(new Error("No response body"));return}const m=new TextDecoder;let c="";try{for(;;){const{done:f,value:j}=await s.read();if(f)break;c+=m.decode(j,{stream:!0});const w=c.split(`
18
- `);c=w.pop()||"";for(const N of w)if(N.trim())try{const S=JSON.parse(N);if(t(this.normalizeStreamChunk(S)),S.done){r==null||r();return}}catch{}}r==null||r()}catch(f){n==null||n(f)}finally{s.releaseLock()}}}class sa extends te{constructor(a){super(a),this.type="groq",this.name="Groq",this.baseUrl=a.baseUrl||"https://api.groq.com/openai/v1"}async chat(a){const r=await(await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama-3.1-70b-versatile",messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024})})).json();return this.normalizeResponse(r)}async chatStream(a,t,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify({model:a.model||this.config.model||"llama-3.1-70b-versatile",messages:a.messages,temperature:a.temperature??.7,max_tokens:a.maxTokens??1024,stream:!0})});await this.parseSSEStream(s,t,r,n)}catch(s){n==null||n(s)}}normalizeResponse(a){const t=a;return{id:t.id,model:t.model,choices:t.choices.map(r=>({index:r.index,message:r.message,finishReason:r.finish_reason})),usage:{promptTokens:t.usage.prompt_tokens,completionTokens:t.usage.completion_tokens,totalTokens:t.usage.total_tokens},estimatedCost:0}}normalizeStreamChunk(a){const t=a;return{id:t.id,choices:t.choices.map(r=>({index:r.index,delta:r.delta,finishReason:r.finish_reason}))}}}function ae(i){switch(i.type){case"openai":return new ta(i);case"anthropic":return new ia(i);case"azure-openai":return new ra(i);case"ollama":return new na(i);case"groq":return new sa(i);default:throw new Error(`Unsupported provider type: ${i.type}`)}}function G(i){const a=i.endpoint.toLowerCase();let t="custom";a.includes("openai.com")?t="openai":a.includes("anthropic.com")?t="anthropic":a.includes("azure.com")||a.includes("openai.azure.com")?t="azure-openai":a.includes("localhost:11434")||a.includes("ollama")?t="ollama":a.includes("groq.com")&&(t="groq");const r=new URL(i.endpoint),n=`${r.protocol}//${r.host}`;return ae({type:t,apiKey:i.apiKey,baseUrl:n,model:i.model,headers:i.headers})}function Z(i,a){for(const n of i.variables)if(n.required&&!(n.name in a)&&!n.default)throw new Error(`Missing required variable: ${n.name}`);const t={};for(const n of i.variables)t[n.name]=a[n.name]??n.default;const r=n=>n.replace(/\{\{(\w+)\}\}/g,(s,m)=>{const c=t[m];return c===void 0?`{{${m}}}`:typeof c=="object"?JSON.stringify(c,null,2):String(c)});return{system:r(i.system),user:r(i.user),metadata:{templateId:i.id,variables:t,timestamp:Date.now()}}}const re={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.
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:g.temperature,onChange:z=>d({...g,temperature:parseFloat(z.target.value)}),min:"0",max:"2",step:"0.1"})]}),e.jsxs("label",{children:["Top K",e.jsx("input",{type:"number",value:g.topK,onChange:z=>d({...g,topK:parseInt(z.target.value)}),min:"1",max:"100"})]}),e.jsxs("label",{children:["Top P",e.jsx("input",{type:"number",value:g.topP,onChange:z=>d({...g,topP:parseFloat(z.target.value)}),min:"0",max:"1",step:"0.05"})]}),e.jsxs("label",{children:["Threshold",e.jsx("input",{type:"number",value:g.threshold,onChange:z=>d({...g,threshold:parseFloat(z.target.value)}),min:"0",max:"1",step:"0.05"})]})]})]}),e.jsx("button",{className:"run-button",onClick:I,disabled:m||!w&&!k&&S==="{}",children:m?"Running...":"Run Inference"})]}),e.jsxs("div",{className:"output-section",children:[e.jsx("h3",{children:"Output"}),x&&e.jsxs("div",{className:"error-message",children:[e.jsx("span",{className:"error-icon",children:"⚠️"}),x]}),j&&e.jsxs("div",{className:"result-container",children:[e.jsxs("div",{className:"result-meta",children:[e.jsxs("span",{children:["Request ID: ",j.requestId]}),e.jsxs("span",{children:["Latency: ",J(j.latency)]}),e.jsxs("span",{children:["Model: ",j.modelVersion]})]}),e.jsx("div",{className:"predictions-list",children:j.predictions.map((z,F)=>V(z,F))})]}),!x&&!j&&e.jsxs("div",{className:"empty-output",children:[e.jsx("span",{className:"icon",children:"📤"}),e.jsx("p",{children:"Run inference to see results"})]})]})]}),o==="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 z=>{var U;const F=(U=z.target.files)==null?void 0:U[0];if(F){const W=await F.text();try{const q=JSON.parse(W);if(Array.isArray(q)){const Z=q.map(ee=>({type:"json",data:ee}));D(Z)}}catch{p("Invalid batch file format")}}},hidden:!0}),e.jsx("span",{className:"upload-icon",children:"📁"}),e.jsx("span",{children:"Upload JSON array file"})]})]}),R!==null&&e.jsxs("div",{className:"batch-progress",children:[e.jsx("div",{className:"progress-bar",children:e.jsx("div",{className:"progress-fill",style:{width:`${R}%`}})}),e.jsxs("span",{children:[Math.round(R),"%"]})]}),_.length>0&&e.jsxs("div",{className:"batch-results",children:[e.jsxs("h3",{children:["Results (",_.length,")"]}),e.jsx("div",{className:"results-list",children:_.map((z,F)=>e.jsxs("div",{className:"batch-result-item",children:[e.jsxs("span",{className:"result-index",children:["#",F+1]}),z.predictions.map((U,W)=>e.jsxs("span",{className:"result-prediction",children:[U.label,": ",(U.confidence||U.score||0*100).toFixed(1),"%"]},W))]},F))})]})]}),o==="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:J(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:J(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:J(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(z=>e.jsxs("div",{className:"histogram-bar",children:[e.jsx("div",{className:"bar-fill",style:{height:`${Math.min(100,s.metrics.latencyP50*z/100)}px`}}),e.jsxs("span",{className:"percentile-label",children:["P",z]})]},z))})]})]}),o==="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:()=>l(z=>({...z,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((z,F)=>e.jsxs("tr",{className:`log-row log-row--${z.status}`,children:[e.jsx("td",{children:Y(z.timestamp)}),e.jsx("td",{className:"request-id",children:z.requestId.slice(0,8)}),e.jsx("td",{children:J(z.duration)}),e.jsx("td",{children:e.jsx("span",{className:`status-badge status-badge--${z.status}`,children:z.status})}),e.jsxs("td",{children:[z.inputSize," B"]}),e.jsxs("td",{children:[z.outputSize," B"]})]},F))})]})})]})]})]})};class ne{constructor(a){this.abortController=null,this.config={timeout:3e4,maxRetries:3,retryDelay:1e3,...a}}async healthCheck(){try{return(await this.chat({messages:[{role:"user",content:"Hi"}],maxTokens:5})).choices.length>0}catch{return!1}}async fetchWithRetry(a,r,t=this.config.maxRetries){let n=null;for(let s=0;s<=t;s++)try{this.abortController=new AbortController;const l=setTimeout(()=>{var f;return(f=this.abortController)==null?void 0:f.abort()},this.config.timeout),o=await fetch(a,{...r,signal:this.abortController.signal});if(clearTimeout(l),o.ok)return o;if(o.status>=400&&o.status<500){const f=await o.text();throw new Error(`API Error ${o.status}: ${f}`)}n=new Error(`HTTP ${o.status}`)}catch(l){n=l,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 f;const s=(f=a.body)==null?void 0:f.getReader();if(!s){n==null||n(new Error("No response body"));return}const l=new TextDecoder;let o="";try{for(;;){const{done:h,value:y}=await s.read();if(h)break;o+=l.decode(y,{stream:!0});const w=o.split(`
42
+ `);o=w.pop()||"";for(const C of w)if(C.startsWith("data: ")){const S=C.slice(6).trim();if(S==="[DONE]"){t==null||t();return}try{const P=JSON.parse(S);r(this.normalizeStreamChunk(P))}catch{}}}t==null||t()}catch(h){n==null||n(h)}finally{s.releaseLock()}}}class fa extends ne{constructor(a){super(a),this.type="openai",this.name="OpenAI",this.baseUrl=a.baseUrl||"https://api.openai.com/v1"}async chat(a){const 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(o=>a.includes(o)),l=s?n[s]:n["gpt-4o-mini"];return r/1e6*l.input+t/1e6*l.output}}class ha extends ne{constructor(a){super(a),this.type="anthropic",this.name="Anthropic Claude",this.baseUrl=a.baseUrl||"https://api.anthropic.com/v1"}async chat(a){const 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 f;const s=(f=a.body)==null?void 0:f.getReader();if(!s){n==null||n(new Error("No response body"));return}const l=new TextDecoder;let o="";try{for(;;){const{done:h,value:y}=await s.read();if(h)break;o+=l.decode(y,{stream:!0});const w=o.split(`
43
+ `);o=w.pop()||"";for(const C of w)if(C.startsWith("data: "))try{const S=JSON.parse(C.slice(6));if(S.type==="content_block_delta")r(this.normalizeStreamChunk(S));else if(S.type==="message_stop"){t==null||t();return}}catch{}}t==null||t()}catch(h){n==null||n(h)}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(o=>a.includes(o)),l=s?n[s]:n["claude-3-5-sonnet"];return r/1e6*l.input+t/1e6*l.output}}class ga extends ne{constructor(a){if(super(a),this.type="azure-openai",this.name="Azure OpenAI",!a.baseUrl||!a.deployment)throw new Error("Azure OpenAI requires baseUrl and deployment")}async chat(a){const 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 l=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(l,r,t,n)}catch(l){n==null||n(l)}}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 ya extends ne{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 f;const s=(f=a.body)==null?void 0:f.getReader();if(!s){n==null||n(new Error("No response body"));return}const l=new TextDecoder;let o="";try{for(;;){const{done:h,value:y}=await s.read();if(h)break;o+=l.decode(y,{stream:!0});const w=o.split(`
44
+ `);o=w.pop()||"";for(const C of w)if(C.trim())try{const S=JSON.parse(C);if(r(this.normalizeStreamChunk(S)),S.done){t==null||t();return}}catch{}}t==null||t()}catch(h){n==null||n(h)}finally{s.releaseLock()}}}class ba extends ne{constructor(a){super(a),this.type="groq",this.name="Groq",this.baseUrl=a.baseUrl||"https://api.groq.com/openai/v1"}async chat(a){const 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 te(i){switch(i.type){case"openai":return new fa(i);case"anthropic":return new ha(i);case"azure-openai":return new ga(i);case"ollama":return new ya(i);case"groq":return new ba(i);default:throw new Error(`Unsupported provider type: ${i.type}`)}}function G(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 te({type:r,apiKey:i.apiKey,baseUrl:n,model:i.model,headers:i.headers})}function ae(i,a){for(const n of i.variables)if(n.required&&!(n.name in a)&&!n.default)throw new Error(`Missing required variable: ${n.name}`);const r={};for(const n of i.variables)r[n.name]=a[n.name]??n.default;const t=n=>n.replace(/\{\{(\w+)\}\}/g,(s,l)=>{const o=r[l];return o===void 0?`{{${l}}}`:typeof o=="object"?JSON.stringify(o,null,2):String(o)});return{system:t(i.system),user:t(i.user),metadata:{templateId:i.id,variables:r,timestamp:Date.now()}}}const ce={id:"data-grid-filter",name:"DataGrid Natural Language Filter",description:"Convert natural language queries to DataGrid filter configurations",category:"data-query",system:`You are a filter query generator for a data grid component.
19
45
  Given column definitions and a natural language query, generate a JSON filter configuration.
20
46
 
21
47
  Available filter operators:
@@ -48,7 +74,7 @@ Generate the filter configuration:`,variables:[{name:"columns",description:"JSON
48
74
  { "column": "city", "operator": "equals", "value": "New York" }
49
75
  ],
50
76
  "logic": "and"
51
- }`}],suggestedTemperature:.2,maxTokens:512},ne={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.
77
+ }`}],suggestedTemperature:.2,maxTokens:512},oe={id:"data-grid-sort",name:"DataGrid Natural Language Sort",description:"Convert natural language to sort configuration",category:"data-query",system:`You are a sort configuration generator for a data grid.
52
78
  Given columns and a natural language request, generate sort configuration.
53
79
 
54
80
  Output format:
@@ -66,7 +92,7 @@ Keywords mapping:
66
92
 
67
93
  Request: "{{query}}"
68
94
 
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},se={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.
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},le={id:"form-builder",name:"Form Generation from Description",description:"Generate form configuration from natural language description",category:"form-generation",system:`You are a form builder AI. Generate form configurations from descriptions.
70
96
 
71
97
  Available field types:
72
98
  - text, email, phone, url, password
@@ -116,7 +142,7 @@ Generate the form configuration:`,variables:[{name:"description",description:"Na
116
142
  { "id": "message", "type": "textarea", "label": "Message", "required": true }
117
143
  ],
118
144
  "layout": { "columns": 1 }
119
- }`}],suggestedTemperature:.5,maxTokens:2048},ce={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.
145
+ }`}],suggestedTemperature:.5,maxTokens:2048},de={id:"chart-config",name:"Chart Configuration Generator",description:"Generate chart configuration from data description",category:"chart-config",system:`You are a data visualization expert. Generate chart configurations from descriptions.
120
146
 
121
147
  Available chart types:
122
148
  - line, area, bar, column
@@ -156,14 +182,14 @@ Available data fields: {{data}}
156
182
  Context: {{context}}
157
183
  {{/if}}
158
184
 
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},oe={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.
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},ue={id:"code-completion",name:"Code Completion",description:"Complete code based on context",category:"code-completion",system:`You are an expert programmer. Complete the code based on context.
160
186
 
161
187
  Rules:
162
188
  - Match the existing code style
163
189
  - Use the same language features and patterns
164
190
  - Keep completions concise and focused
165
191
  - Do not repeat existing code
166
- - Only output the completion, not the full code`,user:"Language: {{language}}\n\nContext (code before cursor):\n```{{language}}\n{{prefix}}\n```\n\nContext (code after cursor):\n```{{language}}\n{{suffix}}\n```\n\nComplete the code at the cursor position:",variables:[{name:"language",description:"Programming language",required:!0,type:"string"},{name:"prefix",description:"Code before cursor",required:!0,type:"string"},{name:"suffix",description:"Code after cursor",required:!1,type:"string",default:""}],suggestedModel:"gpt-4o",suggestedTemperature:.2,maxTokens:512},le={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.
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},pe={id:"workflow-generator",name:"Workflow/BPMN Generator",description:"Generate workflow definition from process description",category:"workflow",system:`You are a business process expert. Generate workflow definitions from descriptions.
167
193
 
168
194
  Output BPMN-compatible JSON:
169
195
  {
@@ -205,7 +231,7 @@ Available roles: {{roles}}
205
231
  Systems involved: {{systems}}
206
232
  {{/if}}
207
233
 
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},de={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.
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},me={id:"report-layout",name:"Report Layout Generator",description:"Generate report layout from description",category:"report",system:`You are a report designer. Generate report layouts from descriptions.
209
235
 
210
236
  Available report elements:
211
237
  - header, footer
@@ -243,7 +269,7 @@ Output JSON:
243
269
  Available data sources: {{dataSources}}
244
270
  {{/if}}
245
271
 
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},ue={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.
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},fe={id:"theme-generator",name:"Theme Generator from Brand Colors",description:"Generate complete theme from brand colors",category:"theme",system:`You are a UI/UX designer specializing in design systems.
247
273
  Generate a complete theme from brand colors following accessibility guidelines.
248
274
 
249
275
  Rules:
@@ -283,7 +309,7 @@ Output JSON:
283
309
  {{#if industry}}Industry: {{industry}}{{/if}}
284
310
  {{#if style}}Style preference: {{style}}{{/if}}
285
311
 
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},ye={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).
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},je={id:"accessibility-checker",name:"Accessibility Checker",description:"Check and fix accessibility issues in HTML/JSX",category:"accessibility",system:`You are a web accessibility expert (WCAG 2.1 AA/AAA certified).
287
313
  Analyze code for accessibility issues and provide fixes.
288
314
 
289
315
  Check for:
@@ -310,7 +336,7 @@ Output JSON:
310
336
  ],
311
337
  "score": 0-100,
312
338
  "summary": "Brief summary of findings"
313
- }`,user:"Analyze this code for accessibility issues:\n\n```{{language}}\n{{code}}\n```\n\nReturn accessibility analysis:",variables:[{name:"code",description:"Code to analyze",required:!0,type:"string"},{name:"language",description:"Code language (html, jsx, tsx)",required:!1,type:"string",default:"jsx"}],suggestedTemperature:.2,maxTokens:2048},_e={id:"translation",name:"UI Translation",description:"Translate UI text maintaining context and formatting",category:"translation",system:`You are a professional UI translator.
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},ke={id:"translation",name:"UI Translation",description:"Translate UI text maintaining context and formatting",category:"translation",system:`You are a professional UI translator.
314
340
  Translate text while:
315
341
  - Preserving placeholders like {name}, {{count}}, %s
316
342
  - Maintaining ICU message format syntax
@@ -328,7 +354,7 @@ Output JSON:
328
354
 
329
355
  {{texts}}
330
356
 
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},we={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.
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},Ne={id:"summarize-data",name:"Data Summarization",description:"Summarize tabular data into insights",category:"summarization",system:`You are a data analyst. Summarize data into actionable insights.
332
358
 
333
359
  Provide:
334
360
  - Key statistics (min, max, mean, median)
@@ -352,7 +378,7 @@ Format output as structured JSON:
352
378
 
353
379
  {{#if context}}Context: {{context}}{{/if}}
354
380
 
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},he={[re.id]:re,[ne.id]:ne,[se.id]:se,[ce.id]:ce,[oe.id]:oe,[le.id]:le,[de.id]:de,[ue.id]:ue,[ye.id]:ye,[_e.id]:_e,[we.id]:we};function nt(i){return he[i]}function st(i){return Object.values(he).filter(a=>a.category===i)}function ct(){return Object.keys(he)}class Re{constructor(){this.records=new Map}async save(a,t){const r=this.records.get(a)||[];this.records.set(a,[...r,...t])}async load(a,t,r){const n=this.records.get(a)||[];return!t&&!r?n:n.filter(s=>!(t&&s.timestamp<t.getTime()||r&&s.timestamp>r.getTime()))}async clear(a,t){if(!t)this.records.delete(a);else{const r=this.records.get(a)||[];this.records.set(a,r.filter(n=>n.timestamp>=t.getTime()))}}}class ca{constructor(){this.prefix="nice2dev-ai-cost:"}async save(a,t){if(typeof window>"u")return;const r=`${this.prefix}${a}`,s=[...JSON.parse(localStorage.getItem(r)||"[]"),...t],m=Date.now()-30*24*60*60*1e3,c=s.filter(g=>g.timestamp>m);localStorage.setItem(r,JSON.stringify(c))}async load(a,t,r){if(typeof window>"u")return[];const n=`${this.prefix}${a}`,s=JSON.parse(localStorage.getItem(n)||"[]");return!t&&!r?s:s.filter(m=>!(t&&m.timestamp<t.getTime()||r&&m.timestamp>r.getTime()))}async clear(a,t){if(typeof window>"u")return;const r=`${this.prefix}${a}`;if(!t)localStorage.removeItem(r);else{const n=JSON.parse(localStorage.getItem(r)||"[]");localStorage.setItem(r,JSON.stringify(n.filter(s=>s.timestamp>=t.getTime())))}}}class oa{constructor(a,t){this.pendingRecords=[],this.flushTimer=null,this.alertCallbacks=[],this.minuteCounter=new Map,this.dayCounter=new Map,this.storage=a||new Re,this.budgetConfig={monthlyBudget:100,dailyBudget:10,maxTokensPerRequest:4096,maxRequestsPerMinute:30,maxRequestsPerDay:1e3,alertThresholds:[50,80,90,100],...t}}async recordUsage(a,t){const r={...t,id:this.generateId(),timestamp:Date.now()};this.pendingRecords.push(r),this.updateCounters(a),this.scheduleFlush(a);const n=await this.getBudgetStatus(a);this.checkAlerts(a,n)}async canMakeRequest(a){const t=await this.getBudgetStatus(a);return t.isOverBudget?{allowed:!1,reason:"Budget exceeded"}:this.budgetConfig.maxRequestsPerMinute&&t.requestsThisMinute>=this.budgetConfig.maxRequestsPerMinute?{allowed:!1,reason:"Rate limit exceeded (per minute)"}:this.budgetConfig.maxRequestsPerDay&&t.requestsToday>=this.budgetConfig.maxRequestsPerDay?{allowed:!1,reason:"Daily request limit exceeded"}:{allowed:!0}}async getBudgetStatus(a){const t=new Date,r=new Date(t.getFullYear(),t.getMonth(),t.getDate()),n=new Date(t.getFullYear(),t.getMonth(),1),s=await this.storage.load(a,r),m=await this.storage.load(a,n),c=s.reduce(($,k)=>$+k.estimatedCost,0),g=m.reduce(($,k)=>$+k.estimatedCost,0),f=this.budgetConfig.dailyBudget||1/0,j=this.budgetConfig.monthlyBudget||1/0,w=f?c/f*100:0,N=j?g/j*100:0,S=[];for(const $ of this.budgetConfig.alertThresholds||[])w>=$&&S.push(`Daily budget ${$}% used`),N>=$&&S.push(`Monthly budget ${$}% used`);return{dailyUsed:c,dailyRemaining:Math.max(0,f-c),dailyPercent:w,monthlyUsed:g,monthlyRemaining:Math.max(0,j-g),monthlyPercent:N,requestsToday:s.length,requestsThisMinute:this.getMinuteCount(a),isOverBudget:c>=f||g>=j,alerts:S}}async getUsageStats(a,t,r){const n=await this.storage.load(a,t,r),s={totalRequests:n.length,totalTokens:0,totalPromptTokens:0,totalCompletionTokens:0,totalCost:0,averageLatency:0,errorCount:0,cacheHitRate:0,byModel:{},byFeature:{},byDay:{}};let m=0,c=0;for(const g of n){s.totalTokens+=g.totalTokens,s.totalPromptTokens+=g.promptTokens,s.totalCompletionTokens+=g.completionTokens,s.totalCost+=g.estimatedCost,m+=g.latencyMs,g.error&&s.errorCount++,g.cached&&c++,s.byModel[g.model]||(s.byModel[g.model]={requests:0,tokens:0,cost:0}),s.byModel[g.model].requests++,s.byModel[g.model].tokens+=g.totalTokens,s.byModel[g.model].cost+=g.estimatedCost;const f=g.feature||"unknown";s.byFeature[f]||(s.byFeature[f]={requests:0,tokens:0,cost:0}),s.byFeature[f].requests++,s.byFeature[f].tokens+=g.totalTokens,s.byFeature[f].cost+=g.estimatedCost;const j=new Date(g.timestamp).toISOString().split("T")[0];s.byDay[j]||(s.byDay[j]={requests:0,tokens:0,cost:0}),s.byDay[j].requests++,s.byDay[j].tokens+=g.totalTokens,s.byDay[j].cost+=g.estimatedCost}return n.length>0&&(s.averageLatency=m/n.length,s.cacheHitRate=c/n.length),s}onAlert(a){return this.alertCallbacks.push(a),()=>{const t=this.alertCallbacks.indexOf(a);t>=0&&this.alertCallbacks.splice(t,1)}}setBudgetConfig(a){this.budgetConfig={...this.budgetConfig,...a}}async clearUsage(a,t){await this.storage.clear(a,t)}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}updateCounters(a){const t=Date.now(),r=t-6e4,n=this.minuteCounter.get(a)||[];n.push(t),this.minuteCounter.set(a,n.filter(c=>c>r));const s=new Date().toISOString().split("T")[0],m=`${a}:${s}`;this.dayCounter.set(m,(this.dayCounter.get(m)||0)+1)}getMinuteCount(a){const r=Date.now()-6e4;return(this.minuteCounter.get(a)||[]).filter(s=>s>r).length}scheduleFlush(a){this.flushTimer||(this.flushTimer=setTimeout(async()=>{this.flushTimer=null,this.pendingRecords.length>0&&(await this.storage.save(a,this.pendingRecords),this.pendingRecords=[])},1e3))}checkAlerts(a,t){if(t.alerts.length!==0)for(const r of t.alerts)for(const n of this.alertCallbacks)try{n(r,t)}catch{}}}function ot(i,a){const t=o.useRef(null),[r,n]=o.useState(null),[s,m]=o.useState(null),[c,g]=o.useState(!0);o.useEffect(()=>{const N=typeof window<"u"?new ca:new Re;t.current=new oa(N,a);const S=t.current.onAlert($=>{console.warn(`[AI Cost Alert] ${$}`)});return()=>{S()}},[]);const f=o.useCallback(async()=>{if(t.current){g(!0);try{const[N,S]=await Promise.all([t.current.getBudgetStatus(i),t.current.getUsageStats(i)]);n(N),m(S)}finally{g(!1)}}},[i]);o.useEffect(()=>{f()},[f]);const j=o.useCallback(async N=>{t.current&&(await t.current.recordUsage(i,N),await f())},[i,f]),w=o.useCallback(async()=>t.current?t.current.canMakeRequest(i):{allowed:!0},[i]);return{status:r,stats:s,loading:c,recordUsage:j,canMakeRequest:w,refresh:f}}class lt{constructor(a=100,t=36e5){this.cache=new Map,this.maxSize=a,this.ttl=t}hashRequest(a){const t=JSON.stringify({messages:a.messages,model:a.model,temperature:a.temperature});let r=0;for(let n=0;n<t.length;n++){const s=t.charCodeAt(n);r=(r<<5)-r+s,r=r&r}return r.toString(36)}get(a){const t=this.hashRequest(a),r=this.cache.get(t);return r?Date.now()-r.timestamp>this.ttl?(this.cache.delete(t),null):r.response:null}set(a,t){const r=this.hashRequest(a);if(this.cache.size>=this.maxSize){const n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(r,{request:r,response:t,timestamp:Date.now()})}clear(){this.cache.clear()}}class la{constructor(a,t){this.backupProviders=[],this.circuitBreakers=new Map,this.primaryProvider=a,this.config={strategies:["retry","failover","cache","graceful-degrade"],maxRetries:3,retryDelay:1e3,backoffMultiplier:2,backupProviders:[],cacheTTL:36e5,offlineConfig:void 0,circuitBreakerThreshold:5,circuitBreakerResetTime:6e4,onFallback:void 0,...t},this.cache=new lt(100,this.config.cacheTTL);for(const r of this.config.backupProviders||[])this.backupProviders.push(ae(r));this.config.offlineConfig&&(this.offlineProvider=ae(this.config.offlineConfig))}async chat(a){if(this.isCircuitOpen(this.primaryProvider.type))return this.executeWithFallback(a,new Error("Circuit breaker open"));try{const t=await this.primaryProvider.chat(a);return this.cache.set(a,t),this.resetCircuitBreaker(this.primaryProvider.type),t}catch(t){return this.recordFailure(this.primaryProvider.type),this.executeWithFallback(a,t)}}async executeWithFallback(a,t){var r,n;for(const s of this.config.strategies)try{const m=await this.executeStrategy(s,a,t);if(m)return(n=(r=this.config).onFallback)==null||n.call(r,s,t),m}catch{}throw new Error(`All fallback strategies failed. Original error: ${t.message}`)}async executeStrategy(a,t,r){switch(a){case"retry":return this.retryStrategy(t);case"failover":return this.failoverStrategy(t);case"cache":return this.cacheStrategy(t);case"offline":return this.offlineStrategy(t);case"graceful-degrade":return this.gracefulDegradeStrategy(t,r);case"circuit-breaker":return this.openCircuitBreaker(this.primaryProvider.type),null;default:return null}}async retryStrategy(a){let t=this.config.retryDelay;for(let r=0;r<this.config.maxRetries;r++){await this.delay(t);try{const n=await this.primaryProvider.chat(a);return this.cache.set(a,n),n}catch{t*=this.config.backoffMultiplier}}return null}async failoverStrategy(a){for(const t of this.backupProviders)if(!this.isCircuitOpen(t.type))try{const r=await t.chat(a);return this.cache.set(a,r),r}catch{this.recordFailure(t.type)}return null}cacheStrategy(a){const t=this.cache.get(a);return t?{...t,id:`cached-${t.id}`}:null}async offlineStrategy(a){if(!this.offlineProvider)return null;try{return await this.offlineProvider.chat(a)}catch{return null}}gracefulDegradeStrategy(a,t){const r=[...a.messages].reverse().find(n=>n.role==="user");return{id:`degraded-${Date.now()}`,model:"fallback",choices:[{index:0,message:{role:"assistant",content:this.generateDegradedResponse((r==null?void 0:r.content)||"",t)},finishReason:"stop"}],usage:{promptTokens:0,completionTokens:0,totalTokens:0}}}generateDegradedResponse(a,t){return a.toLowerCase().includes("filter")||a.toLowerCase().includes("show")?JSON.stringify({filters:[],logic:"and"}):a.toLowerCase().includes("form")||a.toLowerCase().includes("create")?JSON.stringify({title:"Form",fields:[{id:"field1",type:"text",label:"Field 1"}]}):a.toLowerCase().includes("chart")||a.toLowerCase().includes("graph")?JSON.stringify({type:"bar",title:"Chart",data:{source:"data"}}):`I'm sorry, I couldn't process your request at this time. The service is temporarily unavailable. Please try again later or contact support. (Error: ${t.message.substring(0,50)})`}isCircuitOpen(a){const t=this.circuitBreakers.get(a);return t&&t.isOpen?Date.now()-t.lastFailure>this.config.circuitBreakerResetTime?(this.resetCircuitBreaker(a),!1):!0:!1}recordFailure(a){const t=this.circuitBreakers.get(a)||{failures:0,lastFailure:0,isOpen:!1};t.failures++,t.lastFailure=Date.now(),t.failures>=this.config.circuitBreakerThreshold&&(t.isOpen=!0),this.circuitBreakers.set(a,t)}openCircuitBreaker(a){this.circuitBreakers.set(a,{failures:this.config.circuitBreakerThreshold,lastFailure:Date.now(),isOpen:!0})}resetCircuitBreaker(a){this.circuitBreakers.delete(a)}delay(a){return new Promise(t=>setTimeout(t,a))}addBackupProvider(a){this.backupProviders.push(a)}setOfflineProvider(a){this.offlineProvider=a}clearCache(){this.cache.clear()}resetAllCircuitBreakers(){this.circuitBreakers.clear()}getCircuitBreakerStatus(){const a={};for(const[t,r]of this.circuitBreakers)a[t]={...r};return a}async healthCheck(){const a={};a[this.primaryProvider.type]=await this.primaryProvider.healthCheck();for(const t of this.backupProviders)a[`backup-${t.type}`]=await t.healthCheck();return this.offlineProvider&&(a.offline=await this.offlineProvider.healthCheck()),a}}function da(i,a){const t=ae(i);return new la(t,a)}function dt(i,a){const t={strategies:["retry","failover","cache","graceful-degrade"],maxRetries:3,retryDelay:1e3,backoffMultiplier:2,backupProviders:a?[a]:[],circuitBreakerThreshold:5,circuitBreakerResetTime:6e4};return typeof window>"u"&&(t.offlineConfig={type:"ollama",model:"llama3"}),da(i,t)}function ua(i){const{columns:a,config:t,onFilterGenerated:r,onSortGenerated:n,onError:s}=i,m=X(),[c,g]=o.useState(!1),[f,j]=o.useState(null),[w,N]=o.useState(null),[S,$]=o.useState([]),k=o.useRef(null),P=t||(m==null?void 0:m.config),h=o.useMemo(()=>a.map(p=>({id:p.id,label:p.label,type:p.type,...p.options?{options:p.options}:{}})),[a]),d=o.useCallback(async p=>{var b;if(!P){const u="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(u),{type:"filter",error:u}}g(!0),j(p);const _=performance.now();(b=k.current)==null||b.abort(),k.current=new AbortController;try{const u=G(P),y=p.toLowerCase(),A=y.includes("sort")||y.includes("order")||y.includes("arrange")||y.includes("by highest")||y.includes("by lowest"),R=y.includes("show")||y.includes("find")||y.includes("filter")||y.includes("where")||y.includes("with")||y.includes("only")||!A,l={type:"combined"};if(R){const x=Z(re,{columns:h,query:p}),M=await u.chat({messages:[{role:"system",content:x.system},{role:"user",content:x.user}],temperature:.2,maxTokens:512}),z=ut(M);z&&(l.filterConfig=z,l.type="filter",r==null||r(z))}if(A){const x=Z(ne,{columns:h,query:p}),M=await u.chat({messages:[{role:"system",content:x.system},{role:"user",content:x.user}],temperature:.1,maxTokens:256}),z=pt(M);z&&(l.sortConfig=z,l.type=l.filterConfig?"combined":"sort",n==null||n(z))}return l.latencyMs=performance.now()-_,N(l),$(x=>[...x.slice(-9),{query:p,result:l}]),l}catch(u){const y=u instanceof Error?u.message:"AI request failed",A={type:"filter",error:y,latencyMs:performance.now()-_};return N(A),s==null||s(y),A}finally{g(!1)}},[P,h,r,n,s]),v=o.useCallback(()=>{j(null),N(null)},[]),C=o.useCallback(()=>{var p;(p=k.current)==null||p.abort(),g(!1)},[]);return o.useEffect(()=>()=>{var p;(p=k.current)==null||p.abort()},[]),{processQuery:d,loading:c,lastQuery:f,lastResult:w,history:S,clearResults:v,abort:C,isConfigured:!!P}}function ut(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.content)||"",m=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(m);if(c.filters&&Array.isArray(c.filters))return{filters:c.filters,logic:c.logic||"and",confidence:c.confidence,explanation:c.explanation}}catch{}return null}function pt(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.content)||"",m=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(m);if(c.sort&&Array.isArray(c.sort))return{sort:c.sort,confidence:c.confidence}}catch{}return null}function mt({columns:i,config:a,onFilter:t,onSort:r,placeholder:n='Ask AI to filter or sort data... (e.g., "show orders from last week")',showHistory:s=!0,showSuggestions:m=!0,className:c,style:g}){const[f,j]=o.useState(""),[w,N]=o.useState(!1),S=o.useRef(null),{processQuery:$,loading:k,lastResult:P,history:h,isConfigured:d}=ua({columns:i,config:a,onFilterGenerated:t,onSortGenerated:r}),v=o.useMemo(()=>{if(!m||i.length===0)return[];const u=[],y=i.filter(x=>x.type==="string");y.length>0&&u.push(`Show ${y[0].label}s containing "example"`);const A=i.filter(x=>x.type==="number");A.length>0&&(u.push(`${A[0].label} greater than 100`),u.push(`Sort by highest ${A[0].label}`));const R=i.filter(x=>x.type==="date");R.length>0&&(u.push(`${R[0].label} in the last 7 days`),u.push(`Sort by newest ${R[0].label}`));const l=i.filter(x=>{var M;return x.type==="enum"&&((M=x.options)==null?void 0:M.length)});return l.length>0&&l[0].options&&u.push(`Where ${l[0].label} is ${l[0].options[0]}`),u.slice(0,5)},[i,m]),C=async()=>{!f.trim()||k||(await $(f.trim()),N(!1))},p=u=>{u.key==="Enter"?(u.preventDefault(),C()):u.key==="Escape"&&N(!1)},_=u=>{var y;j(u),N(!1),(y=S.current)==null||y.focus()},b=u=>{j(u),N(!1),$(u)};return d?e.jsxs("div",{className:`nice-datagrid-ai ${c||""}`,style:g,children:[e.jsxs("div",{className:"nice-datagrid-ai__input-wrapper",children:[e.jsx("span",{className:"nice-datagrid-ai__icon",children:e.jsx("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor",children:e.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.94-.49-7-3.85-7-7.93s3.05-7.44 7-7.93v15.86zm2-15.86c1.03.13 2 .45 2.87.93H13v-.93zM13 7h5.24c.25.31.48.65.68 1H13V7zm0 3h6.74c.08.33.15.66.19 1H13v-1zm0 9.93V19h2.87c-.87.48-1.84.8-2.87.93zM18.24 17H13v-1h5.92c-.2.35-.43.69-.68 1zm1.5-3H13v-1h6.93c-.04.34-.11.67-.19 1z"})})}),e.jsx("input",{ref:S,type:"text",value:f,onChange:u=>j(u.target.value),onKeyDown:p,onFocus:()=>N(!0),onBlur:()=>setTimeout(()=>N(!1),200),placeholder:n,className:"nice-datagrid-ai__input",disabled:k,"aria-label":"AI query input"}),k?e.jsx("span",{className:"nice-datagrid-ai__spinner"}):e.jsx("button",{type:"button",onClick:C,className:"nice-datagrid-ai__submit",disabled:!f.trim(),"aria-label":"Submit query",children:e.jsx("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor",children:e.jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})})})]}),w&&(v.length>0||s&&h.length>0)&&e.jsxs("div",{className:"nice-datagrid-ai__dropdown",children:[m&&v.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:"Suggestions"}),v.map((u,y)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>_(u),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:"💡"}),u]},y))]}),s&&h.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:"Recent"}),h.slice(-5).reverse().map((u,y)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>b(u.query),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:"🕐"}),u.query,u.result.error&&e.jsx("span",{className:"nice-datagrid-ai__item-error",children:"⚠️"})]},y))]})]}),P&&!P.error&&e.jsxs("div",{className:"nice-datagrid-ai__result",children:[P.filterConfig&&e.jsxs("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--filter",children:[P.filterConfig.filters.length," filter",P.filterConfig.filters.length!==1?"s":""," applied"]}),P.sortConfig&&e.jsxs("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--sort",children:["Sorted by ",P.sortConfig.sort.map(u=>u.column).join(", ")]}),P.latencyMs&&e.jsxs("span",{className:"nice-datagrid-ai__latency",children:[Math.round(P.latencyMs),"ms"]})]}),(P==null?void 0:P.error)&&e.jsx("div",{className:"nice-datagrid-ai__error",children:P.error}),e.jsx("style",{children:`
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},ye={[ce.id]:ce,[oe.id]:oe,[le.id]:le,[de.id]:de,[ue.id]:ue,[pe.id]:pe,[me.id]:me,[fe.id]:fe,[je.id]:je,[ke.id]:ke,[Ne.id]:Ne};function zr(i){return ye[i]}function Lr(i){return Object.values(ye).filter(a=>a.category===i)}function Or(){return Object.keys(ye)}class Ie{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 xa{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],l=Date.now()-30*24*60*60*1e3,o=s.filter(f=>f.timestamp>l);localStorage.setItem(t,JSON.stringify(o))}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(l=>!(r&&l.timestamp<r.getTime()||t&&l.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 va{constructor(a,r){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],...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),l=await this.storage.load(a,n),o=s.reduce((P,k)=>P+k.estimatedCost,0),f=l.reduce((P,k)=>P+k.estimatedCost,0),h=this.budgetConfig.dailyBudget||1/0,y=this.budgetConfig.monthlyBudget||1/0,w=h?o/h*100:0,C=y?f/y*100:0,S=[];for(const P of this.budgetConfig.alertThresholds||[])w>=P&&S.push(`Daily budget ${P}% used`),C>=P&&S.push(`Monthly budget ${P}% used`);return{dailyUsed:o,dailyRemaining:Math.max(0,h-o),dailyPercent:w,monthlyUsed:f,monthlyRemaining:Math.max(0,y-f),monthlyPercent:C,requestsToday:s.length,requestsThisMinute:this.getMinuteCount(a),isOverBudget:o>=h||f>=y,alerts:S}}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 l=0,o=0;for(const f of n){s.totalTokens+=f.totalTokens,s.totalPromptTokens+=f.promptTokens,s.totalCompletionTokens+=f.completionTokens,s.totalCost+=f.estimatedCost,l+=f.latencyMs,f.error&&s.errorCount++,f.cached&&o++,s.byModel[f.model]||(s.byModel[f.model]={requests:0,tokens:0,cost:0}),s.byModel[f.model].requests++,s.byModel[f.model].tokens+=f.totalTokens,s.byModel[f.model].cost+=f.estimatedCost;const h=f.feature||"unknown";s.byFeature[h]||(s.byFeature[h]={requests:0,tokens:0,cost:0}),s.byFeature[h].requests++,s.byFeature[h].tokens+=f.totalTokens,s.byFeature[h].cost+=f.estimatedCost;const y=new Date(f.timestamp).toISOString().split("T")[0];s.byDay[y]||(s.byDay[y]={requests:0,tokens:0,cost:0}),s.byDay[y].requests++,s.byDay[y].tokens+=f.totalTokens,s.byDay[y].cost+=f.estimatedCost}return n.length>0&&(s.averageLatency=l/n.length,s.cacheHitRate=o/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(o=>o>t));const s=new Date().toISOString().split("T")[0],l=`${a}:${s}`;this.dayCounter.set(l,(this.dayCounter.get(l)||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 Er(i,a){const r=c.useRef(null),[t,n]=c.useState(null),[s,l]=c.useState(null),[o,f]=c.useState(!0);c.useEffect(()=>{const C=typeof window<"u"?new xa:new Ie;r.current=new va(C,a);const S=r.current.onAlert(P=>{console.warn(`[AI Cost Alert] ${P}`)});return()=>{S()}},[]);const h=c.useCallback(async()=>{if(r.current){f(!0);try{const[C,S]=await Promise.all([r.current.getBudgetStatus(i),r.current.getUsageStats(i)]);n(C),l(S)}finally{f(!1)}}},[i]);c.useEffect(()=>{h()},[h]);const y=c.useCallback(async C=>{r.current&&(await r.current.recordUsage(i,C),await h())},[i,h]),w=c.useCallback(async()=>r.current?r.current.canMakeRequest(i):{allowed:!0},[i]);return{status:t,stats:s,loading:o,recordUsage:y,canMakeRequest:w,refresh:h}}class Dr{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 _a{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 Dr(100,this.config.cacheTTL);for(const t of this.config.backupProviders||[])this.backupProviders.push(te(t));this.config.offlineConfig&&(this.offlineProvider=te(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 l=await this.executeStrategy(s,a,r);if(l)return(n=(t=this.config).onFallback)==null||n.call(t,s,r),l}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 wa(i,a){const r=te(i);return new _a(r,a)}function Hr(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"}),wa(i,r)}function ja(i){const{columns:a,config:r,onFilterGenerated:t,onSortGenerated:n,onError:s}=i,l=Q(),[o,f]=c.useState(!1),[h,y]=c.useState(null),[w,C]=c.useState(null),[S,P]=c.useState([]),k=c.useRef(null),$=r||(l==null?void 0:l.config),g=c.useMemo(()=>a.map(m=>({id:m.id,label:m.label,type:m.type,...m.options?{options:m.options}:{}})),[a]),d=c.useCallback(async m=>{var x;if(!$){const p="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(p),{type:"filter",error:p}}f(!0),y(m);const v=performance.now();(x=k.current)==null||x.abort(),k.current=new AbortController;try{const p=G($),_=m.toLowerCase(),M=_.includes("sort")||_.includes("order")||_.includes("arrange")||_.includes("by highest")||_.includes("by lowest"),R=_.includes("show")||_.includes("find")||_.includes("filter")||_.includes("where")||_.includes("with")||_.includes("only")||!M,T={type:"combined"};if(R){const u=ae(ce,{columns:g,query:m}),b=await p.chat({messages:[{role:"system",content:u.system},{role:"user",content:u.user}],temperature:.2,maxTokens:512}),I=Br(b);I&&(T.filterConfig=I,T.type="filter",t==null||t(I))}if(M){const u=ae(oe,{columns:g,query:m}),b=await p.chat({messages:[{role:"system",content:u.system},{role:"user",content:u.user}],temperature:.1,maxTokens:256}),I=Fr(b);I&&(T.sortConfig=I,T.type=T.filterConfig?"combined":"sort",n==null||n(I))}return T.latencyMs=performance.now()-v,C(T),P(u=>[...u.slice(-9),{query:m,result:T}]),T}catch(p){const _=p instanceof Error?p.message:"AI request failed",M={type:"filter",error:_,latencyMs:performance.now()-v};return C(M),s==null||s(_),M}finally{f(!1)}},[$,g,t,n,s]),j=c.useCallback(()=>{y(null),C(null)},[]),N=c.useCallback(()=>{var m;(m=k.current)==null||m.abort(),f(!1)},[]);return c.useEffect(()=>()=>{var m;(m=k.current)==null||m.abort()},[]),{processQuery:d,loading:o,lastQuery:h,lastResult:w,history:S,clearResults:j,abort:N,isConfigured:!!$}}function Br(i){var a,r,t;try{const n=((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"",l=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,o=JSON.parse(l);if(o.filters&&Array.isArray(o.filters))return{filters:o.filters,logic:o.logic||"and",confidence:o.confidence,explanation:o.explanation}}catch{}return null}function Fr(i){var a,r,t;try{const n=((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"",l=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,o=JSON.parse(l);if(o.sort&&Array.isArray(o.sort))return{sort:o.sort,confidence:o.confidence}}catch{}return null}function Jr({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:l=!0,className:o,style:f}){const[h,y]=c.useState(""),[w,C]=c.useState(!1),S=c.useRef(null),{processQuery:P,loading:k,lastResult:$,history:g,isConfigured:d}=ja({columns:i,config:a,onFilterGenerated:r,onSortGenerated:t}),j=c.useMemo(()=>{if(!l||i.length===0)return[];const p=[],_=i.filter(u=>u.type==="string");_.length>0&&p.push(`Show ${_[0].label}s containing "example"`);const M=i.filter(u=>u.type==="number");M.length>0&&(p.push(`${M[0].label} greater than 100`),p.push(`Sort by highest ${M[0].label}`));const R=i.filter(u=>u.type==="date");R.length>0&&(p.push(`${R[0].label} in the last 7 days`),p.push(`Sort by newest ${R[0].label}`));const T=i.filter(u=>{var b;return u.type==="enum"&&((b=u.options)==null?void 0:b.length)});return T.length>0&&T[0].options&&p.push(`Where ${T[0].label} is ${T[0].options[0]}`),p.slice(0,5)},[i,l]),N=async()=>{!h.trim()||k||(await P(h.trim()),C(!1))},m=p=>{p.key==="Enter"?(p.preventDefault(),N()):p.key==="Escape"&&C(!1)},v=p=>{var _;y(p),C(!1),(_=S.current)==null||_.focus()},x=p=>{y(p),C(!1),P(p)};return d?e.jsxs("div",{className:`nice-datagrid-ai ${o||""}`,style:f,children:[e.jsxs("div",{className:"nice-datagrid-ai__input-wrapper",children:[e.jsx("span",{className:"nice-datagrid-ai__icon",children:e.jsx("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor",children:e.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.94-.49-7-3.85-7-7.93s3.05-7.44 7-7.93v15.86zm2-15.86c1.03.13 2 .45 2.87.93H13v-.93zM13 7h5.24c.25.31.48.65.68 1H13V7zm0 3h6.74c.08.33.15.66.19 1H13v-1zm0 9.93V19h2.87c-.87.48-1.84.8-2.87.93zM18.24 17H13v-1h5.92c-.2.35-.43.69-.68 1zm1.5-3H13v-1h6.93c-.04.34-.11.67-.19 1z"})})}),e.jsx("input",{ref:S,type:"text",value:h,onChange:p=>y(p.target.value),onKeyDown:m,onFocus:()=>C(!0),onBlur:()=>setTimeout(()=>C(!1),200),placeholder:n,className:"nice-datagrid-ai__input",disabled:k,"aria-label":"AI query input"}),k?e.jsx("span",{className:"nice-datagrid-ai__spinner"}):e.jsx("button",{type:"button",onClick:N,className:"nice-datagrid-ai__submit",disabled:!h.trim(),"aria-label":"Submit query",children:e.jsx("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor",children:e.jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})})})]}),w&&(j.length>0||s&&g.length>0)&&e.jsxs("div",{className:"nice-datagrid-ai__dropdown",children:[l&&j.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:"Suggestions"}),j.map((p,_)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>v(p),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:"💡"}),p]},_))]}),s&&g.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:"Recent"}),g.slice(-5).reverse().map((p,_)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>x(p.query),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:"🕐"}),p.query,p.result.error&&e.jsx("span",{className:"nice-datagrid-ai__item-error",children:"⚠️"})]},_))]})]}),$&&!$.error&&e.jsxs("div",{className:"nice-datagrid-ai__result",children:[$.filterConfig&&e.jsxs("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--filter",children:[$.filterConfig.filters.length," filter",$.filterConfig.filters.length!==1?"s":""," applied"]}),$.sortConfig&&e.jsxs("span",{className:"nice-datagrid-ai__badge nice-datagrid-ai__badge--sort",children:["Sorted by ",$.sortConfig.sort.map(p=>p.column).join(", ")]}),$.latencyMs&&e.jsxs("span",{className:"nice-datagrid-ai__latency",children:[Math.round($.latencyMs),"ms"]})]}),($==null?void 0:$.error)&&e.jsx("div",{className:"nice-datagrid-ai__error",children:$.error}),e.jsx("style",{children:`
356
382
  .nice-datagrid-ai {
357
383
  position: relative;
358
384
  font-family: var(--nice-font-family, system-ui, sans-serif);
@@ -534,13 +560,13 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
534
560
  border-radius: var(--nice-radius-sm, 4px);
535
561
  font-size: 13px;
536
562
  }
537
- `})]}):e.jsx("div",{className:`nice-datagrid-ai nice-datagrid-ai--disabled ${c||""}`,style:g,children:e.jsx("input",{type:"text",placeholder:"AI not configured",disabled:!0,className:"nice-datagrid-ai__input"})})}function pa(i={}){const{config:a,schema:t,context:r,onFormGenerated:n,onError:s}=i,m=X(),[c,g]=o.useState(!1),[f,j]=o.useState(null),[w,N]=o.useState(null),[S,$]=o.useState([]),k=o.useRef(null),P=a||(m==null?void 0:m.config),h=o.useCallback(async p=>{var b,u,y;if(!P){const A="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(A),{error:A}}g(!0),j(p);const _=performance.now();(b=k.current)==null||b.abort(),k.current=new AbortController;try{const A=G(P),R=Z(se,{description:p,schema:t?JSON.stringify(t,null,2):void 0,context:r}),l=await A.chat({messages:[{role:"system",content:R.system},{role:"user",content:R.user}],temperature:.5,maxTokens:2048}),x=ht(l),M={config:x||void 0,rawResponse:(y=(u=l.choices[0])==null?void 0:u.message)==null?void 0:y.content,latencyMs:performance.now()-_,error:x?void 0:"Failed to parse form configuration"};return x&&(n==null||n(x)),N(M),$(z=>[...z.slice(-9),{description:p,result:M}]),M}catch(A){const R=A instanceof Error?A.message:"AI request failed",l={error:R,latencyMs:performance.now()-_};return N(l),s==null||s(R),l}finally{g(!1)}},[P,t,r,n,s]),d=o.useCallback(async p=>{if(!(w!=null&&w.config))return{error:"No form to refine. Generate a form first."};const _=`
563
+ `})]}):e.jsx("div",{className:`nice-datagrid-ai nice-datagrid-ai--disabled ${o||""}`,style:f,children:e.jsx("input",{type:"text",placeholder:"AI not configured",disabled:!0,className:"nice-datagrid-ai__input"})})}function ka(i={}){const{config:a,schema:r,context:t,onFormGenerated:n,onError:s}=i,l=Q(),[o,f]=c.useState(!1),[h,y]=c.useState(null),[w,C]=c.useState(null),[S,P]=c.useState([]),k=c.useRef(null),$=a||(l==null?void 0:l.config),g=c.useCallback(async m=>{var x,p,_;if(!$){const M="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(M),{error:M}}f(!0),y(m);const v=performance.now();(x=k.current)==null||x.abort(),k.current=new AbortController;try{const M=G($),R=ae(le,{description:m,schema:r?JSON.stringify(r,null,2):void 0,context:t}),T=await M.chat({messages:[{role:"system",content:R.system},{role:"user",content:R.user}],temperature:.5,maxTokens:2048}),u=Ur(T),b={config:u||void 0,rawResponse:(_=(p=T.choices[0])==null?void 0:p.message)==null?void 0:_.content,latencyMs:performance.now()-v,error:u?void 0:"Failed to parse form configuration"};return u&&(n==null||n(u)),C(b),P(I=>[...I.slice(-9),{description:m,result:b}]),b}catch(M){const R=M instanceof Error?M.message:"AI request failed",T={error:R,latencyMs:performance.now()-v};return C(T),s==null||s(R),T}finally{f(!1)}},[$,r,t,n,s]),d=c.useCallback(async m=>{if(!(w!=null&&w.config))return{error:"No form to refine. Generate a form first."};const v=`
538
564
  Modify this existing form based on the following instructions:
539
565
 
540
566
  Current form: ${JSON.stringify(w.config,null,2)}
541
567
 
542
- Instructions: ${p}
543
- `;return h(_)},[w,h]),v=o.useCallback(()=>{j(null),N(null)},[]),C=o.useCallback(()=>{var p;(p=k.current)==null||p.abort(),g(!1)},[]);return o.useEffect(()=>()=>{var p;(p=k.current)==null||p.abort()},[]),{generateForm:h,refineForm:d,loading:c,lastDescription:f,lastResult:w,history:S,clearResults:v,abort:C,isConfigured:!!P}}function ht(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.content)||"",m=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(m);if(c.fields&&Array.isArray(c.fields))return{title:c.title,description:c.description,fields:c.fields,layout:c.layout,submitLabel:c.submitLabel,validation:c.validation}}catch{}return null}function gt({config:i,schema:a,context:t,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:m=!0,className:c,style:g,renderForm:f}){const[j,w]=o.useState(""),[N,S]=o.useState(!1),$=o.useRef(null),{generateForm:k,loading:P,lastResult:h,isConfigured:d}=pa({config:i,schema:a,context:t,onFormGenerated:r}),v=["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"],C=async()=>{!j.trim()||P||await k(j.trim())},p=u=>{var y;w(u),S(!1),(y=$.current)==null||y.focus()},_=u=>{u.key==="Enter"&&(u.ctrlKey||u.metaKey)&&(u.preventDefault(),C())},b=u=>{w(u.target.value),u.target.style.height="auto",u.target.style.height=Math.min(u.target.scrollHeight,200)+"px"};return d?e.jsxs("div",{className:`nice-form-builder-ai ${c||""}`,style:g,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:"✨"}),"Describe your form"]}),e.jsxs("div",{className:"nice-form-builder-ai__input-wrapper",children:[e.jsx("textarea",{ref:$,value:j,onChange:b,onKeyDown:_,placeholder:n,className:"nice-form-builder-ai__textarea",disabled:P,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:v.map((u,y)=>e.jsx("button",{type:"button",className:"nice-form-builder-ai__dropdown-item",onClick:()=>p(u),children:u},y))})]}),e.jsx("button",{type:"button",onClick:C,disabled:!j.trim()||P,className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--primary",children:P?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"nice-form-builder-ai__spinner"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"🚀"}),"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"]})]}),h&&e.jsx("div",{className:"nice-form-builder-ai__result",children:h.error?e.jsxs("div",{className:"nice-form-builder-ai__error",children:[e.jsx("strong",{children:"Error:"})," ",h.error]}):h.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: ",h.config.title||"Untitled"]}),h.latencyMs&&e.jsxs("span",{className:"nice-form-builder-ai__latency",children:[Math.round(h.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(h.config),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--success",children:"Use This Form"})]}),h.config.description&&e.jsx("p",{className:"nice-form-builder-ai__result-description",children:h.config.description}),m&&e.jsx("div",{className:"nice-form-builder-ai__preview",children:f?f(h.config):e.jsx(ft,{config:h.config})}),e.jsxs("details",{className:"nice-form-builder-ai__json",children:[e.jsx("summary",{children:"View JSON Configuration"}),e.jsx("pre",{children:JSON.stringify(h.config,null,2)})]})]})}),e.jsx("style",{children:`
568
+ Instructions: ${m}
569
+ `;return g(v)},[w,g]),j=c.useCallback(()=>{y(null),C(null)},[]),N=c.useCallback(()=>{var m;(m=k.current)==null||m.abort(),f(!1)},[]);return c.useEffect(()=>()=>{var m;(m=k.current)==null||m.abort()},[]),{generateForm:g,refineForm:d,loading:o,lastDescription:h,lastResult:w,history:S,clearResults:j,abort:N,isConfigured:!!$}}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)||"",l=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,o=JSON.parse(l);if(o.fields&&Array.isArray(o.fields))return{title:o.title,description:o.description,fields:o.fields,layout:o.layout,submitLabel:o.submitLabel,validation:o.validation}}catch{}return null}function qr({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:l=!0,className:o,style:f,renderForm:h}){const[y,w]=c.useState(""),[C,S]=c.useState(!1),P=c.useRef(null),{generateForm:k,loading:$,lastResult:g,isConfigured:d}=ka({config:i,schema:a,context:r,onFormGenerated:t}),j=["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"],N=async()=>{!y.trim()||$||await k(y.trim())},m=p=>{var _;w(p),S(!1),(_=P.current)==null||_.focus()},v=p=>{p.key==="Enter"&&(p.ctrlKey||p.metaKey)&&(p.preventDefault(),N())},x=p=>{w(p.target.value),p.target.style.height="auto",p.target.style.height=Math.min(p.target.scrollHeight,200)+"px"};return d?e.jsxs("div",{className:`nice-form-builder-ai ${o||""}`,style:f,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:"✨"}),"Describe your form"]}),e.jsxs("div",{className:"nice-form-builder-ai__input-wrapper",children:[e.jsx("textarea",{ref:P,value:y,onChange:x,onKeyDown:v,placeholder:n,className:"nice-form-builder-ai__textarea",disabled:$,rows:2}),e.jsxs("div",{className:"nice-form-builder-ai__actions",children:[s&&e.jsxs("div",{className:"nice-form-builder-ai__examples-wrapper",children:[e.jsx("button",{type:"button",onClick:()=>S(!C),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--secondary",children:"Examples"}),C&&e.jsx("div",{className:"nice-form-builder-ai__dropdown",children:j.map((p,_)=>e.jsx("button",{type:"button",className:"nice-form-builder-ai__dropdown-item",onClick:()=>m(p),children:p},_))})]}),e.jsx("button",{type:"button",onClick:N,disabled:!y.trim()||$,className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--primary",children:$?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"nice-form-builder-ai__spinner"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"🚀"}),"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"]})]}),g&&e.jsx("div",{className:"nice-form-builder-ai__result",children:g.error?e.jsxs("div",{className:"nice-form-builder-ai__error",children:[e.jsx("strong",{children:"Error:"})," ",g.error]}):g.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: ",g.config.title||"Untitled"]}),g.latencyMs&&e.jsxs("span",{className:"nice-form-builder-ai__latency",children:[Math.round(g.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>t==null?void 0:t(g.config),className:"nice-form-builder-ai__btn nice-form-builder-ai__btn--success",children:"Use This Form"})]}),g.config.description&&e.jsx("p",{className:"nice-form-builder-ai__result-description",children:g.config.description}),l&&e.jsx("div",{className:"nice-form-builder-ai__preview",children:h?h(g.config):e.jsx(Wr,{config:g.config})}),e.jsxs("details",{className:"nice-form-builder-ai__json",children:[e.jsx("summary",{children:"View JSON Configuration"}),e.jsx("pre",{children:JSON.stringify(g.config,null,2)})]})]})}),e.jsx("style",{children:`
544
570
  .nice-form-builder-ai {
545
571
  font-family: var(--nice-font-family, system-ui, sans-serif);
546
572
  }
@@ -761,7 +787,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
761
787
  color: var(--nice-error, #c62828);
762
788
  border-radius: var(--nice-radius-md, 6px);
763
789
  }
764
- `})]}):e.jsx("div",{className:`nice-form-builder-ai nice-form-builder-ai--disabled ${c||""}`,style:g,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function ft({config:i}){var r,n;const a=s=>{var c,g;const m={id:s.id,placeholder:s.placeholder,required:s.required,disabled:!0};switch(s.type){case"textarea":case"richtext":case"markdown":return e.jsx("textarea",{...m,rows:3,className:"nice-form-preview__input nice-form-preview__textarea"});case"select":case"multiselect":return e.jsxs("select",{...m,className:"nice-form-preview__input nice-form-preview__select",children:[e.jsxs("option",{value:"",children:["Select ",s.label,"..."]}),(c=s.options)==null?void 0:c.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:(g=s.options)==null?void 0:g.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",...m,className:"nice-form-preview__input"});case"date":return e.jsx("input",{type:"date",...m,className:"nice-form-preview__input"});case"time":return e.jsx("input",{type:"time",...m,className:"nice-form-preview__input"});case"datetime":return e.jsx("input",{type:"datetime-local",...m,className:"nice-form-preview__input"});case"number":case"currency":case"percentage":return e.jsx("input",{type:"number",...m,className:"nice-form-preview__input"});case"email":return e.jsx("input",{type:"email",...m,className:"nice-form-preview__input"});case"phone":return e.jsx("input",{type:"tel",...m,className:"nice-form-preview__input"});case"url":return e.jsx("input",{type:"url",...m,className:"nice-form-preview__input"});case"password":return e.jsx("input",{type:"password",...m,className:"nice-form-preview__input"});case"color":return e.jsx("input",{type:"color",...m,className:"nice-form-preview__input nice-form-preview__color"});case"slider":case"rating":return e.jsx("input",{type:"range",...m,className:"nice-form-preview__input"});default:return e.jsx("input",{type:"text",...m,className:"nice-form-preview__input"})}},t=((r=i.layout)==null?void 0:r.columns)||1;return e.jsxs("form",{className:"nice-form-preview",style:{"--columns":t},children:[(n=i.layout)!=null&&n.sections?i.layout.sections.map((s,m)=>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(c=>{const g=i.fields.find(f=>f.id===c);return g?e.jsxs("div",{className:"nice-form-preview__field",children:[g.type!=="checkbox"&&e.jsxs("label",{className:"nice-form-preview__label",children:[g.label,g.required&&e.jsx("span",{className:"nice-form-preview__required",children:"*"})]}),a(g)]},g.id):null})})]},m)):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:`
790
+ `})]}):e.jsx("div",{className:`nice-form-builder-ai nice-form-builder-ai--disabled ${o||""}`,style:f,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function Wr({config:i}){var t,n;const a=s=>{var o,f;const l={id:s.id,placeholder:s.placeholder,required:s.required,disabled:!0};switch(s.type){case"textarea":case"richtext":case"markdown":return e.jsx("textarea",{...l,rows:3,className:"nice-form-preview__input nice-form-preview__textarea"});case"select":case"multiselect":return e.jsxs("select",{...l,className:"nice-form-preview__input nice-form-preview__select",children:[e.jsxs("option",{value:"",children:["Select ",s.label,"..."]}),(o=s.options)==null?void 0:o.map(h=>e.jsx("option",{value:h.value,children:h.label},h.value))]});case"radio":return e.jsx("div",{className:"nice-form-preview__radio-group",children:(f=s.options)==null?void 0:f.map(h=>e.jsxs("label",{className:"nice-form-preview__radio",children:[e.jsx("input",{type:"radio",name:s.id,value:h.value,disabled:!0}),h.label]},h.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",...l,className:"nice-form-preview__input"});case"date":return e.jsx("input",{type:"date",...l,className:"nice-form-preview__input"});case"time":return e.jsx("input",{type:"time",...l,className:"nice-form-preview__input"});case"datetime":return e.jsx("input",{type:"datetime-local",...l,className:"nice-form-preview__input"});case"number":case"currency":case"percentage":return e.jsx("input",{type:"number",...l,className:"nice-form-preview__input"});case"email":return e.jsx("input",{type:"email",...l,className:"nice-form-preview__input"});case"phone":return e.jsx("input",{type:"tel",...l,className:"nice-form-preview__input"});case"url":return e.jsx("input",{type:"url",...l,className:"nice-form-preview__input"});case"password":return e.jsx("input",{type:"password",...l,className:"nice-form-preview__input"});case"color":return e.jsx("input",{type:"color",...l,className:"nice-form-preview__input nice-form-preview__color"});case"slider":case"rating":return e.jsx("input",{type:"range",...l,className:"nice-form-preview__input"});default:return e.jsx("input",{type:"text",...l,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,l)=>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(o=>{const f=i.fields.find(h=>h.id===o);return f?e.jsxs("div",{className:"nice-form-preview__field",children:[f.type!=="checkbox"&&e.jsxs("label",{className:"nice-form-preview__label",children:[f.label,f.required&&e.jsx("span",{className:"nice-form-preview__required",children:"*"})]}),a(f)]},f.id):null})})]},l)):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:`
765
791
  .nice-form-preview {
766
792
  --columns: 1;
767
793
  }
@@ -866,7 +892,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
866
892
  cursor: not-allowed;
867
893
  opacity: 0.7;
868
894
  }
869
- `})]})}function ma(i={}){const{config:a,dataFields:t,context:r,onChartGenerated:n,onError:s}=i,m=X(),[c,g]=o.useState(!1),[f,j]=o.useState(null),[w,N]=o.useState(null),[S,$]=o.useState([]),k=o.useRef(null),P=a||(m==null?void 0:m.config),h=o.useMemo(()=>{if(t)return t.map(_=>{var b;return{name:_.name,type:_.type,label:_.label||_.name,...(b=_.sampleValues)!=null&&b.length?{samples:_.sampleValues.slice(0,3)}:{}}})},[t]),d=o.useCallback(async _=>{var u,y,A;if(!P){const R="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(R),{error:R}}g(!0),j(_);const b=performance.now();(u=k.current)==null||u.abort(),k.current=new AbortController;try{const R=G(P),l=Z(ce,{request:_,data:h?JSON.stringify(h,null,2):void 0,context:r}),x=await R.chat({messages:[{role:"system",content:l.system},{role:"user",content:l.user}],temperature:.4,maxTokens:1024}),M=xt(x),z={config:M||void 0,rawResponse:(A=(y=x.choices[0])==null?void 0:y.message)==null?void 0:A.content,latencyMs:performance.now()-b,error:M?void 0:"Failed to parse chart configuration",suggestions:bt(M)};return M&&(n==null||n(M)),N(z),$(D=>[...D.slice(-9),{request:_,result:z}]),z}catch(R){const l=R instanceof Error?R.message:"AI request failed",x={error:l,latencyMs:performance.now()-b};return N(x),s==null||s(l),x}finally{g(!1)}},[P,h,r,n,s]),v=o.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]),C=o.useCallback(()=>{j(null),N(null)},[]),p=o.useCallback(()=>{var _;(_=k.current)==null||_.abort(),g(!1)},[]);return o.useEffect(()=>()=>{var _;(_=k.current)==null||_.abort()},[]),{generateChart:d,suggestAlternatives:v,loading:c,lastRequest:f,lastResult:w,history:S,clearResults:C,abort:p,isConfigured:!!P}}function xt(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.content)||"",m=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(m);if(c.type)return{type:c.type,title:c.title,subtitle:c.subtitle,data:c.data||{},xAxis:c.xAxis,yAxis:c.yAxis,options:c.options}}catch{}return null}function bt(i){var t;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")),(t=i.options)!=null&&t.animation||a.push("Enable animations for better UX"),a.slice(0,3)}function vt({config:i,dataFields:a,context:t,onGenerate:r,placeholder:n='Describe the chart you want... (e.g., "Show monthly sales as a line chart")',showTypeSelector:s=!0,showPreview:m=!0,className:c,style:g,renderChart:f}){var y;const[j,w]=o.useState(""),[N,S]=o.useState(null),$=o.useRef(null),{generateChart:k,suggestAlternatives:P,loading:h,lastResult:d,isConfigured:v}=ma({config:i,dataFields:a,context:t,onChartGenerated:r}),C=[{type:"line",icon:"📈",label:"Line"},{type:"bar",icon:"📊",label:"Bar"},{type:"pie",icon:"🥧",label:"Pie"},{type:"area",icon:"📉",label:"Area"},{type:"scatter",icon:"⚬",label:"Scatter"},{type:"donut",icon:"🍩",label:"Donut"},{type:"heatmap",icon:"🔥",label:"Heatmap"},{type:"funnel",icon:"⏬",label:"Funnel"},{type:"gauge",icon:"⏱️",label:"Gauge"},{type:"radar",icon:"🎯",label:"Radar"}],p=async()=>{if(!j.trim()||h)return;const A=N?`Create a ${N} chart: ${j}`:j;await k(A)},_=A=>{A.key==="Enter"&&(A.preventDefault(),p())},b=A=>{S(N===A?null:A)},u=async A=>{if(!(d!=null&&d.config))return;const R={...d.config,type:A};r==null||r(R)};return v?e.jsxs("div",{className:`nice-chart-ai ${c||""}`,style:g,children:[s&&e.jsx("div",{className:"nice-chart-ai__types",children:C.map(({type:A,icon:R,label:l})=>e.jsxs("button",{type:"button",className:`nice-chart-ai__type ${N===A?"nice-chart-ai__type--selected":""}`,onClick:()=>b(A),title:l,children:[e.jsx("span",{className:"nice-chart-ai__type-icon",children:R}),e.jsx("span",{className:"nice-chart-ai__type-label",children:l})]},A))}),e.jsxs("div",{className:"nice-chart-ai__input-wrapper",children:[e.jsx("span",{className:"nice-chart-ai__icon",children:"📊"}),e.jsx("input",{ref:$,type:"text",value:j,onChange:A=>w(A.target.value),onKeyDown:_,placeholder:n,className:"nice-chart-ai__input",disabled:h}),h?e.jsx("span",{className:"nice-chart-ai__spinner"}):e.jsx("button",{type:"button",onClick:p,className:"nice-chart-ai__submit",disabled:!j.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(A=>e.jsx("span",{className:"nice-chart-ai__field-badge",title:A.type,children:A.label||A.name},A.name))]}),d&&e.jsx("div",{className:"nice-chart-ai__result",children:d.error?e.jsx("div",{className:"nice-chart-ai__error",children:d.error}):d.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:[(y=C.find(A=>A.type===d.config.type))==null?void 0:y.icon,d.config.type.charAt(0).toUpperCase()+d.config.type.slice(1)," ","Chart"]}),d.config.title&&e.jsx("span",{className:"nice-chart-ai__chart-title",children:d.config.title})]}),d.latencyMs&&e.jsxs("span",{className:"nice-chart-ai__latency",children:[Math.round(d.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(d.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:"}),C.filter(A=>A.type!==d.config.type).slice(0,4).map(({type:A,icon:R})=>e.jsx("button",{type:"button",className:"nice-chart-ai__alternative",onClick:()=>u(A),title:`Convert to ${A}`,children:R},A))]}),m&&e.jsx("div",{className:"nice-chart-ai__preview",children:f?f(d.config):e.jsx(yt,{config:d.config})}),e.jsxs("details",{className:"nice-chart-ai__json",children:[e.jsx("summary",{children:"View Configuration"}),e.jsx("pre",{children:JSON.stringify(d.config,null,2)})]})]})}),e.jsx("style",{children:`
895
+ `})]})}function Na(i={}){const{config:a,dataFields:r,context:t,onChartGenerated:n,onError:s}=i,l=Q(),[o,f]=c.useState(!1),[h,y]=c.useState(null),[w,C]=c.useState(null),[S,P]=c.useState([]),k=c.useRef(null),$=a||(l==null?void 0:l.config),g=c.useMemo(()=>{if(r)return r.map(v=>{var x;return{name:v.name,type:v.type,label:v.label||v.name,...(x=v.sampleValues)!=null&&x.length?{samples:v.sampleValues.slice(0,3)}:{}}})},[r]),d=c.useCallback(async v=>{var p,_,M;if(!$){const R="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(R),{error:R}}f(!0),y(v);const x=performance.now();(p=k.current)==null||p.abort(),k.current=new AbortController;try{const R=G($),T=ae(de,{request:v,data:g?JSON.stringify(g,null,2):void 0,context:t}),u=await R.chat({messages:[{role:"system",content:T.system},{role:"user",content:T.user}],temperature:.4,maxTokens:1024}),b=Gr(u),I={config:b||void 0,rawResponse:(M=(_=u.choices[0])==null?void 0:_.message)==null?void 0:M.content,latencyMs:performance.now()-x,error:b?void 0:"Failed to parse chart configuration",suggestions:Vr(b)};return b&&(n==null||n(b)),C(I),P(D=>[...D.slice(-9),{request:v,result:I}]),I}catch(R){const T=R instanceof Error?R.message:"AI request failed",u={error:T,latencyMs:performance.now()-x};return C(u),s==null||s(T),u}finally{f(!1)}},[$,g,t,n,s]),j=c.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]),N=c.useCallback(()=>{y(null),C(null)},[]),m=c.useCallback(()=>{var v;(v=k.current)==null||v.abort(),f(!1)},[]);return c.useEffect(()=>()=>{var v;(v=k.current)==null||v.abort()},[]),{generateChart:d,suggestAlternatives:j,loading:o,lastRequest:h,lastResult:w,history:S,clearResults:N,abort:m,isConfigured:!!$}}function Gr(i){var a,r,t;try{const n=((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"",l=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,o=JSON.parse(l);if(o.type)return{type:o.type,title:o.title,subtitle:o.subtitle,data:o.data||{},xAxis:o.xAxis,yAxis:o.yAxis,options:o.options}}catch{}return null}function Vr(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 Kr({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:l=!0,className:o,style:f,renderChart:h}){var _;const[y,w]=c.useState(""),[C,S]=c.useState(null),P=c.useRef(null),{generateChart:k,suggestAlternatives:$,loading:g,lastResult:d,isConfigured:j}=Na({config:i,dataFields:a,context:r,onChartGenerated:t}),N=[{type:"line",icon:"📈",label:"Line"},{type:"bar",icon:"📊",label:"Bar"},{type:"pie",icon:"🥧",label:"Pie"},{type:"area",icon:"📉",label:"Area"},{type:"scatter",icon:"⚬",label:"Scatter"},{type:"donut",icon:"🍩",label:"Donut"},{type:"heatmap",icon:"🔥",label:"Heatmap"},{type:"funnel",icon:"⏬",label:"Funnel"},{type:"gauge",icon:"⏱️",label:"Gauge"},{type:"radar",icon:"🎯",label:"Radar"}],m=async()=>{if(!y.trim()||g)return;const M=C?`Create a ${C} chart: ${y}`:y;await k(M)},v=M=>{M.key==="Enter"&&(M.preventDefault(),m())},x=M=>{S(C===M?null:M)},p=async M=>{if(!(d!=null&&d.config))return;const R={...d.config,type:M};t==null||t(R)};return j?e.jsxs("div",{className:`nice-chart-ai ${o||""}`,style:f,children:[s&&e.jsx("div",{className:"nice-chart-ai__types",children:N.map(({type:M,icon:R,label:T})=>e.jsxs("button",{type:"button",className:`nice-chart-ai__type ${C===M?"nice-chart-ai__type--selected":""}`,onClick:()=>x(M),title:T,children:[e.jsx("span",{className:"nice-chart-ai__type-icon",children:R}),e.jsx("span",{className:"nice-chart-ai__type-label",children:T})]},M))}),e.jsxs("div",{className:"nice-chart-ai__input-wrapper",children:[e.jsx("span",{className:"nice-chart-ai__icon",children:"📊"}),e.jsx("input",{ref:P,type:"text",value:y,onChange:M=>w(M.target.value),onKeyDown:v,placeholder:n,className:"nice-chart-ai__input",disabled:g}),g?e.jsx("span",{className:"nice-chart-ai__spinner"}):e.jsx("button",{type:"button",onClick:m,className:"nice-chart-ai__submit",disabled:!y.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(M=>e.jsx("span",{className:"nice-chart-ai__field-badge",title:M.type,children:M.label||M.name},M.name))]}),d&&e.jsx("div",{className:"nice-chart-ai__result",children:d.error?e.jsx("div",{className:"nice-chart-ai__error",children:d.error}):d.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:[(_=N.find(M=>M.type===d.config.type))==null?void 0:_.icon,d.config.type.charAt(0).toUpperCase()+d.config.type.slice(1)," ","Chart"]}),d.config.title&&e.jsx("span",{className:"nice-chart-ai__chart-title",children:d.config.title})]}),d.latencyMs&&e.jsxs("span",{className:"nice-chart-ai__latency",children:[Math.round(d.latencyMs),"ms"]}),e.jsx("button",{type:"button",onClick:()=>t==null?void 0:t(d.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:"}),N.filter(M=>M.type!==d.config.type).slice(0,4).map(({type:M,icon:R})=>e.jsx("button",{type:"button",className:"nice-chart-ai__alternative",onClick:()=>p(M),title:`Convert to ${M}`,children:R},M))]}),l&&e.jsx("div",{className:"nice-chart-ai__preview",children:h?h(d.config):e.jsx(Yr,{config:d.config})}),e.jsxs("details",{className:"nice-chart-ai__json",children:[e.jsx("summary",{children:"View Configuration"}),e.jsx("pre",{children:JSON.stringify(d.config,null,2)})]})]})}),e.jsx("style",{children:`
870
896
  .nice-chart-ai {
871
897
  font-family: var(--nice-font-family, system-ui, sans-serif);
872
898
  }
@@ -1110,7 +1136,7 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
1110
1136
  color: var(--nice-error, #c62828);
1111
1137
  border-radius: var(--nice-radius-md, 6px);
1112
1138
  }
1113
- `})]}):e.jsx("div",{className:`nice-chart-ai nice-chart-ai--disabled ${c||""}`,style:g,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function yt({config:i}){var t;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 r=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,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.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()}),((t=i.options)==null?void 0:t.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:`
1139
+ `})]}):e.jsx("div",{className:`nice-chart-ai nice-chart-ai--disabled ${o||""}`,style:f,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function Yr({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.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:`
1114
1140
  .nice-chart-preview {
1115
1141
  text-align: center;
1116
1142
  }
@@ -1171,11 +1197,11 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
1171
1197
  height: 12px;
1172
1198
  border-radius: var(--nice-radius-sm, 2px);
1173
1199
  }
1174
- `})]})}function ha(i={}){const{config:a,language:t="typescript",context:r,maxSuggestions:n=3,debounceMs:s=300,onSuggestion:m,onError:c}=i,g=X(),[f,j]=o.useState(!1),[w,N]=o.useState([]),[S,$]=o.useState(-1),k=o.useRef(null),P=o.useRef(null),h=a||(g==null?void 0:g.config),d=o.useCallback(async(l,x)=>{var z,D,J;if(!h)return{suggestions:[],error:"AI not configured"};j(!0),(z=k.current)==null||z.abort(),k.current=new AbortController;const M=performance.now();try{const H=G(h),Y=l.split(`
1175
- `),I=Y[x.line]||"",F=I.substring(0,x.column),q=I.substring(x.column),W=Y.slice(Math.max(0,x.line-20),x.line).join(`
1176
- `),U=Y.slice(x.line+1,x.line+10).join(`
1177
- `),K=Z(oe,{language:t,code_context:W,prefix:F,suffix:q,context_after:U,context:r}),Q=await H.chat({messages:[{role:"system",content:K.system},{role:"user",content:K.user}],temperature:.2,maxTokens:512}),T=_t(Q,x,n),L={suggestions:T,rawResponse:(J=(D=Q.choices[0])==null?void 0:D.message)==null?void 0:J.content,latencyMs:performance.now()-M};return N(T),$(T.length>0?0:-1),m==null||m(T),L}catch(H){const Y=H instanceof Error?H.message:"Completion failed";return c==null||c(Y),{suggestions:[],error:Y,latencyMs:performance.now()-M}}finally{j(!1)}},[h,t,r,n,m,c]),v=o.useCallback((l,x)=>{P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{d(l,x)},s)},[d,s]),C=o.useCallback(async l=>{if(!h)return null;j(!0);try{const M=await G(h).chat({messages:[{role:"system",content:`You are a code explanation assistant. Explain the following ${t} code clearly and concisely. Return JSON with: { "summary": string, "details": string, "complexity": "low"|"medium"|"high", "suggestions": string[] }`},{role:"user",content:l}],temperature:.3,maxTokens:1024});return wt(M)}catch{return null}finally{j(!1)}},[h,t]),p=o.useCallback(async l=>{if(!h)return[];j(!0);try{const M=await G(h).chat({messages:[{role:"system",content:`You are a code refactoring assistant. Analyze the following ${t} code and suggest improvements. Return JSON array with: [{ "title": string, "description": string, "before": string, "after": string, "type": "extract-function"|"rename"|"simplify"|"optimize"|"security"|"style" }]`},{role:"user",content:l}],temperature:.4,maxTokens:2048});return jt(M)}catch{return[]}finally{j(!1)}},[h,t]),_=o.useCallback(async(l,x)=>{var M,z;if(!h)return null;j(!0);try{const D=G(h),J=x||kt(t);return((z=(M=(await D.chat({messages:[{role:"system",content:`You are a testing expert. Generate comprehensive unit tests for the following ${t} code using ${J}. Include edge cases and error scenarios. Return only the test code.`},{role:"user",content:l}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:M.message)==null?void 0:z.content)||null}catch{return null}finally{j(!1)}},[h,t]),b=o.useCallback(async(l,x)=>{var M,z;if(!h)return null;j(!0);try{const D=G(h),J=x||Nt(t);return((z=(M=(await D.chat({messages:[{role:"system",content:`Generate ${J} documentation for the following ${t} code. Include descriptions for parameters, return values, and examples where appropriate. Return only the documented code.`},{role:"user",content:l}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:M.message)==null?void 0:z.content)||null}catch{return null}finally{j(!1)}},[h,t]),u=o.useCallback((l=S)=>{const x=w[l];return N([]),$(-1),x},[w,S]),y=o.useCallback(()=>{N([]),$(-1)},[]),A=o.useCallback(l=>{w.length!==0&&$(x=>l==="up"?x<=0?w.length-1:x-1:x>=w.length-1?0:x+1)},[w.length]),R=o.useCallback(()=>{var l;(l=k.current)==null||l.abort(),P.current&&clearTimeout(P.current),j(!1)},[]);return o.useEffect(()=>()=>{var l;(l=k.current)==null||l.abort(),P.current&&clearTimeout(P.current)},[]),{getCompletions:d,getCompletionsDebounced:v,suggestions:w,activeSuggestion:S,acceptSuggestion:u,dismissSuggestions:y,navigateSuggestions:A,explainCode:C,suggestRefactoring:p,generateTests:_,generateDocs:b,loading:f,abort:R,isConfigured:!!h}}function _t(i,a,t){var r,n;try{return(((n=(r=i.choices[0])==null?void 0:r.message)==null?void 0:n.content)||"").split(`
1178
- `).filter(c=>c.trim()).slice(0,t).map((c,g)=>({id:`suggestion-${Date.now()}-${g}`,text:c.trim(),type:"inline",preview:c.trim().slice(0,50),confidence:.8-g*.1,insertPosition:a}))}catch{return[]}}function wt(i){var a,t;try{const r=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.content)||"",n=r.match(/\{[\s\S]*\}/);return n?JSON.parse(n[0]):{summary:r}}catch{return null}}function jt(i){var a,t;try{const n=(((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.content)||"").match(/\[[\s\S]*\]/);if(n)return JSON.parse(n[0])}catch{}return[]}function kt(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 Nt(i){return{javascript:"jsdoc",typescript:"tsdoc",python:"docstring",java:"javadoc",kotlin:"javadoc"}[i]||"jsdoc"}function Ct({code:i="",language:a="typescript",config:t,onChange:r,onAcceptSuggestion:n,showToolbar:s=!0,enableInlineSuggestions:m=!0,placeholder:c="Start typing code...",className:g,style:f,renderEditor:j}){const[w,N]=o.useState(i),[S,$]=o.useState(null),[k,P]=o.useState(null),[h,d]=o.useState([]),[v,C]=o.useState(null),[p,_]=o.useState(null),b=o.useRef(null),{getCompletionsDebounced:u,suggestions:y,activeSuggestion:A,acceptSuggestion:R,dismissSuggestions:l,navigateSuggestions:x,explainCode:M,suggestRefactoring:z,generateTests:D,generateDocs:J,loading:H,isConfigured:Y}=ha({config:t,language:a}),I=O=>{if(N(O),r==null||r(O),m&&b.current){const B=St(b.current);u(O,B)}},F=O=>{if(y.length>0)if(O.key==="ArrowUp")O.preventDefault(),x("up");else if(O.key==="ArrowDown")O.preventDefault(),x("down");else if(O.key==="Tab"||O.key==="Enter"){if(A>=0){O.preventDefault();const B=R(A);B&&(q(B),n==null||n(B))}}else O.key==="Escape"&&l()},q=O=>{if(!b.current)return;const B=b.current,ee=B.selectionStart,Me=w.slice(0,ee)+O.text+w.slice(ee);N(Me),r==null||r(Me);const Pe=ee+O.text.length;setTimeout(()=>{B.focus(),B.setSelectionRange(Pe,Pe)},0)},W=async()=>{const O=S||w;if(!O.trim())return;_("explain");const B=await M(O);P(B)},U=async()=>{const O=S||w;if(!O.trim())return;_("refactor");const B=await z(O);d(B)},K=async()=>{if(!w.trim())return;_("tests");const O=await D(w);C(O)},Q=async()=>{if(!w.trim())return;_("docs");const O=await J(w);C(O)},T=O=>{const B=w.replace(O.before,O.after);N(B),r==null||r(B),_(null)},L=()=>{v&&navigator.clipboard.writeText(v)},E=()=>{if(b.current){const O=b.current.selectionStart,B=b.current.selectionEnd;$(O!==B?w.slice(O,B):null)}};return Y?j?e.jsx("div",{className:`nice-code-editor-ai ${g||""}`,style:f,children:j({code:w,onChange:I,suggestions:y,onAccept:O=>{const B=R(O);B&&(n==null||n(B))}})}):e.jsxs("div",{className:`nice-code-editor-ai ${g||""}`,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.jsx("button",{type:"button",onClick:W,disabled:H||!w.trim(),title:"Explain code",children:"💡 Explain"}),e.jsx("button",{type:"button",onClick:U,disabled:H||!w.trim(),title:"Suggest refactoring",children:"🔧 Refactor"}),e.jsx("button",{type:"button",onClick:K,disabled:H||!w.trim(),title:"Generate tests",children:"🧪 Tests"}),e.jsx("button",{type:"button",onClick:Q,disabled:H||!w.trim(),title:"Generate docs",children:"📝 Docs"})]}),H&&e.jsx("span",{className:"nice-code-editor-ai__loading",children:"Processing..."})]}),e.jsxs("div",{className:"nice-code-editor-ai__editor-wrapper",children:[e.jsx("textarea",{ref:b,value:w,onChange:O=>I(O.target.value),onKeyDown:F,onSelect:E,placeholder:c,className:"nice-code-editor-ai__textarea",spellCheck:!1}),y.length>0&&e.jsxs("div",{className:"nice-code-editor-ai__suggestions",children:[y.map((O,B)=>e.jsxs("div",{className:`nice-code-editor-ai__suggestion ${B===A?"nice-code-editor-ai__suggestion--active":""}`,onClick:()=>{const ee=R(B);ee&&(q(ee),n==null||n(ee))},children:[e.jsx("span",{className:"nice-code-editor-ai__suggestion-text",children:O.text}),e.jsxs("span",{className:"nice-code-editor-ai__suggestion-confidence",children:[Math.round(O.confidence*100),"%"]})]},O.id)),e.jsx("div",{className:"nice-code-editor-ai__suggestions-hint",children:"↑↓ 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"&&"💡 Explanation",p==="refactor"&&"🔧 Refactoring Suggestions",p==="tests"&&"🧪 Generated Tests",p==="docs"&&"📝 Generated Documentation"]}),e.jsx("button",{type:"button",onClick:()=>_(null),children:"✕"})]}),e.jsxs("div",{className:"nice-code-editor-ai__panel-content",children:[p==="explain"&&k&&e.jsxs("div",{className:"nice-code-editor-ai__explanation",children:[e.jsx("div",{className:"nice-code-editor-ai__explanation-summary",children:k.summary}),k.details&&e.jsx("div",{className:"nice-code-editor-ai__explanation-details",children:k.details}),k.complexity&&e.jsxs("span",{className:`nice-code-editor-ai__complexity nice-code-editor-ai__complexity--${k.complexity}`,children:["Complexity: ",k.complexity]}),k.suggestions&&k.suggestions.length>0&&e.jsx("ul",{className:"nice-code-editor-ai__explanation-suggestions",children:k.suggestions.map((O,B)=>e.jsx("li",{children:O},B))})]}),p==="refactor"&&h.length>0&&e.jsx("div",{className:"nice-code-editor-ai__refactorings",children:h.map((O,B)=>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:O.title}),e.jsx("span",{className:`nice-code-editor-ai__refactoring-type nice-code-editor-ai__refactoring-type--${O.type}`,children:O.type})]}),e.jsx("p",{className:"nice-code-editor-ai__refactoring-desc",children:O.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:O.before})]}),e.jsxs("div",{className:"nice-code-editor-ai__refactoring-after",children:[e.jsx("span",{children:"After:"}),e.jsx("pre",{children:O.after})]})]}),e.jsx("button",{type:"button",className:"nice-code-editor-ai__refactoring-apply",onClick:()=>T(O),children:"Apply"})]},B))}),(p==="tests"||p==="docs")&&v&&e.jsxs("div",{className:"nice-code-editor-ai__generated",children:[e.jsx("pre",{children:v}),e.jsx("button",{type:"button",onClick:L,children:"📋 Copy"})]})]})]}),e.jsx("style",{children:`
1200
+ `})]})}function Ca(i={}){const{config:a,language:r="typescript",context:t,maxSuggestions:n=3,debounceMs:s=300,onSuggestion:l,onError:o}=i,f=Q(),[h,y]=c.useState(!1),[w,C]=c.useState([]),[S,P]=c.useState(-1),k=c.useRef(null),$=c.useRef(null),g=a||(f==null?void 0:f.config),d=c.useCallback(async(T,u)=>{var I,D,J;if(!g)return{suggestions:[],error:"AI not configured"};y(!0),(I=k.current)==null||I.abort(),k.current=new AbortController;const b=performance.now();try{const Y=G(g),V=T.split(`
1201
+ `),z=V[u.line]||"",F=z.substring(0,u.column),U=z.substring(u.column),W=V.slice(Math.max(0,u.line-20),u.line).join(`
1202
+ `),q=V.slice(u.line+1,u.line+10).join(`
1203
+ `),Z=ae(ue,{language:r,code_context:W,prefix:F,suffix:U,context_after:q,context:t}),ee=await Y.chat({messages:[{role:"system",content:Z.system},{role:"user",content:Z.user}],temperature:.2,maxTokens:512}),A=Xr(ee,u,n),L={suggestions:A,rawResponse:(J=(D=ee.choices[0])==null?void 0:D.message)==null?void 0:J.content,latencyMs:performance.now()-b};return C(A),P(A.length>0?0:-1),l==null||l(A),L}catch(Y){const V=Y instanceof Error?Y.message:"Completion failed";return o==null||o(V),{suggestions:[],error:V,latencyMs:performance.now()-b}}finally{y(!1)}},[g,r,t,n,l,o]),j=c.useCallback((T,u)=>{$.current&&clearTimeout($.current),$.current=setTimeout(()=>{d(T,u)},s)},[d,s]),N=c.useCallback(async T=>{if(!g)return null;y(!0);try{const b=await G(g).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:T}],temperature:.3,maxTokens:1024});return Zr(b)}catch{return null}finally{y(!1)}},[g,r]),m=c.useCallback(async T=>{if(!g)return[];y(!0);try{const b=await G(g).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:T}],temperature:.4,maxTokens:2048});return Qr(b)}catch{return[]}finally{y(!1)}},[g,r]),v=c.useCallback(async(T,u)=>{var b,I;if(!g)return null;y(!0);try{const D=G(g),J=u||ei(r);return((I=(b=(await D.chat({messages:[{role:"system",content:`You are a testing expert. Generate comprehensive unit tests for the following ${r} code using ${J}. Include edge cases and error scenarios. Return only the test code.`},{role:"user",content:T}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:b.message)==null?void 0:I.content)||null}catch{return null}finally{y(!1)}},[g,r]),x=c.useCallback(async(T,u)=>{var b,I;if(!g)return null;y(!0);try{const D=G(g),J=u||ai(r);return((I=(b=(await D.chat({messages:[{role:"system",content:`Generate ${J} documentation for the following ${r} code. Include descriptions for parameters, return values, and examples where appropriate. Return only the documented code.`},{role:"user",content:T}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:b.message)==null?void 0:I.content)||null}catch{return null}finally{y(!1)}},[g,r]),p=c.useCallback((T=S)=>{const u=w[T];return C([]),P(-1),u},[w,S]),_=c.useCallback(()=>{C([]),P(-1)},[]),M=c.useCallback(T=>{w.length!==0&&P(u=>T==="up"?u<=0?w.length-1:u-1:u>=w.length-1?0:u+1)},[w.length]),R=c.useCallback(()=>{var T;(T=k.current)==null||T.abort(),$.current&&clearTimeout($.current),y(!1)},[]);return c.useEffect(()=>()=>{var T;(T=k.current)==null||T.abort(),$.current&&clearTimeout($.current)},[]),{getCompletions:d,getCompletionsDebounced:j,suggestions:w,activeSuggestion:S,acceptSuggestion:p,dismissSuggestions:_,navigateSuggestions:M,explainCode:N,suggestRefactoring:m,generateTests:v,generateDocs:x,loading:h,abort:R,isConfigured:!!g}}function Xr(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(o=>o.trim()).slice(0,r).map((o,f)=>({id:`suggestion-${Date.now()}-${f}`,text:o.trim(),type:"inline",preview:o.trim().slice(0,50),confidence:.8-f*.1,insertPosition:a}))}catch{return[]}}function Zr(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 Qr(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 ei(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 ai(i){return{javascript:"jsdoc",typescript:"tsdoc",python:"docstring",java:"javadoc",kotlin:"javadoc"}[i]||"jsdoc"}function ri({code:i="",language:a="typescript",config:r,onChange:t,onAcceptSuggestion:n,showToolbar:s=!0,enableInlineSuggestions:l=!0,placeholder:o="Start typing code...",className:f,style:h,renderEditor:y}){const[w,C]=c.useState(i),[S,P]=c.useState(null),[k,$]=c.useState(null),[g,d]=c.useState([]),[j,N]=c.useState(null),[m,v]=c.useState(null),x=c.useRef(null),{getCompletionsDebounced:p,suggestions:_,activeSuggestion:M,acceptSuggestion:R,dismissSuggestions:T,navigateSuggestions:u,explainCode:b,suggestRefactoring:I,generateTests:D,generateDocs:J,loading:Y,isConfigured:V}=Ca({config:r,language:a}),z=O=>{if(C(O),t==null||t(O),l&&x.current){const B=ii(x.current);p(O,B)}},F=O=>{if(_.length>0)if(O.key==="ArrowUp")O.preventDefault(),u("up");else if(O.key==="ArrowDown")O.preventDefault(),u("down");else if(O.key==="Tab"||O.key==="Enter"){if(M>=0){O.preventDefault();const B=R(M);B&&(U(B),n==null||n(B))}}else O.key==="Escape"&&T()},U=O=>{if(!x.current)return;const B=x.current,re=B.selectionStart,ze=w.slice(0,re)+O.text+w.slice(re);C(ze),t==null||t(ze);const Le=re+O.text.length;setTimeout(()=>{B.focus(),B.setSelectionRange(Le,Le)},0)},W=async()=>{const O=S||w;if(!O.trim())return;v("explain");const B=await b(O);$(B)},q=async()=>{const O=S||w;if(!O.trim())return;v("refactor");const B=await I(O);d(B)},Z=async()=>{if(!w.trim())return;v("tests");const O=await D(w);N(O)},ee=async()=>{if(!w.trim())return;v("docs");const O=await J(w);N(O)},A=O=>{const B=w.replace(O.before,O.after);C(B),t==null||t(B),v(null)},L=()=>{j&&navigator.clipboard.writeText(j)},H=()=>{if(x.current){const O=x.current.selectionStart,B=x.current.selectionEnd;P(O!==B?w.slice(O,B):null)}};return V?y?e.jsx("div",{className:`nice-code-editor-ai ${f||""}`,style:h,children:y({code:w,onChange:z,suggestions:_,onAccept:O=>{const B=R(O);B&&(n==null||n(B))}})}):e.jsxs("div",{className:`nice-code-editor-ai ${f||""}`,style:h,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.jsx("button",{type:"button",onClick:W,disabled:Y||!w.trim(),title:"Explain code",children:"💡 Explain"}),e.jsx("button",{type:"button",onClick:q,disabled:Y||!w.trim(),title:"Suggest refactoring",children:"🔧 Refactor"}),e.jsx("button",{type:"button",onClick:Z,disabled:Y||!w.trim(),title:"Generate tests",children:"🧪 Tests"}),e.jsx("button",{type:"button",onClick:ee,disabled:Y||!w.trim(),title:"Generate docs",children:"📝 Docs"})]}),Y&&e.jsx("span",{className:"nice-code-editor-ai__loading",children:"Processing..."})]}),e.jsxs("div",{className:"nice-code-editor-ai__editor-wrapper",children:[e.jsx("textarea",{ref:x,value:w,onChange:O=>z(O.target.value),onKeyDown:F,onSelect:H,placeholder:o,className:"nice-code-editor-ai__textarea",spellCheck:!1}),_.length>0&&e.jsxs("div",{className:"nice-code-editor-ai__suggestions",children:[_.map((O,B)=>e.jsxs("div",{className:`nice-code-editor-ai__suggestion ${B===M?"nice-code-editor-ai__suggestion--active":""}`,onClick:()=>{const re=R(B);re&&(U(re),n==null||n(re))},children:[e.jsx("span",{className:"nice-code-editor-ai__suggestion-text",children:O.text}),e.jsxs("span",{className:"nice-code-editor-ai__suggestion-confidence",children:[Math.round(O.confidence*100),"%"]})]},O.id)),e.jsx("div",{className:"nice-code-editor-ai__suggestions-hint",children:"↑↓ navigate • Tab accept • Esc dismiss"})]})]}),m&&e.jsxs("div",{className:"nice-code-editor-ai__panel",children:[e.jsxs("div",{className:"nice-code-editor-ai__panel-header",children:[e.jsxs("span",{children:[m==="explain"&&"💡 Explanation",m==="refactor"&&"🔧 Refactoring Suggestions",m==="tests"&&"🧪 Generated Tests",m==="docs"&&"📝 Generated Documentation"]}),e.jsx("button",{type:"button",onClick:()=>v(null),children:"✕"})]}),e.jsxs("div",{className:"nice-code-editor-ai__panel-content",children:[m==="explain"&&k&&e.jsxs("div",{className:"nice-code-editor-ai__explanation",children:[e.jsx("div",{className:"nice-code-editor-ai__explanation-summary",children:k.summary}),k.details&&e.jsx("div",{className:"nice-code-editor-ai__explanation-details",children:k.details}),k.complexity&&e.jsxs("span",{className:`nice-code-editor-ai__complexity nice-code-editor-ai__complexity--${k.complexity}`,children:["Complexity: ",k.complexity]}),k.suggestions&&k.suggestions.length>0&&e.jsx("ul",{className:"nice-code-editor-ai__explanation-suggestions",children:k.suggestions.map((O,B)=>e.jsx("li",{children:O},B))})]}),m==="refactor"&&g.length>0&&e.jsx("div",{className:"nice-code-editor-ai__refactorings",children:g.map((O,B)=>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:O.title}),e.jsx("span",{className:`nice-code-editor-ai__refactoring-type nice-code-editor-ai__refactoring-type--${O.type}`,children:O.type})]}),e.jsx("p",{className:"nice-code-editor-ai__refactoring-desc",children:O.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:O.before})]}),e.jsxs("div",{className:"nice-code-editor-ai__refactoring-after",children:[e.jsx("span",{children:"After:"}),e.jsx("pre",{children:O.after})]})]}),e.jsx("button",{type:"button",className:"nice-code-editor-ai__refactoring-apply",onClick:()=>A(O),children:"Apply"})]},B))}),(m==="tests"||m==="docs")&&j&&e.jsxs("div",{className:"nice-code-editor-ai__generated",children:[e.jsx("pre",{children:j}),e.jsx("button",{type:"button",onClick:L,children:"📋 Copy"})]})]})]}),e.jsx("style",{children:`
1179
1205
  .nice-code-editor-ai {
1180
1206
  font-family: var(--nice-font-family, system-ui, sans-serif);
1181
1207
  display: flex;
@@ -1481,11 +1507,11 @@ Provide summary and insights:`,variables:[{name:"data",description:"Data to summ
1481
1507
  border-radius: var(--nice-radius-md, 6px);
1482
1508
  cursor: pointer;
1483
1509
  }
1484
- `})]}):e.jsxs("div",{className:`nice-code-editor-ai nice-code-editor-ai--disabled ${g||""}`,style:f,children:[e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."}),e.jsx("textarea",{value:w,onChange:O=>I(O.target.value),placeholder:c,className:"nice-code-editor-ai__textarea"})]})}function St(i){const t=i.value.substring(0,i.selectionStart).split(`
1485
- `);return{line:t.length-1,column:t[t.length-1].length}}function ga(i={}){const{config:a,context:t,existingRoles:r,existingVariables:n,onWorkflowGenerated:s,onError:m}=i,c=X(),[g,f]=o.useState(!1),[j,w]=o.useState(null),[N,S]=o.useState([]),$=o.useRef(null),k=a||(c==null?void 0:c.config),P=o.useCallback(async _=>{var u,y,A;if(!k){const R="AI not configured";return m==null||m(R),{error:R}}f(!0);const b=performance.now();(u=$.current)==null||u.abort(),$.current=new AbortController;try{const R=G(k),l=[t,r!=null&&r.length?`Available roles: ${r.join(", ")}`:"",n!=null&&n.length?`Existing variables: ${n.join(", ")}`:""].filter(Boolean).join(`
1486
- `),x=Z(le,{description:_,context:l}),M=await R.chat({messages:[{role:"system",content:x.system},{role:"user",content:x.user}],temperature:.5,maxTokens:2048}),z=Oe(M),D={workflow:z||void 0,rawResponse:(A=(y=M.choices[0])==null?void 0:y.message)==null?void 0:A.content,latencyMs:performance.now()-b,error:z?void 0:"Failed to generate workflow",suggestions:At(z)};return z&&(s==null||s(z)),w(D),S(J=>[...J.slice(-9),{request:_,result:D}]),D}catch(R){const l=R instanceof Error?R.message:"Workflow generation failed",x={error:l,latencyMs:performance.now()-b};return w(x),m==null||m(l),x}finally{f(!1)}},[k,t,r,n,s,m]),h=o.useCallback(async _=>{if(!k)return{error:"AI not configured"};f(!0);const b=performance.now();try{const y=await G(k).chat({messages:[{role:"system",content:"You are a workflow optimization expert. Analyze the following BPMN workflow and suggest improvements for efficiency, clarity, and error handling. Return the optimized workflow in JSON format with the same structure."},{role:"user",content:JSON.stringify(_,null,2)}],temperature:.4,maxTokens:2048});return{workflow:Oe(y)||void 0,latencyMs:performance.now()-b}}catch(u){return{error:u instanceof Error?u.message:"Optimization failed"}}finally{f(!1)}},[k]),d=o.useCallback(async(_,b)=>{var u,y;if(!k)return[];f(!0);try{const A=G(k),R=_.nodes.find(z=>z.id===b),M=(((y=(u=(await A.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: ${_.name}
1487
- Current node: ${(R==null?void 0:R.label)||b}
1488
- Existing nodes: ${_.nodes.map(z=>z.label).join(", ")}`}],temperature:.6,maxTokens:512})).choices[0])==null?void 0:u.message)==null?void 0:y.content)||"").match(/\[[\s\S]*\]/);if(M)return JSON.parse(M[0])}catch{}finally{f(!1)}return[]},[k]),v=o.useCallback(async _=>{var b,u;if(!k)return[];f(!0);try{const l=(((u=(b=(await G(k).chat({messages:[{role:"system",content:'Analyze the BPMN workflow for potential issues. Check for: dead ends, unreachable nodes, missing error handling, infinite loops, unclear conditions, missing assignments. Return JSON array of issues: [{ "severity": "error"|"warning"|"info", "message": string, "nodeId": string? }]'},{role:"user",content:JSON.stringify(_,null,2)}],temperature:.3,maxTokens:1024})).choices[0])==null?void 0:b.message)==null?void 0:u.content)||"").match(/\[[\s\S]*\]/);if(l)return JSON.parse(l[0]).map(M=>`[${M.severity}] ${M.message}`)}catch{}finally{f(!1)}return[]},[k]),C=o.useCallback(()=>{w(null)},[]),p=o.useCallback(()=>{var _;(_=$.current)==null||_.abort(),f(!1)},[]);return o.useEffect(()=>()=>{var _;(_=$.current)==null||_.abort()},[]),{generateWorkflow:P,optimizeWorkflow:h,suggestNextStep:d,validateWorkflow:v,loading:g,lastResult:j,history:N,clearResults:C,abort:p,isConfigured:!!k}}function Oe(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.content)||"",m=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(m);if(c.nodes&&Array.isArray(c.nodes)){const g=c.nodes.map((f,j)=>({...f,id:f.id||`node_${j}`,position:f.position||Tt(j,c.nodes.length)}));return{id:c.id||`workflow_${Date.now()}`,name:c.name||"Generated Workflow",description:c.description,version:c.version||"1.0",nodes:g,edges:c.edges||[],lanes:c.lanes,variables:c.variables,metadata:c.metadata}}}catch{}return null}function Tt(i,a){const s=Math.floor(i/5);return{x:100+i%5*200,y:100+s*100}}function At(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 Rt=["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 Mt({config:i,context:a,roles:t,onGenerate:r,placeholder:n='Describe the workflow process... (e.g., "Leave request with manager approval")',showExamples:s=!0,showPreview:m=!0,className:c,style:g,renderWorkflow:f}){const[j,w]=o.useState(""),[N,S]=o.useState([]),$=o.useRef(null),{generateWorkflow:k,validateWorkflow:P,loading:h,lastResult:d,isConfigured:v}=ga({config:i,context:a,existingRoles:t,onWorkflowGenerated:r}),C=async()=>{!j.trim()||h||await k(j)},p=u=>{var y;w(u),(y=$.current)==null||y.focus()},_=async()=>{if(!(d!=null&&d.workflow))return;const u=await P(d.workflow);S(u)},b=()=>{if(!(d!=null&&d.workflow))return;const u=$t(d.workflow),y=new Blob([u],{type:"application/xml"}),A=URL.createObjectURL(y),R=document.createElement("a");R.href=A,R.download=`${d.workflow.name.replace(/\s+/g,"_")}.bpmn`,R.click(),URL.revokeObjectURL(A)};return v?e.jsxs("div",{className:`nice-workflow-ai ${c||""}`,style:g,children:[e.jsxs("div",{className:"nice-workflow-ai__input-section",children:[e.jsx("textarea",{ref:$,value:j,onChange:u=>w(u.target.value),placeholder:n,className:"nice-workflow-ai__input",rows:3,disabled:h}),e.jsx("button",{type:"button",onClick:C,className:"nice-workflow-ai__submit",disabled:h||!j.trim(),children:h?e.jsx("span",{className:"nice-workflow-ai__spinner"}):"🔄 Generate Workflow"})]}),s&&e.jsxs("div",{className:"nice-workflow-ai__examples",children:[e.jsx("span",{className:"nice-workflow-ai__examples-label",children:"Try:"}),Rt.slice(0,3).map((u,y)=>e.jsx("button",{type:"button",className:"nice-workflow-ai__example",onClick:()=>p(u),children:u},y))]}),d&&e.jsx("div",{className:"nice-workflow-ai__result",children:d.error?e.jsx("div",{className:"nice-workflow-ai__error",children:d.error}):d.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:d.workflow.name}),d.workflow.description&&e.jsx("span",{className:"nice-workflow-ai__workflow-desc",children:d.workflow.description})]}),e.jsxs("div",{className:"nice-workflow-ai__result-meta",children:[e.jsxs("span",{className:"nice-workflow-ai__stat",children:[d.workflow.nodes.length," nodes"]}),e.jsxs("span",{className:"nice-workflow-ai__stat",children:[d.workflow.edges.length," connections"]}),d.latencyMs&&e.jsxs("span",{className:"nice-workflow-ai__latency",children:[Math.round(d.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-workflow-ai__actions",children:[e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(d.workflow),children:"✅ Use Workflow"}),e.jsx("button",{type:"button",onClick:_,children:"🔍 Validate"}),e.jsx("button",{type:"button",onClick:b,children:"📥 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,y)=>e.jsx("li",{className:`nice-workflow-ai__issue nice-workflow-ai__issue--${u.startsWith("[error]")?"error":u.startsWith("[warning]")?"warning":"info"}`,children:u},y))})]}),m&&e.jsx("div",{className:"nice-workflow-ai__preview",children:f?f(d.workflow):e.jsx(Pt,{workflow:d.workflow})}),d.suggestions&&d.suggestions.length>0&&e.jsxs("div",{className:"nice-workflow-ai__suggestions",children:[e.jsx("span",{className:"nice-workflow-ai__suggestions-title",children:"💡 Suggestions:"}),e.jsx("ul",{children:d.suggestions.map((u,y)=>e.jsx("li",{children:u},y))})]}),e.jsxs("details",{className:"nice-workflow-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(d.workflow,null,2)})]})]})}),e.jsx("style",{children:`
1510
+ `})]}):e.jsxs("div",{className:`nice-code-editor-ai nice-code-editor-ai--disabled ${f||""}`,style:h,children:[e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."}),e.jsx("textarea",{value:w,onChange:O=>z(O.target.value),placeholder:o,className:"nice-code-editor-ai__textarea"})]})}function ii(i){const r=i.value.substring(0,i.selectionStart).split(`
1511
+ `);return{line:r.length-1,column:r[r.length-1].length}}function Sa(i={}){const{config:a,context:r,existingRoles:t,existingVariables:n,onWorkflowGenerated:s,onError:l}=i,o=Q(),[f,h]=c.useState(!1),[y,w]=c.useState(null),[C,S]=c.useState([]),P=c.useRef(null),k=a||(o==null?void 0:o.config),$=c.useCallback(async v=>{var p,_,M;if(!k){const R="AI not configured";return l==null||l(R),{error:R}}h(!0);const x=performance.now();(p=P.current)==null||p.abort(),P.current=new AbortController;try{const R=G(k),T=[r,t!=null&&t.length?`Available roles: ${t.join(", ")}`:"",n!=null&&n.length?`Existing variables: ${n.join(", ")}`:""].filter(Boolean).join(`
1512
+ `),u=ae(pe,{description:v,context:T}),b=await R.chat({messages:[{role:"system",content:u.system},{role:"user",content:u.user}],temperature:.5,maxTokens:2048}),I=Fe(b),D={workflow:I||void 0,rawResponse:(M=(_=b.choices[0])==null?void 0:_.message)==null?void 0:M.content,latencyMs:performance.now()-x,error:I?void 0:"Failed to generate workflow",suggestions:ni(I)};return I&&(s==null||s(I)),w(D),S(J=>[...J.slice(-9),{request:v,result:D}]),D}catch(R){const T=R instanceof Error?R.message:"Workflow generation failed",u={error:T,latencyMs:performance.now()-x};return w(u),l==null||l(T),u}finally{h(!1)}},[k,r,t,n,s,l]),g=c.useCallback(async v=>{if(!k)return{error:"AI not configured"};h(!0);const x=performance.now();try{const _=await G(k).chat({messages:[{role:"system",content:"You are a workflow optimization expert. Analyze the following BPMN workflow and suggest improvements for efficiency, clarity, and error handling. Return the optimized workflow in JSON format with the same structure."},{role:"user",content:JSON.stringify(v,null,2)}],temperature:.4,maxTokens:2048});return{workflow:Fe(_)||void 0,latencyMs:performance.now()-x}}catch(p){return{error:p instanceof Error?p.message:"Optimization failed"}}finally{h(!1)}},[k]),d=c.useCallback(async(v,x)=>{var p,_;if(!k)return[];h(!0);try{const M=G(k),R=v.nodes.find(I=>I.id===x),b=(((_=(p=(await M.chat({messages:[{role:"system",content:'Given the current workflow state, suggest 2-3 possible next steps after the specified node. Return JSON array of nodes: [{ "id": string, "type": string, "label": string, "description": string }]'},{role:"user",content:`Workflow: ${v.name}
1513
+ Current node: ${(R==null?void 0:R.label)||x}
1514
+ Existing nodes: ${v.nodes.map(I=>I.label).join(", ")}`}],temperature:.6,maxTokens:512})).choices[0])==null?void 0:p.message)==null?void 0:_.content)||"").match(/\[[\s\S]*\]/);if(b)return JSON.parse(b[0])}catch{}finally{h(!1)}return[]},[k]),j=c.useCallback(async v=>{var x,p;if(!k)return[];h(!0);try{const T=(((p=(x=(await G(k).chat({messages:[{role:"system",content:'Analyze the BPMN workflow for potential issues. Check for: dead ends, unreachable nodes, missing error handling, infinite loops, unclear conditions, missing assignments. Return JSON array of issues: [{ "severity": "error"|"warning"|"info", "message": string, "nodeId": string? }]'},{role:"user",content:JSON.stringify(v,null,2)}],temperature:.3,maxTokens:1024})).choices[0])==null?void 0:x.message)==null?void 0:p.content)||"").match(/\[[\s\S]*\]/);if(T)return JSON.parse(T[0]).map(b=>`[${b.severity}] ${b.message}`)}catch{}finally{h(!1)}return[]},[k]),N=c.useCallback(()=>{w(null)},[]),m=c.useCallback(()=>{var v;(v=P.current)==null||v.abort(),h(!1)},[]);return c.useEffect(()=>()=>{var v;(v=P.current)==null||v.abort()},[]),{generateWorkflow:$,optimizeWorkflow:g,suggestNextStep:d,validateWorkflow:j,loading:f,lastResult:y,history:C,clearResults:N,abort:m,isConfigured:!!k}}function Fe(i){var a,r,t;try{const n=((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"",l=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,o=JSON.parse(l);if(o.nodes&&Array.isArray(o.nodes)){const f=o.nodes.map((h,y)=>({...h,id:h.id||`node_${y}`,position:h.position||ti(y,o.nodes.length)}));return{id:o.id||`workflow_${Date.now()}`,name:o.name||"Generated Workflow",description:o.description,version:o.version||"1.0",nodes:f,edges:o.edges||[],lanes:o.lanes,variables:o.variables,metadata:o.metadata}}}catch{}return null}function ti(i,a){const s=Math.floor(i/5);return{x:100+i%5*200,y:100+s*100}}function ni(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 si=["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 ci({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:l=!0,className:o,style:f,renderWorkflow:h}){const[y,w]=c.useState(""),[C,S]=c.useState([]),P=c.useRef(null),{generateWorkflow:k,validateWorkflow:$,loading:g,lastResult:d,isConfigured:j}=Sa({config:i,context:a,existingRoles:r,onWorkflowGenerated:t}),N=async()=>{!y.trim()||g||await k(y)},m=p=>{var _;w(p),(_=P.current)==null||_.focus()},v=async()=>{if(!(d!=null&&d.workflow))return;const p=await $(d.workflow);S(p)},x=()=>{if(!(d!=null&&d.workflow))return;const p=li(d.workflow),_=new Blob([p],{type:"application/xml"}),M=URL.createObjectURL(_),R=document.createElement("a");R.href=M,R.download=`${d.workflow.name.replace(/\s+/g,"_")}.bpmn`,R.click(),URL.revokeObjectURL(M)};return j?e.jsxs("div",{className:`nice-workflow-ai ${o||""}`,style:f,children:[e.jsxs("div",{className:"nice-workflow-ai__input-section",children:[e.jsx("textarea",{ref:P,value:y,onChange:p=>w(p.target.value),placeholder:n,className:"nice-workflow-ai__input",rows:3,disabled:g}),e.jsx("button",{type:"button",onClick:N,className:"nice-workflow-ai__submit",disabled:g||!y.trim(),children:g?e.jsx("span",{className:"nice-workflow-ai__spinner"}):"🔄 Generate Workflow"})]}),s&&e.jsxs("div",{className:"nice-workflow-ai__examples",children:[e.jsx("span",{className:"nice-workflow-ai__examples-label",children:"Try:"}),si.slice(0,3).map((p,_)=>e.jsx("button",{type:"button",className:"nice-workflow-ai__example",onClick:()=>m(p),children:p},_))]}),d&&e.jsx("div",{className:"nice-workflow-ai__result",children:d.error?e.jsx("div",{className:"nice-workflow-ai__error",children:d.error}):d.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:d.workflow.name}),d.workflow.description&&e.jsx("span",{className:"nice-workflow-ai__workflow-desc",children:d.workflow.description})]}),e.jsxs("div",{className:"nice-workflow-ai__result-meta",children:[e.jsxs("span",{className:"nice-workflow-ai__stat",children:[d.workflow.nodes.length," nodes"]}),e.jsxs("span",{className:"nice-workflow-ai__stat",children:[d.workflow.edges.length," connections"]}),d.latencyMs&&e.jsxs("span",{className:"nice-workflow-ai__latency",children:[Math.round(d.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-workflow-ai__actions",children:[e.jsx("button",{type:"button",onClick:()=>t==null?void 0:t(d.workflow),children:"✅ Use Workflow"}),e.jsx("button",{type:"button",onClick:v,children:"🔍 Validate"}),e.jsx("button",{type:"button",onClick:x,children:"📥 Export BPMN"})]}),C.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:C.map((p,_)=>e.jsx("li",{className:`nice-workflow-ai__issue nice-workflow-ai__issue--${p.startsWith("[error]")?"error":p.startsWith("[warning]")?"warning":"info"}`,children:p},_))})]}),l&&e.jsx("div",{className:"nice-workflow-ai__preview",children:h?h(d.workflow):e.jsx(oi,{workflow:d.workflow})}),d.suggestions&&d.suggestions.length>0&&e.jsxs("div",{className:"nice-workflow-ai__suggestions",children:[e.jsx("span",{className:"nice-workflow-ai__suggestions-title",children:"💡 Suggestions:"}),e.jsx("ul",{children:d.suggestions.map((p,_)=>e.jsx("li",{children:p},_))})]}),e.jsxs("details",{className:"nice-workflow-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(d.workflow,null,2)})]})]})}),e.jsx("style",{children:`
1489
1515
  .nice-workflow-ai {
1490
1516
  font-family: var(--nice-font-family, system-ui, sans-serif);
1491
1517
  }
@@ -1746,7 +1772,7 @@ Existing nodes: ${_.nodes.map(z=>z.label).join(", ")}`}],temperature:.6,maxToken
1746
1772
  color: var(--nice-error, #c62828);
1747
1773
  border-radius: var(--nice-radius-md, 6px);
1748
1774
  }
1749
- `})]}):e.jsx("div",{className:`nice-workflow-ai nice-workflow-ai--disabled ${c||""}`,style:g,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function Pt({workflow:i}){const a=r=>({start:"▶️",end:"⏹️",task:"📋",userTask:"👤",serviceTask:"⚙️",scriptTask:"📜","gateway-exclusive":"◇","gateway-parallel":"✚","gateway-inclusive":"○","event-timer":"⏰","event-message":"✉️","event-error":"⚠️"})[r]||"📋",t=r=>r==="start"?"var(--nice-success, #4caf50)":r==="end"?"var(--nice-danger, #f44336)":r.startsWith("gateway")?"var(--nice-warning, #ff9800)":r.startsWith("event")?"var(--nice-accent, #9c27b0)":"var(--nice-primary, #2196f3)";return e.jsxs("div",{className:"workflow-preview",children:[e.jsxs("div",{className:"workflow-preview__diagram",children:[i.nodes.map(r=>{var n,s;return e.jsxs("div",{className:`workflow-preview__node workflow-preview__node--${r.type.split("-")[0]}`,style:{left:(n=r.position)==null?void 0:n.x,top:(s=r.position)==null?void 0:s.y,borderColor:t(r.type)},children:[e.jsx("span",{className:"workflow-preview__node-icon",children:a(r.type)}),e.jsx("span",{className:"workflow-preview__node-label",children:r.label})]},r.id)}),e.jsxs("svg",{className:"workflow-preview__connections",children:[i.edges.map(r=>{const n=i.nodes.find(j=>j.id===r.source),s=i.nodes.find(j=>j.id===r.target);if(!(n!=null&&n.position)||!(s!=null&&s.position))return null;const m=n.position.x+60,c=n.position.y+20,g=s.position.x,f=s.position.y+20;return e.jsxs("g",{children:[e.jsx("line",{x1:m,y1:c,x2:g,y2:f,stroke:"var(--nice-text-secondary, #666)",strokeWidth:"2",markerEnd:"url(#arrowhead)"}),r.label&&e.jsx("text",{x:(m+g)/2,y:(c+f)/2-5,fontSize:"10",fill:"var(--nice-text-secondary, #666)",textAnchor:"middle",children:r.label})]},r.id)}),e.jsx("defs",{children:e.jsx("marker",{id:"arrowhead",markerWidth:"10",markerHeight:"7",refX:"9",refY:"3.5",orient:"auto",children:e.jsx("polygon",{points:"0 0, 10 3.5, 0 7",fill:"var(--nice-text-secondary, #666)"})})})]})]}),i.lanes&&i.lanes.length>0&&e.jsxs("div",{className:"workflow-preview__lanes",children:[e.jsx("span",{className:"workflow-preview__lanes-title",children:"Swimlanes:"}),i.lanes.map(r=>e.jsx("span",{className:"workflow-preview__lane",children:r.name},r.id))]}),e.jsx("style",{children:`
1775
+ `})]}):e.jsx("div",{className:`nice-workflow-ai nice-workflow-ai--disabled ${o||""}`,style:f,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function oi({workflow:i}){const a=t=>({start:"▶️",end:"⏹️",task:"📋",userTask:"👤",serviceTask:"⚙️",scriptTask:"📜","gateway-exclusive":"◇","gateway-parallel":"✚","gateway-inclusive":"○","event-timer":"⏰","event-message":"✉️","event-error":"⚠️"})[t]||"📋",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:a(t.type)}),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(y=>y.id===t.source),s=i.nodes.find(y=>y.id===t.target);if(!(n!=null&&n.position)||!(s!=null&&s.position))return null;const l=n.position.x+60,o=n.position.y+20,f=s.position.x,h=s.position.y+20;return e.jsxs("g",{children:[e.jsx("line",{x1:l,y1:o,x2:f,y2:h,stroke:"var(--nice-text-secondary, #666)",strokeWidth:"2",markerEnd:"url(#arrowhead)"}),t.label&&e.jsx("text",{x:(l+f)/2,y:(o+h)/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:`
1750
1776
  .workflow-preview {
1751
1777
  min-height: 200px;
1752
1778
  }
@@ -1835,21 +1861,21 @@ Existing nodes: ${_.nodes.map(z=>z.label).join(", ")}`}],temperature:.6,maxToken
1835
1861
  border-radius: var(--nice-radius-sm, 4px);
1836
1862
  font-size: 12px;
1837
1863
  }
1838
- `})]})}function $t(i){const a={start:"bpmn:startEvent",end:"bpmn:endEvent",task:"bpmn:task",userTask:"bpmn:userTask",serviceTask:"bpmn:serviceTask",scriptTask:"bpmn:scriptTask","gateway-exclusive":"bpmn:exclusiveGateway","gateway-parallel":"bpmn:parallelGateway","gateway-inclusive":"bpmn:inclusiveGateway"},t=i.nodes.map(n=>` <${a[n.type]||"bpmn:task"} id="${n.id}" name="${ge(n.label)}" />`).join(`
1839
- `),r=i.edges.map(n=>` <bpmn:sequenceFlow id="${n.id}" sourceRef="${n.source}" targetRef="${n.target}"${n.label?` name="${ge(n.label)}"`:""} />`).join(`
1864
+ `})]})}function li(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="${be(n.label)}" />`).join(`
1865
+ `),t=i.edges.map(n=>` <bpmn:sequenceFlow id="${n.id}" sourceRef="${n.source}" targetRef="${n.target}"${n.label?` name="${be(n.label)}"`:""} />`).join(`
1840
1866
  `);return`<?xml version="1.0" encoding="UTF-8"?>
1841
1867
  <bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL"
1842
1868
  xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
1843
1869
  id="${i.id}"
1844
1870
  targetNamespace="http://nice2dev.com/bpmn">
1845
- <bpmn:process id="Process_${i.id}" name="${ge(i.name)}" isExecutable="true">
1846
- ${t}
1871
+ <bpmn:process id="Process_${i.id}" name="${be(i.name)}" isExecutable="true">
1847
1872
  ${r}
1873
+ ${t}
1848
1874
  </bpmn:process>
1849
- </bpmn:definitions>`}function ge(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function fa(i={}){const{config:a,dataSources:t,context:r,onReportGenerated:n,onError:s}=i,m=X(),[c,g]=o.useState(!1),[f,j]=o.useState(null),[w,N]=o.useState([]),S=o.useRef(null),$=a||(m==null?void 0:m.config),k=o.useCallback(async p=>{var b,u,y;if(!$){const A="AI not configured";return s==null||s(A),{error:A}}g(!0);const _=performance.now();(b=S.current)==null||b.abort(),S.current=new AbortController;try{const A=G($),R=t?t.map(D=>`- ${D.name} (${D.id}): ${D.fields.join(", ")}`).join(`
1850
- `):void 0,l=Z(de,{description:p,data_sources:R,context:r}),x=await A.chat({messages:[{role:"system",content:l.system},{role:"user",content:l.user}],temperature:.5,maxTokens:2048}),M=It(x),z={layout:M||void 0,rawResponse:(y=(u=x.choices[0])==null?void 0:u.message)==null?void 0:y.content,latencyMs:performance.now()-_,error:M?void 0:"Failed to generate report layout",suggestions:zt(M)};return M&&(n==null||n(M)),j(z),N(D=>[...D.slice(-9),{request:p,result:z}]),z}catch(A){const R=A instanceof Error?A.message:"Report generation failed",l={error:R,latencyMs:performance.now()-_};return j(l),s==null||s(R),l}finally{g(!1)}},[$,t,r,n,s]),P=o.useCallback(async p=>{var _,b;if(!$)return[];g(!0);try{const R=(((b=(_=(await G($).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(l=>l.type).join(", ")}`}],temperature:.6,maxTokens:1024})).choices[0])==null?void 0:_.message)==null?void 0:b.content)||"").match(/\[[\s\S]*\]/);if(R)return JSON.parse(R[0])}catch{}finally{g(!1)}return[]},[$]),h=o.useCallback(async p=>{var _,b;if(!$)return null;g(!0);try{return((b=(_=(await G($).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:_.message)==null?void 0:b.content)||null}catch{return null}finally{g(!1)}},[$]),d=o.useCallback(async(p,_)=>{var b,u,y;if(!$)return"bar";try{const A=G($),R=p.slice(0,5),x=(y=(u=(b=(await A.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(R)}
1852
- Purpose: ${_}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:b.message)==null?void 0:u.content)==null?void 0:y.toLowerCase().trim();return["line","bar","pie","donut","area","column","scatter","combo","gauge","heatmap"].find(z=>x==null?void 0:x.includes(z))||"bar"}catch{return"bar"}},[$]),v=o.useCallback(()=>{j(null)},[]),C=o.useCallback(()=>{var p;(p=S.current)==null||p.abort(),g(!1)},[]);return o.useEffect(()=>()=>{var p;(p=S.current)==null||p.abort()},[]),{generateReport:k,suggestSections:P,generateSummary:h,suggestChartType:d,loading:c,lastResult:f,history:w,clearResults:v,abort:C,isConfigured:!!$}}function It(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.content)||"",m=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(m);if(c.sections&&Array.isArray(c.sections)){const g=c.sections.map((f,j)=>({...f,id:f.id||`section_${j}`,order:f.order??j,config:f.config||{}}));return{id:c.id||`report_${Date.now()}`,name:c.name||"Generated Report",description:c.description,orientation:c.orientation||"portrait",pageSize:c.pageSize||"A4",margins:c.margins||{top:20,right:20,bottom:20,left:20},sections:g,dataSources:c.dataSources,parameters:c.parameters,styles:c.styles}}}catch{}return null}function zt(i){if(!i)return[];const a=[],t=new Set(i.sections.map(r=>r.type));return t.has("summary")||a.push("Add an executive summary for quick insights"),t.has("kpi")||a.push("Include KPI cards for key metrics"),t.has("chart")||a.push("Add visualizations to make data more accessible"),t.has("footer")||a.push("Add a footer with page numbers and date"),i.sections.length>5&&!t.has("toc")&&a.push("Consider adding a table of contents"),a.slice(0,3)}const Lt=[{icon:"📊",name:"Sales Report",prompt:"Monthly sales report with revenue KPIs, sales by region chart, and top products table"},{icon:"📈",name:"Financial Summary",prompt:"Quarterly financial summary with P&L, cash flow chart, and expense breakdown"},{icon:"👥",name:"HR Dashboard",prompt:"Employee report with headcount KPIs, department breakdown, and turnover trends"},{icon:"📦",name:"Inventory Report",prompt:"Inventory status report with stock levels, low stock alerts, and turnover analysis"},{icon:"🎯",name:"KPI Dashboard",prompt:"Executive KPI dashboard with performance metrics, trends, and target comparison"}];function Ot({config:i,dataSources:a,context:t,onGenerate:r,placeholder:n='Describe the report you need... (e.g., "Monthly sales report with KPIs and charts")',showTemplates:s=!0,showPreview:m=!0,className:c,style:g,renderReport:f}){const[j,w]=o.useState(""),N=o.useRef(null),{generateReport:S,loading:$,lastResult:k,isConfigured:P}=fa({config:i,dataSources:a,context:t,onReportGenerated:r}),h=async()=>{!j.trim()||$||await S(j)},d=C=>{var p;w(C.prompt),(p=N.current)==null||p.focus()},v=()=>{if(!(k!=null&&k.layout))return;const C=JSON.stringify(k.layout,null,2),p=new Blob([C],{type:"application/json"}),_=URL.createObjectURL(p),b=document.createElement("a");b.href=_,b.download=`${k.layout.name.replace(/\s+/g,"_")}.json`,b.click(),URL.revokeObjectURL(_)};return P?e.jsxs("div",{className:`nice-report-ai ${c||""}`,style:g,children:[s&&e.jsx("div",{className:"nice-report-ai__templates",children:Lt.map((C,p)=>e.jsxs("button",{type:"button",className:"nice-report-ai__template",onClick:()=>d(C),children:[e.jsx("span",{className:"nice-report-ai__template-icon",children:C.icon}),e.jsx("span",{className:"nice-report-ai__template-name",children:C.name})]},p))}),e.jsxs("div",{className:"nice-report-ai__input-section",children:[e.jsx("textarea",{ref:N,value:j,onChange:C=>w(C.target.value),placeholder:n,className:"nice-report-ai__input",rows:3,disabled:$}),e.jsx("button",{type:"button",onClick:h,className:"nice-report-ai__submit",disabled:$||!j.trim(),children:$?e.jsx("span",{className:"nice-report-ai__spinner"}):"📄 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(C=>e.jsx("span",{className:"nice-report-ai__datasource",children:C.name},C.id))]}),k&&e.jsx("div",{className:"nice-report-ai__result",children:k.error?e.jsx("div",{className:"nice-report-ai__error",children:k.error}):k.layout&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-report-ai__result-header",children:[e.jsxs("div",{className:"nice-report-ai__report-info",children:[e.jsx("span",{className:"nice-report-ai__report-name",children:k.layout.name}),k.layout.description&&e.jsx("span",{className:"nice-report-ai__report-desc",children:k.layout.description})]}),e.jsxs("div",{className:"nice-report-ai__result-meta",children:[e.jsxs("span",{className:"nice-report-ai__stat",children:[k.layout.sections.length," sections"]}),e.jsxs("span",{className:"nice-report-ai__stat",children:[k.layout.pageSize," ",k.layout.orientation]}),k.latencyMs&&e.jsxs("span",{className:"nice-report-ai__latency",children:[Math.round(k.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-report-ai__actions",children:[e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r(k.layout),children:"✅ Use Report"}),e.jsx("button",{type:"button",onClick:v,children:"📥 Export JSON"})]}),e.jsxs("div",{className:"nice-report-ai__sections",children:[e.jsx("div",{className:"nice-report-ai__sections-title",children:"Report Structure:"}),e.jsx("div",{className:"nice-report-ai__sections-list",children:k.layout.sections.map((C,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:xa(C.type)}),e.jsx("span",{className:"nice-report-ai__section-type",children:C.type}),C.title&&e.jsx("span",{className:"nice-report-ai__section-title",children:C.title})]},C.id))})]}),m&&e.jsx("div",{className:"nice-report-ai__preview",children:f?f(k.layout):e.jsx(Et,{layout:k.layout})}),k.suggestions&&k.suggestions.length>0&&e.jsxs("div",{className:"nice-report-ai__suggestions",children:[e.jsx("span",{className:"nice-report-ai__suggestions-title",children:"💡 Suggestions:"}),e.jsx("ul",{children:k.suggestions.map((C,p)=>e.jsx("li",{children:C},p))})]}),e.jsxs("details",{className:"nice-report-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(k.layout,null,2)})]})]})}),e.jsx("style",{children:`
1875
+ </bpmn:definitions>`}function be(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Ta(i={}){const{config:a,dataSources:r,context:t,onReportGenerated:n,onError:s}=i,l=Q(),[o,f]=c.useState(!1),[h,y]=c.useState(null),[w,C]=c.useState([]),S=c.useRef(null),P=a||(l==null?void 0:l.config),k=c.useCallback(async m=>{var x,p,_;if(!P){const M="AI not configured";return s==null||s(M),{error:M}}f(!0);const v=performance.now();(x=S.current)==null||x.abort(),S.current=new AbortController;try{const M=G(P),R=r?r.map(D=>`- ${D.name} (${D.id}): ${D.fields.join(", ")}`).join(`
1876
+ `):void 0,T=ae(me,{description:m,data_sources:R,context:t}),u=await M.chat({messages:[{role:"system",content:T.system},{role:"user",content:T.user}],temperature:.5,maxTokens:2048}),b=di(u),I={layout:b||void 0,rawResponse:(_=(p=u.choices[0])==null?void 0:p.message)==null?void 0:_.content,latencyMs:performance.now()-v,error:b?void 0:"Failed to generate report layout",suggestions:ui(b)};return b&&(n==null||n(b)),y(I),C(D=>[...D.slice(-9),{request:m,result:I}]),I}catch(M){const R=M instanceof Error?M.message:"Report generation failed",T={error:R,latencyMs:performance.now()-v};return y(T),s==null||s(R),T}finally{f(!1)}},[P,r,t,n,s]),$=c.useCallback(async m=>{var v,x;if(!P)return[];f(!0);try{const R=(((x=(v=(await G(P).chat({messages:[{role:"system",content:"Given the existing report layout, suggest 2-3 additional sections that would enhance it. Return JSON array of sections with: id, type, title, order, config."},{role:"user",content:`Report: ${m.name}
1877
+ Existing sections: ${m.sections.map(T=>T.type).join(", ")}`}],temperature:.6,maxTokens:1024})).choices[0])==null?void 0:v.message)==null?void 0:x.content)||"").match(/\[[\s\S]*\]/);if(R)return JSON.parse(R[0])}catch{}finally{f(!1)}return[]},[P]),g=c.useCallback(async m=>{var v,x;if(!P)return null;f(!0);try{return((x=(v=(await G(P).chat({messages:[{role:"system",content:"Generate a concise executive summary (2-3 paragraphs) based on the provided data. Highlight key metrics, trends, and actionable insights."},{role:"user",content:JSON.stringify(m,null,2)}],temperature:.5,maxTokens:512})).choices[0])==null?void 0:v.message)==null?void 0:x.content)||null}catch{return null}finally{f(!1)}},[P]),d=c.useCallback(async(m,v)=>{var x,p,_;if(!P)return"bar";try{const M=G(P),R=m.slice(0,5),u=(_=(p=(x=(await M.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(R)}
1878
+ Purpose: ${v}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:x.message)==null?void 0:p.content)==null?void 0:_.toLowerCase().trim();return["line","bar","pie","donut","area","column","scatter","combo","gauge","heatmap"].find(I=>u==null?void 0:u.includes(I))||"bar"}catch{return"bar"}},[P]),j=c.useCallback(()=>{y(null)},[]),N=c.useCallback(()=>{var m;(m=S.current)==null||m.abort(),f(!1)},[]);return c.useEffect(()=>()=>{var m;(m=S.current)==null||m.abort()},[]),{generateReport:k,suggestSections:$,generateSummary:g,suggestChartType:d,loading:o,lastResult:h,history:w,clearResults:j,abort:N,isConfigured:!!P}}function di(i){var a,r,t;try{const n=((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"",l=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,o=JSON.parse(l);if(o.sections&&Array.isArray(o.sections)){const f=o.sections.map((h,y)=>({...h,id:h.id||`section_${y}`,order:h.order??y,config:h.config||{}}));return{id:o.id||`report_${Date.now()}`,name:o.name||"Generated Report",description:o.description,orientation:o.orientation||"portrait",pageSize:o.pageSize||"A4",margins:o.margins||{top:20,right:20,bottom:20,left:20},sections:f,dataSources:o.dataSources,parameters:o.parameters,styles:o.styles}}}catch{}return null}function ui(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 pi=[{icon:"📊",name:"Sales Report",prompt:"Monthly sales report with revenue KPIs, sales by region chart, and top products table"},{icon:"📈",name:"Financial Summary",prompt:"Quarterly financial summary with P&L, cash flow chart, and expense breakdown"},{icon:"👥",name:"HR Dashboard",prompt:"Employee report with headcount KPIs, department breakdown, and turnover trends"},{icon:"📦",name:"Inventory Report",prompt:"Inventory status report with stock levels, low stock alerts, and turnover analysis"},{icon:"🎯",name:"KPI Dashboard",prompt:"Executive KPI dashboard with performance metrics, trends, and target comparison"}];function mi({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:l=!0,className:o,style:f,renderReport:h}){const[y,w]=c.useState(""),C=c.useRef(null),{generateReport:S,loading:P,lastResult:k,isConfigured:$}=Ta({config:i,dataSources:a,context:r,onReportGenerated:t}),g=async()=>{!y.trim()||P||await S(y)},d=N=>{var m;w(N.prompt),(m=C.current)==null||m.focus()},j=()=>{if(!(k!=null&&k.layout))return;const N=JSON.stringify(k.layout,null,2),m=new Blob([N],{type:"application/json"}),v=URL.createObjectURL(m),x=document.createElement("a");x.href=v,x.download=`${k.layout.name.replace(/\s+/g,"_")}.json`,x.click(),URL.revokeObjectURL(v)};return $?e.jsxs("div",{className:`nice-report-ai ${o||""}`,style:f,children:[s&&e.jsx("div",{className:"nice-report-ai__templates",children:pi.map((N,m)=>e.jsxs("button",{type:"button",className:"nice-report-ai__template",onClick:()=>d(N),children:[e.jsx("span",{className:"nice-report-ai__template-icon",children:N.icon}),e.jsx("span",{className:"nice-report-ai__template-name",children:N.name})]},m))}),e.jsxs("div",{className:"nice-report-ai__input-section",children:[e.jsx("textarea",{ref:C,value:y,onChange:N=>w(N.target.value),placeholder:n,className:"nice-report-ai__input",rows:3,disabled:P}),e.jsx("button",{type:"button",onClick:g,className:"nice-report-ai__submit",disabled:P||!y.trim(),children:P?e.jsx("span",{className:"nice-report-ai__spinner"}):"📄 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(N=>e.jsx("span",{className:"nice-report-ai__datasource",children:N.name},N.id))]}),k&&e.jsx("div",{className:"nice-report-ai__result",children:k.error?e.jsx("div",{className:"nice-report-ai__error",children:k.error}):k.layout&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"nice-report-ai__result-header",children:[e.jsxs("div",{className:"nice-report-ai__report-info",children:[e.jsx("span",{className:"nice-report-ai__report-name",children:k.layout.name}),k.layout.description&&e.jsx("span",{className:"nice-report-ai__report-desc",children:k.layout.description})]}),e.jsxs("div",{className:"nice-report-ai__result-meta",children:[e.jsxs("span",{className:"nice-report-ai__stat",children:[k.layout.sections.length," sections"]}),e.jsxs("span",{className:"nice-report-ai__stat",children:[k.layout.pageSize," ",k.layout.orientation]}),k.latencyMs&&e.jsxs("span",{className:"nice-report-ai__latency",children:[Math.round(k.latencyMs),"ms"]})]})]}),e.jsxs("div",{className:"nice-report-ai__actions",children:[e.jsx("button",{type:"button",onClick:()=>t==null?void 0:t(k.layout),children:"✅ Use Report"}),e.jsx("button",{type:"button",onClick:j,children:"📥 Export JSON"})]}),e.jsxs("div",{className:"nice-report-ai__sections",children:[e.jsx("div",{className:"nice-report-ai__sections-title",children:"Report Structure:"}),e.jsx("div",{className:"nice-report-ai__sections-list",children:k.layout.sections.map((N,m)=>e.jsxs("div",{className:"nice-report-ai__section",children:[e.jsx("span",{className:"nice-report-ai__section-number",children:m+1}),e.jsx("span",{className:"nice-report-ai__section-icon",children:Aa(N.type)}),e.jsx("span",{className:"nice-report-ai__section-type",children:N.type}),N.title&&e.jsx("span",{className:"nice-report-ai__section-title",children:N.title})]},N.id))})]}),l&&e.jsx("div",{className:"nice-report-ai__preview",children:h?h(k.layout):e.jsx(fi,{layout:k.layout})}),k.suggestions&&k.suggestions.length>0&&e.jsxs("div",{className:"nice-report-ai__suggestions",children:[e.jsx("span",{className:"nice-report-ai__suggestions-title",children:"💡 Suggestions:"}),e.jsx("ul",{children:k.suggestions.map((N,m)=>e.jsx("li",{children:N},m))})]}),e.jsxs("details",{className:"nice-report-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(k.layout,null,2)})]})]})}),e.jsx("style",{children:`
1853
1879
  .nice-report-ai {
1854
1880
  font-family: var(--nice-font-family, system-ui, sans-serif);
1855
1881
  }
@@ -2157,7 +2183,7 @@ Purpose: ${_}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:b.messa
2157
2183
  color: var(--nice-error, #c62828);
2158
2184
  border-radius: var(--nice-radius-md, 6px);
2159
2185
  }
2160
- `})]}):e.jsx("div",{className:`nice-report-ai nice-report-ai--disabled ${c||""}`,style:g,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function xa(i){return{header:"📑",summary:"📝",kpi:"📈",table:"📋",chart:"📊",text:"📄",image:"🖼️",divider:"➖",spacer:"⬜",pageBreak:"📃",footer:"📜",toc:"📚",customBlock:"🧩"}[i]||"📄"}function Et({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:xa(a.type)}),e.jsx("span",{className:"report-preview__section-label",children:a.title||a.type})]},a.id))}),e.jsx("style",{children:`
2186
+ `})]}):e.jsx("div",{className:`nice-report-ai nice-report-ai--disabled ${o||""}`,style:f,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function Aa(i){return{header:"📑",summary:"📝",kpi:"📈",table:"📋",chart:"📊",text:"📄",image:"🖼️",divider:"➖",spacer:"⬜",pageBreak:"📃",footer:"📜",toc:"📚",customBlock:"🧩"}[i]||"📄"}function fi({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:Aa(a.type)}),e.jsx("span",{className:"report-preview__section-label",children:a.title||a.type})]},a.id))}),e.jsx("style",{children:`
2161
2187
  .report-preview {
2162
2188
  display: flex;
2163
2189
  justify-content: center;
@@ -2236,19 +2262,19 @@ Purpose: ${_}`}],temperature:.3,maxTokens:20})).choices[0])==null?void 0:b.messa
2236
2262
  text-overflow: ellipsis;
2237
2263
  white-space: nowrap;
2238
2264
  }
2239
- `})]})}function ba(i={}){const{config:a,generateDarkMode:t=!0,onThemeGenerated:r,onError:n}=i,s=X(),[m,c]=o.useState(!1),[g,f]=o.useState(null),j=o.useRef(null),w=a||(s==null?void 0:s.config),N=o.useCallback(async d=>{var C,p,_,b;if(!w){const u="AI not configured";return n==null||n(u),{error:u}}c(!0);const v=performance.now();(C=j.current)==null||C.abort(),j.current=new AbortController;try{const u=G(w);let y="";switch(d.type){case"description":y=d.value;break;case"brand":y=`Create a theme for "${d.value.name}"${d.value.industry?` in the ${d.value.industry} industry`:""}${(p=d.value.keywords)!=null&&p.length?`. Keywords: ${d.value.keywords.join(", ")}`:""}`;break;case"colors":y=`Create a theme based on primary color ${d.value.primary}${d.value.secondary?` and secondary color ${d.value.secondary}`:""}`;break;case"image":y="Extract colors and create a theme from the provided image palette";break}const A=Z(ue,{description:y,generate_dark_mode:t?"true":"false"}),R=await u.chat({messages:[{role:"system",content:A.system},{role:"user",content:A.user}],temperature:.6,maxTokens:2048}),l=Ee(R),x={theme:l.light||void 0,darkTheme:l.dark||void 0,rawResponse:(b=(_=R.choices[0])==null?void 0:_.message)==null?void 0:b.content,latencyMs:performance.now()-v,error:l.light?void 0:"Failed to generate theme",suggestions:Dt(l.light)};return l.light&&(r==null||r(l.light,l.dark??void 0)),f(x),x}catch(u){const y=u instanceof Error?u.message:"Theme generation failed",A={error:y,latencyMs:performance.now()-v};return f(A),n==null||n(y),A}finally{c(!1)}},[w,t,r,n]),S=o.useCallback(async(d,v)=>{if(!w)return null;c(!0);try{const p=await G(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:
2265
+ `})]})}function Ra(i={}){const{config:a,generateDarkMode:r=!0,onThemeGenerated:t,onError:n}=i,s=Q(),[l,o]=c.useState(!1),[f,h]=c.useState(null),y=c.useRef(null),w=a||(s==null?void 0:s.config),C=c.useCallback(async d=>{var N,m,v,x;if(!w){const p="AI not configured";return n==null||n(p),{error:p}}o(!0);const j=performance.now();(N=y.current)==null||N.abort(),y.current=new AbortController;try{const p=G(w);let _="";switch(d.type){case"description":_=d.value;break;case"brand":_=`Create a theme for "${d.value.name}"${d.value.industry?` in the ${d.value.industry} industry`:""}${(m=d.value.keywords)!=null&&m.length?`. Keywords: ${d.value.keywords.join(", ")}`:""}`;break;case"colors":_=`Create a theme based on primary color ${d.value.primary}${d.value.secondary?` and secondary color ${d.value.secondary}`:""}`;break;case"image":_="Extract colors and create a theme from the provided image palette";break}const M=ae(fe,{description:_,generate_dark_mode:r?"true":"false"}),R=await p.chat({messages:[{role:"system",content:M.system},{role:"user",content:M.user}],temperature:.6,maxTokens:2048}),T=Je(R),u={theme:T.light||void 0,darkTheme:T.dark||void 0,rawResponse:(x=(v=R.choices[0])==null?void 0:v.message)==null?void 0:x.content,latencyMs:performance.now()-j,error:T.light?void 0:"Failed to generate theme",suggestions:hi(T.light)};return T.light&&(t==null||t(T.light,T.dark??void 0)),h(u),u}catch(p){const _=p instanceof Error?p.message:"Theme generation failed",M={error:_,latencyMs:performance.now()-j};return h(M),n==null||n(_),M}finally{o(!1)}},[w,r,t,n]),S=c.useCallback(async(d,j)=>{if(!w)return null;o(!0);try{const m=await G(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
2266
  ${JSON.stringify(d,null,2)}
2241
2267
 
2242
- Adjustments: ${v}`}],temperature:.4,maxTokens:2048});return Ee(p).light||null}catch{return null}finally{c(!1)}},[w]),$=o.useCallback(d=>{const v=[];return v.push(" /* Colors */"),Object.entries(d.colors).forEach(([C,p])=>{v.push(` --nice-${xe(C)}: ${p};`)}),v.push(`
2243
- /* Typography */`),Object.entries(d.typography).forEach(([C,p])=>{v.push(` --nice-${xe(C)}: ${p};`)}),v.push(`
2244
- /* Spacing */`),Object.entries(d.spacing).forEach(([C,p])=>{v.push(` --nice-spacing-${C}: ${p};`)}),v.push(`
2245
- /* Border Radius */`),Object.entries(d.borderRadius).forEach(([C,p])=>{v.push(` --nice-radius-${C}: ${p};`)}),v.push(`
2246
- /* Shadows */`),Object.entries(d.shadows).forEach(([C,p])=>{v.push(` --nice-shadow-${C}: ${p};`)}),v.push(`
2247
- /* Animations */`),Object.entries(d.animations).forEach(([C,p])=>{v.push(` --nice-${xe(C)}: ${p};`)}),`:root {
2248
- ${v.join(`
2268
+ Adjustments: ${j}`}],temperature:.4,maxTokens:2048});return Je(m).light||null}catch{return null}finally{o(!1)}},[w]),P=c.useCallback(d=>{const j=[];return j.push(" /* Colors */"),Object.entries(d.colors).forEach(([N,m])=>{j.push(` --nice-${ve(N)}: ${m};`)}),j.push(`
2269
+ /* Typography */`),Object.entries(d.typography).forEach(([N,m])=>{j.push(` --nice-${ve(N)}: ${m};`)}),j.push(`
2270
+ /* Spacing */`),Object.entries(d.spacing).forEach(([N,m])=>{j.push(` --nice-spacing-${N}: ${m};`)}),j.push(`
2271
+ /* Border Radius */`),Object.entries(d.borderRadius).forEach(([N,m])=>{j.push(` --nice-radius-${N}: ${m};`)}),j.push(`
2272
+ /* Shadows */`),Object.entries(d.shadows).forEach(([N,m])=>{j.push(` --nice-shadow-${N}: ${m};`)}),j.push(`
2273
+ /* Animations */`),Object.entries(d.animations).forEach(([N,m])=>{j.push(` --nice-${ve(N)}: ${m};`)}),`:root {
2274
+ ${j.join(`
2249
2275
  `)}
2250
- }`},[]),k=o.useCallback(d=>{const v={theme:{extend:{colors:{primary:{DEFAULT:d.colors.primary,light:d.colors.primaryLight,dark:d.colors.primaryDark},secondary:{DEFAULT:d.colors.secondary,light:d.colors.secondaryLight,dark:d.colors.secondaryDark},accent:d.colors.accent,success:d.colors.success,warning:d.colors.warning,error:d.colors.error,info:d.colors.info},fontFamily:{sans:[d.typography.fontFamily],mono:[d.typography.fontFamilyMono]},borderRadius:d.borderRadius,boxShadow:d.shadows}}};return`// tailwind.config.js
2251
- module.exports = ${JSON.stringify(v,null,2)}`},[]),P=o.useCallback(()=>{f(null)},[]),h=o.useCallback(()=>{var d;(d=j.current)==null||d.abort(),c(!1)},[]);return o.useEffect(()=>()=>{var d;(d=j.current)==null||d.abort()},[]),{generateTheme:N,adjustTheme:S,toCSSVariables:$,toTailwindConfig:k,loading:m,lastResult:g,clearResults:P,abort:h,isConfigured:!!w}}function Ee(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.content)||"",m=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(m);if(c.light||c.theme)return{light:fe(c.light||c.theme),dark:c.dark?fe(c.dark):null};if(c.colors)return{light:fe(c),dark:null}}catch{}return{light:null,dark:null}}function fe(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 Dt(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 xe(i){return i.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}const Bt=[{icon:"🏢",name:"Corporate",prompt:"Professional corporate theme with blue and gray tones"},{icon:"🎨",name:"Creative",prompt:"Vibrant creative agency theme with bold colors"},{icon:"🌿",name:"Natural",prompt:"Organic natural theme with earth tones and greens"},{icon:"🌙",name:"Dark Pro",prompt:"Modern dark theme for developer tools"},{icon:"🍬",name:"Playful",prompt:"Fun playful theme with candy colors for kids"},{icon:"💎",name:"Luxury",prompt:"Elegant luxury brand theme with gold accents"}];function Ft({config:i,generateDarkMode:a=!0,onGenerate:t,showPresets:r=!0,showPreview:n=!0,className:s,style:m}){const[c,g]=o.useState("description"),[f,j]=o.useState(""),[w,N]=o.useState(""),[S,$]=o.useState(""),[k,P]=o.useState("var(--nice-primary, #0066cc)"),[h,d]=o.useState("light"),{generateTheme:v,toCSSVariables:C,toTailwindConfig:p,loading:_,lastResult:b,isConfigured:u}=ba({config:i,generateDarkMode:a,onThemeGenerated:t}),y=async()=>{if(_)return;let M;switch(c){case"brand":if(!w.trim())return;M={type:"brand",value:{name:w,industry:S||void 0}};break;case"colors":M={type:"colors",value:{primary:k}};break;default:if(!f.trim())return;M={type:"description",value:f}}await v(M)},A=M=>{g("description"),j(M.prompt)},R=()=>{if(!(b!=null&&b.theme))return;const M=C(b.theme),z=new Blob([M],{type:"text/css"}),D=URL.createObjectURL(z),J=document.createElement("a");J.href=D,J.download=`${b.theme.name.replace(/\s+/g,"-").toLowerCase()}.css`,J.click(),URL.revokeObjectURL(D)},l=()=>{if(!(b!=null&&b.theme))return;const M=p(b.theme),z=new Blob([M],{type:"text/javascript"}),D=URL.createObjectURL(z),J=document.createElement("a");J.href=D,J.download="tailwind.config.js",J.click(),URL.revokeObjectURL(D)},x=h==="dark"&&(b!=null&&b.darkTheme)?b.darkTheme:b==null?void 0:b.theme;return u?e.jsxs("div",{className:`nice-theme-ai ${s||""}`,style:m,children:[r&&e.jsx("div",{className:"nice-theme-ai__presets",children:Bt.map((M,z)=>e.jsxs("button",{type:"button",className:"nice-theme-ai__preset",onClick:()=>A(M),children:[e.jsx("span",{className:"nice-theme-ai__preset-icon",children:M.icon}),e.jsx("span",{className:"nice-theme-ai__preset-name",children:M.name})]},z))}),e.jsxs("div",{className:"nice-theme-ai__tabs",children:[e.jsx("button",{type:"button",className:`nice-theme-ai__tab ${c==="description"?"nice-theme-ai__tab--active":""}`,onClick:()=>g("description"),children:"📝 Description"}),e.jsx("button",{type:"button",className:`nice-theme-ai__tab ${c==="brand"?"nice-theme-ai__tab--active":""}`,onClick:()=>g("brand"),children:"🏷️ Brand"}),e.jsx("button",{type:"button",className:`nice-theme-ai__tab ${c==="colors"?"nice-theme-ai__tab--active":""}`,onClick:()=>g("colors"),children:"🎨 Colors"})]}),e.jsxs("div",{className:"nice-theme-ai__input-section",children:[c==="description"&&e.jsx("textarea",{value:f,onChange:M=>j(M.target.value),placeholder:"Describe the theme you want... (e.g., 'Modern tech startup with blue and green')",className:"nice-theme-ai__textarea",rows:3,disabled:_}),c==="brand"&&e.jsxs("div",{className:"nice-theme-ai__brand-inputs",children:[e.jsx("input",{type:"text",value:w,onChange:M=>N(M.target.value),placeholder:"Brand name",className:"nice-theme-ai__input",disabled:_}),e.jsx("input",{type:"text",value:S,onChange:M=>$(M.target.value),placeholder:"Industry (optional)",className:"nice-theme-ai__input",disabled:_})]}),c==="colors"&&e.jsx("div",{className:"nice-theme-ai__color-input",children:e.jsxs("label",{children:["Primary Color:",e.jsx("input",{type:"color",value:k,onChange:M=>P(M.target.value),className:"nice-theme-ai__color-picker",disabled:_}),e.jsx("span",{className:"nice-theme-ai__color-value",children:k})]})}),e.jsx("button",{type:"button",onClick:y,className:"nice-theme-ai__submit",disabled:_,children:_?e.jsx("span",{className:"nice-theme-ai__spinner"}):"✨ Generate Theme"})]}),b&&x&&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:x.name}),x.description&&e.jsx("span",{className:"nice-theme-ai__theme-desc",children:x.description})]}),e.jsxs("div",{className:"nice-theme-ai__actions",children:[b.darkTheme&&e.jsxs("div",{className:"nice-theme-ai__mode-toggle",children:[e.jsx("button",{type:"button",className:h==="light"?"active":"",onClick:()=>d("light"),children:"☀️"}),e.jsx("button",{type:"button",className:h==="dark"?"active":"",onClick:()=>d("dark"),children:"🌙"})]}),e.jsx("button",{type:"button",onClick:R,children:"📥 CSS"}),e.jsx("button",{type:"button",onClick:l,children:"📥 Tailwind"})]})]}),n&&e.jsx(Jt,{theme:x}),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(x.colors).map(([M,z])=>e.jsxs("div",{className:"nice-theme-ai__color",children:[e.jsx("div",{className:"nice-theme-ai__color-swatch",style:{backgroundColor:z}}),e.jsx("span",{className:"nice-theme-ai__color-name",children:M}),e.jsx("span",{className:"nice-theme-ai__color-hex",children:z})]},M))})]}),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:x.typography.fontFamily},children:[e.jsx("p",{style:{fontSize:x.typography.fontSize3xl,fontWeight:x.typography.fontWeightBold},children:"Heading 1"}),e.jsx("p",{style:{fontSize:x.typography.fontSizeLg},children:"Body text: The quick brown fox jumps over the lazy dog."}),e.jsx("p",{style:{fontFamily:x.typography.fontFamilyMono,fontSize:x.typography.fontSizeSm},children:'const code = "Monospace font"'})]})]})]}),e.jsx("style",{children:`
2276
+ }`},[]),k=c.useCallback(d=>{const j={theme:{extend:{colors:{primary:{DEFAULT:d.colors.primary,light:d.colors.primaryLight,dark:d.colors.primaryDark},secondary:{DEFAULT:d.colors.secondary,light:d.colors.secondaryLight,dark:d.colors.secondaryDark},accent:d.colors.accent,success:d.colors.success,warning:d.colors.warning,error:d.colors.error,info:d.colors.info},fontFamily:{sans:[d.typography.fontFamily],mono:[d.typography.fontFamilyMono]},borderRadius:d.borderRadius,boxShadow:d.shadows}}};return`// tailwind.config.js
2277
+ module.exports = ${JSON.stringify(j,null,2)}`},[]),$=c.useCallback(()=>{h(null)},[]),g=c.useCallback(()=>{var d;(d=y.current)==null||d.abort(),o(!1)},[]);return c.useEffect(()=>()=>{var d;(d=y.current)==null||d.abort()},[]),{generateTheme:C,adjustTheme:S,toCSSVariables:P,toTailwindConfig:k,loading:l,lastResult:f,clearResults:$,abort:g,isConfigured:!!w}}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)||"",l=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,o=JSON.parse(l);if(o.light||o.theme)return{light:xe(o.light||o.theme),dark:o.dark?xe(o.dark):null};if(o.colors)return{light:xe(o),dark:null}}catch{}return{light:null,dark:null}}function xe(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 hi(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 ve(i){return i.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}const gi=[{icon:"🏢",name:"Corporate",prompt:"Professional corporate theme with blue and gray tones"},{icon:"🎨",name:"Creative",prompt:"Vibrant creative agency theme with bold colors"},{icon:"🌿",name:"Natural",prompt:"Organic natural theme with earth tones and greens"},{icon:"🌙",name:"Dark Pro",prompt:"Modern dark theme for developer tools"},{icon:"🍬",name:"Playful",prompt:"Fun playful theme with candy colors for kids"},{icon:"💎",name:"Luxury",prompt:"Elegant luxury brand theme with gold accents"}];function yi({config:i,generateDarkMode:a=!0,onGenerate:r,showPresets:t=!0,showPreview:n=!0,className:s,style:l}){const[o,f]=c.useState("description"),[h,y]=c.useState(""),[w,C]=c.useState(""),[S,P]=c.useState(""),[k,$]=c.useState("var(--nice-primary, #0066cc)"),[g,d]=c.useState("light"),{generateTheme:j,toCSSVariables:N,toTailwindConfig:m,loading:v,lastResult:x,isConfigured:p}=Ra({config:i,generateDarkMode:a,onThemeGenerated:r}),_=async()=>{if(v)return;let b;switch(o){case"brand":if(!w.trim())return;b={type:"brand",value:{name:w,industry:S||void 0}};break;case"colors":b={type:"colors",value:{primary:k}};break;default:if(!h.trim())return;b={type:"description",value:h}}await j(b)},M=b=>{f("description"),y(b.prompt)},R=()=>{if(!(x!=null&&x.theme))return;const b=N(x.theme),I=new Blob([b],{type:"text/css"}),D=URL.createObjectURL(I),J=document.createElement("a");J.href=D,J.download=`${x.theme.name.replace(/\s+/g,"-").toLowerCase()}.css`,J.click(),URL.revokeObjectURL(D)},T=()=>{if(!(x!=null&&x.theme))return;const b=m(x.theme),I=new Blob([b],{type:"text/javascript"}),D=URL.createObjectURL(I),J=document.createElement("a");J.href=D,J.download="tailwind.config.js",J.click(),URL.revokeObjectURL(D)},u=g==="dark"&&(x!=null&&x.darkTheme)?x.darkTheme:x==null?void 0:x.theme;return p?e.jsxs("div",{className:`nice-theme-ai ${s||""}`,style:l,children:[t&&e.jsx("div",{className:"nice-theme-ai__presets",children:gi.map((b,I)=>e.jsxs("button",{type:"button",className:"nice-theme-ai__preset",onClick:()=>M(b),children:[e.jsx("span",{className:"nice-theme-ai__preset-icon",children:b.icon}),e.jsx("span",{className:"nice-theme-ai__preset-name",children:b.name})]},I))}),e.jsxs("div",{className:"nice-theme-ai__tabs",children:[e.jsx("button",{type:"button",className:`nice-theme-ai__tab ${o==="description"?"nice-theme-ai__tab--active":""}`,onClick:()=>f("description"),children:"📝 Description"}),e.jsx("button",{type:"button",className:`nice-theme-ai__tab ${o==="brand"?"nice-theme-ai__tab--active":""}`,onClick:()=>f("brand"),children:"🏷️ Brand"}),e.jsx("button",{type:"button",className:`nice-theme-ai__tab ${o==="colors"?"nice-theme-ai__tab--active":""}`,onClick:()=>f("colors"),children:"🎨 Colors"})]}),e.jsxs("div",{className:"nice-theme-ai__input-section",children:[o==="description"&&e.jsx("textarea",{value:h,onChange:b=>y(b.target.value),placeholder:"Describe the theme you want... (e.g., 'Modern tech startup with blue and green')",className:"nice-theme-ai__textarea",rows:3,disabled:v}),o==="brand"&&e.jsxs("div",{className:"nice-theme-ai__brand-inputs",children:[e.jsx("input",{type:"text",value:w,onChange:b=>C(b.target.value),placeholder:"Brand name",className:"nice-theme-ai__input",disabled:v}),e.jsx("input",{type:"text",value:S,onChange:b=>P(b.target.value),placeholder:"Industry (optional)",className:"nice-theme-ai__input",disabled:v})]}),o==="colors"&&e.jsx("div",{className:"nice-theme-ai__color-input",children:e.jsxs("label",{children:["Primary Color:",e.jsx("input",{type:"color",value:k,onChange:b=>$(b.target.value),className:"nice-theme-ai__color-picker",disabled:v}),e.jsx("span",{className:"nice-theme-ai__color-value",children:k})]})}),e.jsx("button",{type:"button",onClick:_,className:"nice-theme-ai__submit",disabled:v,children:v?e.jsx("span",{className:"nice-theme-ai__spinner"}):"✨ Generate Theme"})]}),x&&u&&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:u.name}),u.description&&e.jsx("span",{className:"nice-theme-ai__theme-desc",children:u.description})]}),e.jsxs("div",{className:"nice-theme-ai__actions",children:[x.darkTheme&&e.jsxs("div",{className:"nice-theme-ai__mode-toggle",children:[e.jsx("button",{type:"button",className:g==="light"?"active":"",onClick:()=>d("light"),children:"☀️"}),e.jsx("button",{type:"button",className:g==="dark"?"active":"",onClick:()=>d("dark"),children:"🌙"})]}),e.jsx("button",{type:"button",onClick:R,children:"📥 CSS"}),e.jsx("button",{type:"button",onClick:T,children:"📥 Tailwind"})]})]}),n&&e.jsx(bi,{theme:u}),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(u.colors).map(([b,I])=>e.jsxs("div",{className:"nice-theme-ai__color",children:[e.jsx("div",{className:"nice-theme-ai__color-swatch",style:{backgroundColor:I}}),e.jsx("span",{className:"nice-theme-ai__color-name",children:b}),e.jsx("span",{className:"nice-theme-ai__color-hex",children:I})]},b))})]}),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:u.typography.fontFamily},children:[e.jsx("p",{style:{fontSize:u.typography.fontSize3xl,fontWeight:u.typography.fontWeightBold},children:"Heading 1"}),e.jsx("p",{style:{fontSize:u.typography.fontSizeLg},children:"Body text: The quick brown fox jumps over the lazy dog."}),e.jsx("p",{style:{fontFamily:u.typography.fontFamilyMono,fontSize:u.typography.fontSizeSm},children:'const code = "Monospace font"'})]})]})]}),e.jsx("style",{children:`
2252
2278
  .nice-theme-ai {
2253
2279
  font-family: var(--nice-font-family, system-ui, sans-serif);
2254
2280
  }
@@ -2519,7 +2545,7 @@ module.exports = ${JSON.stringify(v,null,2)}`},[]),P=o.useCallback(()=>{f(null)}
2519
2545
  .nice-theme-ai__typography {
2520
2546
  margin-top: var(--nice-space-5, 20px);
2521
2547
  }
2522
- `})]}):e.jsx("div",{className:`nice-theme-ai nice-theme-ai--disabled ${s||""}`,style:m,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function Jt({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:`
2548
+ `})]}):e.jsx("div",{className:`nice-theme-ai nice-theme-ai--disabled ${s||""}`,style:l,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function bi({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:`
2523
2549
  .theme-preview {
2524
2550
  background: var(--preview-bg);
2525
2551
  border: 1px solid var(--preview-border);
@@ -2565,7 +2591,7 @@ module.exports = ${JSON.stringify(v,null,2)}`},[]),P=o.useCallback(()=>{f(null)}
2565
2591
  cursor: text;
2566
2592
  width: 150px;
2567
2593
  }
2568
- `})]})}function va(i={}){const{config:a,targetDevice:t="responsive",onLayoutGenerated:r,onError:n}=i,s=X(),[m,c]=o.useState(!1),[g,f]=o.useState(null),j=o.useRef(null),w=a||(s==null?void 0:s.config),N=o.useCallback(async(h,d)=>{var C,p,_;if(!w){const b="AI not configured";return n==null||n(b),{error:b}}c(!0);const v=performance.now();(C=j.current)==null||C.abort(),j.current=new AbortController;try{const b=G(w),u=`You are a UI layout expert. Generate a responsive layout based on the description.
2594
+ `})]})}function Ma(i={}){const{config:a,targetDevice:r="responsive",onLayoutGenerated:t,onError:n}=i,s=Q(),[l,o]=c.useState(!1),[f,h]=c.useState(null),y=c.useRef(null),w=a||(s==null?void 0:s.config),C=c.useCallback(async(g,d)=>{var N,m,v;if(!w){const x="AI not configured";return n==null||n(x),{error:x}}o(!0);const j=performance.now();(N=y.current)==null||N.abort(),y.current=new AbortController;try{const x=G(w),p=`You are a UI layout expert. Generate a responsive layout based on the description.
2569
2595
  Return JSON with this structure:
2570
2596
  {
2571
2597
  "id": "unique_id",
@@ -2600,45 +2626,45 @@ Return JSON with this structure:
2600
2626
  "xl": "1280px",
2601
2627
  "2xl": "1536px"
2602
2628
  }
2603
- }`,y=await b.chat({messages:[{role:"system",content:u},{role:"user",content:`Create a ${t} layout: ${h}${d?` (type: ${d})`:""}`}],temperature:.5,maxTokens:2048}),A=qt(y),R={layout:A||void 0,rawResponse:(_=(p=y.choices[0])==null?void 0:p.message)==null?void 0:_.content,latencyMs:performance.now()-v,error:A?void 0:"Failed to generate layout",suggestions:Ut(A)};return A&&(r==null||r(A)),f(R),R}catch(b){const u=b instanceof Error?b.message:"Layout generation failed",y={error:u,latencyMs:performance.now()-v};return f(y),n==null||n(u),y}finally{c(!1)}},[w,t,r,n]),S=o.useCallback(h=>{let d=`.${h.id} {
2604
- `;if(d+=` display: ${h.container.direction==="grid"?"grid":"flex"};
2605
- `,h.container.direction==="grid"){if(h.container.gridColumns){const v=typeof h.container.gridColumns=="number"?`repeat(${h.container.gridColumns}, 1fr)`:h.container.gridColumns;d+=` grid-template-columns: ${v};
2606
- `}h.container.gridRows&&(d+=` grid-template-rows: ${h.container.gridRows};
2607
- `)}else d+=` flex-direction: ${h.container.direction};
2608
- `,h.container.wrap&&(d+=` flex-wrap: wrap;
2609
- `);return h.container.gap&&(d+=` gap: ${h.container.gap};
2610
- `),h.container.padding&&(d+=` padding: ${h.container.padding};
2611
- `),h.container.align&&(d+=` align-items: ${h.container.align};
2612
- `),h.container.justify&&(d+=` justify-content: ${{start:"flex-start",end:"flex-end",center:"center",between:"space-between",around:"space-around",evenly:"space-evenly"}[h.container.justify]||h.container.justify};
2629
+ }`,_=await x.chat({messages:[{role:"system",content:p},{role:"user",content:`Create a ${r} layout: ${g}${d?` (type: ${d})`:""}`}],temperature:.5,maxTokens:2048}),M=xi(_),R={layout:M||void 0,rawResponse:(v=(m=_.choices[0])==null?void 0:m.message)==null?void 0:v.content,latencyMs:performance.now()-j,error:M?void 0:"Failed to generate layout",suggestions:vi(M)};return M&&(t==null||t(M)),h(R),R}catch(x){const p=x instanceof Error?x.message:"Layout generation failed",_={error:p,latencyMs:performance.now()-j};return h(_),n==null||n(p),_}finally{o(!1)}},[w,r,t,n]),S=c.useCallback(g=>{let d=`.${g.id} {
2630
+ `;if(d+=` display: ${g.container.direction==="grid"?"grid":"flex"};
2631
+ `,g.container.direction==="grid"){if(g.container.gridColumns){const j=typeof g.container.gridColumns=="number"?`repeat(${g.container.gridColumns}, 1fr)`:g.container.gridColumns;d+=` grid-template-columns: ${j};
2632
+ `}g.container.gridRows&&(d+=` grid-template-rows: ${g.container.gridRows};
2633
+ `)}else d+=` flex-direction: ${g.container.direction};
2634
+ `,g.container.wrap&&(d+=` flex-wrap: wrap;
2635
+ `);return g.container.gap&&(d+=` gap: ${g.container.gap};
2636
+ `),g.container.padding&&(d+=` padding: ${g.container.padding};
2637
+ `),g.container.align&&(d+=` align-items: ${g.container.align};
2638
+ `),g.container.justify&&(d+=` justify-content: ${{start:"flex-start",end:"flex-end",center:"center",between:"space-between",around:"space-around",evenly:"space-evenly"}[g.container.justify]||g.container.justify};
2613
2639
  `),d+=`}
2614
2640
 
2615
- `,h.regions.forEach(v=>{var C,p,_,b,u,y;d+=`.${h.id}__${v.id} {
2616
- `,(C=v.position)!=null&&C.gridColumn&&(d+=` grid-column: ${v.position.gridColumn};
2617
- `),(p=v.position)!=null&&p.gridRow&&(d+=` grid-row: ${v.position.gridRow};
2618
- `),(_=v.size)!=null&&_.width&&(d+=` width: ${v.size.width};
2619
- `),(b=v.size)!=null&&b.height&&(d+=` height: ${v.size.height};
2620
- `),(u=v.size)!=null&&u.minWidth&&(d+=` min-width: ${v.size.minWidth};
2621
- `),(y=v.size)!=null&&y.maxWidth&&(d+=` max-width: ${v.size.maxWidth};
2641
+ `,g.regions.forEach(j=>{var N,m,v,x,p,_;d+=`.${g.id}__${j.id} {
2642
+ `,(N=j.position)!=null&&N.gridColumn&&(d+=` grid-column: ${j.position.gridColumn};
2643
+ `),(m=j.position)!=null&&m.gridRow&&(d+=` grid-row: ${j.position.gridRow};
2644
+ `),(v=j.size)!=null&&v.width&&(d+=` width: ${j.size.width};
2645
+ `),(x=j.size)!=null&&x.height&&(d+=` height: ${j.size.height};
2646
+ `),(p=j.size)!=null&&p.minWidth&&(d+=` min-width: ${j.size.minWidth};
2647
+ `),(_=j.size)!=null&&_.maxWidth&&(d+=` max-width: ${j.size.maxWidth};
2622
2648
  `),d+=`}
2623
2649
 
2624
- `}),h.breakpoints&&Object.entries(h.breakpoints).forEach(([v,C])=>{const p=h.regions.filter(_=>{var b;return(b=_.responsive)==null?void 0:b[v]});p.length>0&&(d+=`@media (max-width: ${C}) {
2625
- `,p.forEach(_=>{var u,y;const b=_.responsive[v];d+=` .${h.id}__${_.id} {
2626
- `,(u=b.size)!=null&&u.width&&(d+=` width: ${b.size.width};
2627
- `),(y=b.size)!=null&&y.height&&(d+=` height: ${b.size.height};
2650
+ `}),g.breakpoints&&Object.entries(g.breakpoints).forEach(([j,N])=>{const m=g.regions.filter(v=>{var x;return(x=v.responsive)==null?void 0:x[j]});m.length>0&&(d+=`@media (max-width: ${N}) {
2651
+ `,m.forEach(v=>{var p,_;const x=v.responsive[j];d+=` .${g.id}__${v.id} {
2652
+ `,(p=x.size)!=null&&p.width&&(d+=` width: ${x.size.width};
2653
+ `),(_=x.size)!=null&&_.height&&(d+=` height: ${x.size.height};
2628
2654
  `),d+=` }
2629
2655
  `}),d+=`}
2630
2656
 
2631
- `)}),d},[]),$=o.useCallback(h=>{const d=h.regions.map(v=>` <div className="${h.id}__${v.id}">{/* ${v.type} */}</div>`).join(`
2657
+ `)}),d},[]),P=c.useCallback(g=>{const d=g.regions.map(j=>` <div className="${g.id}__${j.id}">{/* ${j.type} */}</div>`).join(`
2632
2658
  `);return`import React from 'react';
2633
- import './${h.id}.css';
2659
+ import './${g.id}.css';
2634
2660
 
2635
- export function ${ya(h.name)}() {
2661
+ export function ${Pa(g.name)}() {
2636
2662
  return (
2637
- <div className="${h.id}">
2663
+ <div className="${g.id}">
2638
2664
  ${d}
2639
2665
  </div>
2640
2666
  );
2641
- }`},[]),k=o.useCallback(()=>{f(null)},[]),P=o.useCallback(()=>{var h;(h=j.current)==null||h.abort(),c(!1)},[]);return o.useEffect(()=>()=>{var h;(h=j.current)==null||h.abort()},[]),{generateLayout:N,toCSS:S,toReactComponent:$,loading:m,lastResult:g,clearResults:k,abort:P,isConfigured:!!w}}function qt(i){var a,t,r;try{const n=((t=(a=i.choices[0])==null?void 0:a.message)==null?void 0:t.content)||"",m=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,c=JSON.parse(m);if(c.regions||c.container)return{id:c.id||`layout_${Date.now()}`,name:c.name||"Generated Layout",description:c.description,type:c.type||"dashboard",container:{direction:"grid",gap:"16px",padding:"20px",gridColumns:12,...c.container},regions:c.regions||[],breakpoints:c.breakpoints||{xs:"320px",sm:"640px",md:"768px",lg:"1024px",xl:"1280px","2xl":"1536px"},cssGrid:c.cssGrid,cssVariables:c.cssVariables}}catch{}return null}function Ut(i){if(!i)return[];const a=[],t=new Set(i.regions.map(r=>r.type));return t.has("header")||a.push("Consider adding a header region for navigation"),!t.has("sidebar")&&i.type==="dashboard"&&a.push("Add a sidebar for dashboard navigation"),i.regions.some(r=>!r.responsive)&&a.push("Add responsive breakpoints for mobile compatibility"),a.slice(0,3)}function ya(i){return i.replace(/[^a-zA-Z0-9]+(.)/g,(a,t)=>t.toUpperCase()).replace(/^./,a=>a.toUpperCase())}const Ht=[{type:"dashboard",icon:"📊",label:"Dashboard"},{type:"form",icon:"📝",label:"Form"},{type:"list",icon:"📋",label:"List"},{type:"detail",icon:"📄",label:"Detail"},{type:"landing",icon:"🏠",label:"Landing"},{type:"settings",icon:"⚙️",label:"Settings"},{type:"wizard",icon:"🧙",label:"Wizard"},{type:"split",icon:"↔️",label:"Split"},{type:"grid",icon:"⊞",label:"Grid"},{type:"kanban",icon:"📌",label:"Kanban"}];function Wt({config:i,targetDevice:a="responsive",onGenerate:t,showTypeSelector:r=!0,showPreview:n=!0,className:s,style:m,renderLayout:c}){const[g,f]=o.useState(""),[j,w]=o.useState(null),{generateLayout:N,toCSS:S,toReactComponent:$,loading:k,lastResult:P,isConfigured:h}=va({config:i,targetDevice:a,onLayoutGenerated:t}),d=async()=>{!g.trim()||k||await N(g,j||void 0)},v=()=>{if(!(P!=null&&P.layout))return;const p=S(P.layout),_=new Blob([p],{type:"text/css"}),b=URL.createObjectURL(_),u=document.createElement("a");u.href=b,u.download=`${P.layout.id}.css`,u.click(),URL.revokeObjectURL(b)},C=()=>{if(!(P!=null&&P.layout))return;const p=$(P.layout),_=new Blob([p],{type:"text/javascript"}),b=URL.createObjectURL(_),u=document.createElement("a");u.href=b,u.download=`${ya(P.layout.name)}.tsx`,u.click(),URL.revokeObjectURL(b)};return h?e.jsxs("div",{className:`nice-layout-ai ${s||""}`,style:m,children:[r&&e.jsx("div",{className:"nice-layout-ai__types",children:Ht.map(({type:p,icon:_,label:b})=>e.jsxs("button",{type:"button",className:`nice-layout-ai__type ${j===p?"nice-layout-ai__type--selected":""}`,onClick:()=>w(j===p?null:p),children:[e.jsx("span",{className:"nice-layout-ai__type-icon",children:_}),e.jsx("span",{className:"nice-layout-ai__type-label",children:b})]},p))}),e.jsxs("div",{className:"nice-layout-ai__input-section",children:[e.jsx("textarea",{value:g,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:k}),e.jsx("button",{type:"button",onClick:d,className:"nice-layout-ai__submit",disabled:k||!g.trim(),children:k?e.jsx("span",{className:"nice-layout-ai__spinner"}):"🎨 Generate Layout"})]}),P&&P.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:P.layout.name}),e.jsx("span",{className:"nice-layout-ai__layout-type",children:P.layout.type})]}),e.jsxs("div",{className:"nice-layout-ai__actions",children:[e.jsx("button",{type:"button",onClick:()=>t==null?void 0:t(P.layout),children:"✅ Use Layout"}),e.jsx("button",{type:"button",onClick:v,children:"📥 CSS"}),e.jsx("button",{type:"button",onClick:C,children:"📥 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:P.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:c?c(P.layout):e.jsx(Gt,{layout:P.layout})}),e.jsxs("details",{className:"nice-layout-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify(P.layout,null,2)})]})]}),e.jsx("style",{children:`
2667
+ }`},[]),k=c.useCallback(()=>{h(null)},[]),$=c.useCallback(()=>{var g;(g=y.current)==null||g.abort(),o(!1)},[]);return c.useEffect(()=>()=>{var g;(g=y.current)==null||g.abort()},[]),{generateLayout:C,toCSS:S,toReactComponent:P,loading:l,lastResult:f,clearResults:k,abort:$,isConfigured:!!w}}function xi(i){var a,r,t;try{const n=((r=(a=i.choices[0])==null?void 0:a.message)==null?void 0:r.content)||"",l=((t=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:t.trim())||n,o=JSON.parse(l);if(o.regions||o.container)return{id:o.id||`layout_${Date.now()}`,name:o.name||"Generated Layout",description:o.description,type:o.type||"dashboard",container:{direction:"grid",gap:"16px",padding:"20px",gridColumns:12,...o.container},regions:o.regions||[],breakpoints:o.breakpoints||{xs:"320px",sm:"640px",md:"768px",lg:"1024px",xl:"1280px","2xl":"1536px"},cssGrid:o.cssGrid,cssVariables:o.cssVariables}}catch{}return null}function vi(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 Pa(i){return i.replace(/[^a-zA-Z0-9]+(.)/g,(a,r)=>r.toUpperCase()).replace(/^./,a=>a.toUpperCase())}const _i=[{type:"dashboard",icon:"📊",label:"Dashboard"},{type:"form",icon:"📝",label:"Form"},{type:"list",icon:"📋",label:"List"},{type:"detail",icon:"📄",label:"Detail"},{type:"landing",icon:"🏠",label:"Landing"},{type:"settings",icon:"⚙️",label:"Settings"},{type:"wizard",icon:"🧙",label:"Wizard"},{type:"split",icon:"↔️",label:"Split"},{type:"grid",icon:"⊞",label:"Grid"},{type:"kanban",icon:"📌",label:"Kanban"}];function wi({config:i,targetDevice:a="responsive",onGenerate:r,showTypeSelector:t=!0,showPreview:n=!0,className:s,style:l,renderLayout:o}){const[f,h]=c.useState(""),[y,w]=c.useState(null),{generateLayout:C,toCSS:S,toReactComponent:P,loading:k,lastResult:$,isConfigured:g}=Ma({config:i,targetDevice:a,onLayoutGenerated:r}),d=async()=>{!f.trim()||k||await C(f,y||void 0)},j=()=>{if(!($!=null&&$.layout))return;const m=S($.layout),v=new Blob([m],{type:"text/css"}),x=URL.createObjectURL(v),p=document.createElement("a");p.href=x,p.download=`${$.layout.id}.css`,p.click(),URL.revokeObjectURL(x)},N=()=>{if(!($!=null&&$.layout))return;const m=P($.layout),v=new Blob([m],{type:"text/javascript"}),x=URL.createObjectURL(v),p=document.createElement("a");p.href=x,p.download=`${Pa($.layout.name)}.tsx`,p.click(),URL.revokeObjectURL(x)};return g?e.jsxs("div",{className:`nice-layout-ai ${s||""}`,style:l,children:[t&&e.jsx("div",{className:"nice-layout-ai__types",children:_i.map(({type:m,icon:v,label:x})=>e.jsxs("button",{type:"button",className:`nice-layout-ai__type ${y===m?"nice-layout-ai__type--selected":""}`,onClick:()=>w(y===m?null:m),children:[e.jsx("span",{className:"nice-layout-ai__type-icon",children:v}),e.jsx("span",{className:"nice-layout-ai__type-label",children:x})]},m))}),e.jsxs("div",{className:"nice-layout-ai__input-section",children:[e.jsx("textarea",{value:f,onChange:m=>h(m.target.value),placeholder:"Describe the layout you need... (e.g., 'Admin dashboard with sidebar navigation and header')",className:"nice-layout-ai__input",rows:3,disabled:k}),e.jsx("button",{type:"button",onClick:d,className:"nice-layout-ai__submit",disabled:k||!f.trim(),children:k?e.jsx("span",{className:"nice-layout-ai__spinner"}):"🎨 Generate Layout"})]}),$&&$.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:$.layout.name}),e.jsx("span",{className:"nice-layout-ai__layout-type",children:$.layout.type})]}),e.jsxs("div",{className:"nice-layout-ai__actions",children:[e.jsx("button",{type:"button",onClick:()=>r==null?void 0:r($.layout),children:"✅ Use Layout"}),e.jsx("button",{type:"button",onClick:j,children:"📥 CSS"}),e.jsx("button",{type:"button",onClick:N,children:"📥 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:$.layout.regions.map(m=>e.jsx("span",{className:`nice-layout-ai__region nice-layout-ai__region--${m.type}`,children:m.type},m.id))})]}),n&&e.jsx("div",{className:"nice-layout-ai__preview",children:o?o($.layout):e.jsx(ji,{layout:$.layout})}),e.jsxs("details",{className:"nice-layout-ai__json",children:[e.jsx("summary",{children:"View JSON Definition"}),e.jsx("pre",{children:JSON.stringify($.layout,null,2)})]})]}),e.jsx("style",{children:`
2642
2668
  .nice-layout-ai {
2643
2669
  font-family: var(--nice-font-family, system-ui, sans-serif);
2644
2670
  }
@@ -2862,7 +2888,7 @@ ${d}
2862
2888
  font-size: 12px;
2863
2889
  overflow-x: auto;
2864
2890
  }
2865
- `})]}):e.jsx("div",{className:`nice-layout-ai nice-layout-ai--disabled ${s||""}`,style:m,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function Gt({layout:i}){const a=t=>({header:"var(--nice-primary-bg, #e3f2fd)",sidebar:"var(--nice-success-bg, #e8f5e9)",aside:"var(--nice-success-bg, #e8f5e9)",main:"var(--nice-warning-bg, #fff3e0)",content:"var(--nice-warning-bg, #fff3e0)",footer:"var(--nice-bg-secondary, #f5f5f5)",nav:"var(--nice-accent-bg, #fce4ec)"})[t]||"var(--nice-bg-secondary, #f5f5f5)";return e.jsx("div",{className:"layout-preview",style:{display:i.container.direction==="grid"?"grid":"flex",flexDirection:i.container.direction==="column"?"column":"row",gridTemplateColumns:i.container.direction==="grid"&&i.container.gridColumns?typeof i.container.gridColumns=="number"?`repeat(${i.container.gridColumns}, 1fr)`:i.container.gridColumns:void 0,gap:i.container.gap||"8px",minHeight:"300px"},children:i.regions.map(t=>{var r,n,s,m,c,g;return e.jsx("div",{className:"layout-preview__region",style:{gridColumn:(r=t.position)==null?void 0:r.gridColumn,gridRow:(n=t.position)==null?void 0:n.gridRow,width:(s=t.size)==null?void 0:s.width,height:((m=t.size)==null?void 0:m.height)||"80px",minWidth:(c=t.size)==null?void 0:c.minWidth,maxWidth:(g=t.size)==null?void 0:g.maxWidth,background:a(t.type),borderRadius:"6px",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:500,color:"var(--nice-text-secondary, #666)",border:"1px dashed var(--nice-border, #ccc)"},children:t.type},t.id)})})}function _a(i={}){const{config:a,wcagLevel:t="AA",onAuditComplete:r,onError:n}=i,s=X(),[m,c]=o.useState(!1),[g,f]=o.useState(null),j=o.useRef(null),w=a||(s==null?void 0:s.config),N=o.useCallback(async(d,v)=>{var C;if(!w){const p="AI not configured";return n==null||n(p),je("html",t,p)}c(!0),(C=j.current)==null||C.abort(),j.current=new AbortController;try{const p=G(w),_=`You are a WCAG accessibility expert. Analyze the provided HTML code for accessibility issues at WCAG ${t} level.
2891
+ `})]}):e.jsx("div",{className:`nice-layout-ai nice-layout-ai--disabled ${s||""}`,style:l,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function ji({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,l,o,f;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:((l=r.size)==null?void 0:l.height)||"80px",minWidth:(o=r.size)==null?void 0:o.minWidth,maxWidth:(f=r.size)==null?void 0:f.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 $a(i={}){const{config:a,wcagLevel:r="AA",onAuditComplete:t,onError:n}=i,s=Q(),[l,o]=c.useState(!1),[f,h]=c.useState(null),y=c.useRef(null),w=a||(s==null?void 0:s.config),C=c.useCallback(async(d,j)=>{var N;if(!w){const m="AI not configured";return n==null||n(m),Ce("html",r,m)}o(!0),(N=y.current)==null||N.abort(),y.current=new AbortController;try{const m=G(w),v=`You are a WCAG accessibility expert. Analyze the provided HTML code for accessibility issues at WCAG ${r} level.
2866
2892
 
2867
2893
  Return JSON with this exact structure:
2868
2894
  {
@@ -2896,10 +2922,10 @@ Focus on:
2896
2922
  7. Heading hierarchy
2897
2923
  8. Landmark regions
2898
2924
  9. Semantic HTML usage
2899
- 10. Language attributes`,b=await p.chat({messages:[{role:"system",content:_},{role:"user",content:`Analyze this HTML for accessibility:
2900
- ${v?`Context: ${v}
2925
+ 10. Language attributes`,x=await m.chat({messages:[{role:"system",content:v},{role:"user",content:`Analyze this HTML for accessibility:
2926
+ ${j?`Context: ${j}
2901
2927
 
2902
- `:""}${d}`}],temperature:.3,maxTokens:4096}),u=Vt(b,"html",t);return f(u),r==null||r(u),u}catch(p){const _=p instanceof Error?p.message:"Audit failed";return n==null||n(_),je("html",t,_)}finally{c(!1)}},[w,t,r,n]),S=o.useCallback((d,v)=>{const C=me(pe(d)),p=me(pe(v)),_=(Math.max(C,p)+.05)/(Math.min(C,p)+.05),b={foreground:d,background:v,ratio:Math.round(_*100)/100,passesAA:_>=4.5,passesAALarge:_>=3,passesAAA:_>=7,passesAAALarge:_>=4.5};return b.passesAA||(b.suggestions=Yt(d,v,4.5)),b},[]),$=o.useCallback(async d=>{var v,C;if(!w)return n==null||n("AI not configured"),[];try{const y=(((C=(v=(await G(w).chat({messages:[{role:"system",content:`Analyze the HTML for ARIA attribute issues.
2928
+ `:""}${d}`}],temperature:.3,maxTokens:4096}),p=ki(x,"html",r);return h(p),t==null||t(p),p}catch(m){const v=m instanceof Error?m.message:"Audit failed";return n==null||n(v),Ce("html",r,v)}finally{o(!1)}},[w,r,t,n]),S=c.useCallback((d,j)=>{const N=ge(he(d)),m=ge(he(j)),v=(Math.max(N,m)+.05)/(Math.min(N,m)+.05),x={foreground:d,background:j,ratio:Math.round(v*100)/100,passesAA:v>=4.5,passesAALarge:v>=3,passesAAA:v>=7,passesAAALarge:v>=4.5};return x.passesAA||(x.suggestions=Ci(d,j,4.5)),x},[]),P=c.useCallback(async d=>{var j,N;if(!w)return n==null||n("AI not configured"),[];try{const _=(((N=(j=(await G(w).chat({messages:[{role:"system",content:`Analyze the HTML for ARIA attribute issues.
2903
2929
  Return JSON array:
2904
2930
  [{
2905
2931
  "element": "<button>...",
@@ -2910,10 +2936,10 @@ Return JSON array:
2910
2936
  "issues": ["Missing aria-label"],
2911
2937
  "suggestions": ["Add aria-label='Submit form'"]
2912
2938
  }]`},{role:"user",content:`Validate ARIA in:
2913
- ${d}`}],temperature:.2,maxTokens:2048})).choices[0])==null?void 0:v.message)==null?void 0:C.content)||"").match(/\[[\s\S]*\]/);if(y)return JSON.parse(y[0])}catch{}return[]},[w,n]),k=o.useCallback(async d=>{var v,C;if(!w)return n==null||n("AI not configured"),d;try{const b=((C=(v=(await G(w).chat({messages:[{role:"system",content:`You are an accessibility expert. Improve the HTML to be fully WCAG ${t} compliant.
2939
+ ${d}`}],temperature:.2,maxTokens:2048})).choices[0])==null?void 0:j.message)==null?void 0:N.content)||"").match(/\[[\s\S]*\]/);if(_)return JSON.parse(_[0])}catch{}return[]},[w,n]),k=c.useCallback(async d=>{var j,N;if(!w)return n==null||n("AI not configured"),d;try{const x=((N=(j=(await G(w).chat({messages:[{role:"system",content:`You are an accessibility expert. Improve the HTML to be fully WCAG ${r} compliant.
2914
2940
  Add proper ARIA attributes, semantic HTML, keyboard handlers, focus management.
2915
2941
  Return only the improved HTML code.`},{role:"user",content:`Make this accessible:
2916
- ${d}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:v.message)==null?void 0:C.content)||"",u=b.match(/```(?:html)?\s*([\s\S]*?)```/);return u?u[1].trim():b.trim()}catch{return d}},[w,t,n]),P=o.useCallback(()=>{f(null)},[]),h=o.useCallback(()=>{var d;(d=j.current)==null||d.abort(),c(!1)},[]);return o.useEffect(()=>()=>{var d;(d=j.current)==null||d.abort()},[]),{analyzeHTML:N,checkContrast:S,validateARIA:$,suggestAccessibleCode:k,loading:m,lastAudit:g,clearAudit:P,abort:h,isConfigured:!!w}}function je(i,a,t){return{timestamp:new Date,target:i,wcagLevel:a,issues:t?[{id:"error",category:"semantic-html",severity:"critical",wcagCriteria:"N/A",wcagLevel:"A",title:"Audit Error",description:t,impact:"Audit could not complete",suggestion:"Try again or check configuration"}]:[],score:t?0:100,summary:{critical:t?1:0,serious:0,moderate:0,minor:0,passed:0},recommendations:[]}}function Vt(i,a,t){var r,n,s;try{const m=((n=(r=i.choices[0])==null?void 0:r.message)==null?void 0:n.content)||"",g=((s=(m.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,m])[1])==null?void 0:s.trim())||m,f=JSON.parse(g),j=(f.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:j.filter(N=>N.severity==="critical").length,serious:j.filter(N=>N.severity==="serious").length,moderate:j.filter(N=>N.severity==="moderate").length,minor:j.filter(N=>N.severity==="minor").length,passed:0};return{timestamp:new Date,target:a,wcagLevel:t,issues:j,score:f.score??Kt(w),summary:w,recommendations:f.recommendations||[]}}catch{return je(a,t,"Failed to parse audit results")}}function Kt(i){const a=i.critical*25+i.serious*15+i.moderate*5+i.minor*2;return Math.max(0,100-a)}function pe(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 me(i){const[a,t,r]=[i.r,i.g,i.b].map(n=>(n/=255,n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4)));return .2126*a+.7152*t+.0722*r}function Yt(i,a,t){const r=[],n=pe(i),s=pe(a),m={r:Math.max(0,n.r-40),g:Math.max(0,n.g-40),b:Math.max(0,n.b-40)},c=`#${m.r.toString(16).padStart(2,"0")}${m.g.toString(16).padStart(2,"0")}${m.b.toString(16).padStart(2,"0")}`,g=me(m),f=me(s);(Math.max(g,f)+.05)/(Math.min(g,f)+.05)>=t&&r.push(`Try darker foreground: ${c}`);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 be={critical:{bg:"var(--nice-danger-bg, #ffebee)",color:"var(--nice-danger-dark, #c62828)",icon:"🚫"},serious:{bg:"var(--nice-warning-bg, #fff3e0)",color:"var(--nice-warning-dark, #e65100)",icon:"⚠️"},moderate:{bg:"var(--nice-warning-bg, #fff8e1)",color:"var(--nice-warning-dark, #f57f17)",icon:"⚡"},minor:{bg:"var(--nice-primary-bg, #e3f2fd)",color:"var(--nice-primary-dark, #1565c0)",icon:"ℹ️"}};function Xt({config:i,wcagLevel:a="AA",onAuditComplete:t,showContrastChecker:r=!0,className:n,style:s,renderIssue:m}){const[c,g]=o.useState(""),[f,j]=o.useState("var(--nice-text, #333333)"),[w,N]=o.useState("var(--nice-bg, #fff)"),[S,$]=o.useState(null),{analyzeHTML:k,checkContrast:P,suggestAccessibleCode:h,loading:d,lastAudit:v,isConfigured:C}=_a({config:i,wcagLevel:a,onAuditComplete:t}),p=async()=>{!c.trim()||d||await k(c)},_=()=>{const u=P(f,w);$(u)},b=async()=>{if(!c.trim())return;const u=await h(c);g(u)};return C?e.jsxs("div",{className:`nice-a11y-ai ${n||""}`,style:s,children:[r&&e.jsxs("div",{className:"nice-a11y-ai__contrast",children:[e.jsx("h3",{children:"Color Contrast Checker"}),e.jsxs("div",{className:"nice-a11y-ai__contrast-inputs",children:[e.jsxs("label",{children:["Foreground",e.jsx("input",{type:"color",value:f,onChange:u=>j(u.target.value)}),e.jsx("input",{type:"text",value:f,onChange:u=>j(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:_,children:"Check"})]}),S&&e.jsxs("div",{className:"nice-a11y-ai__contrast-result",children:[e.jsx("div",{className:"nice-a11y-ai__contrast-preview",style:{color:f,background: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: ",S.passesAA?"✅":"❌"]}),e.jsxs("span",{className:S.passesAALarge?"pass":"fail",children:["AA Large: ",S.passesAALarge?"✅":"❌"]}),e.jsxs("span",{className:S.passesAAA?"pass":"fail",children:["AAA: ",S.passesAAA?"✅":"❌"]})]})]}),S.suggestions&&S.suggestions.length>0&&e.jsx("div",{className:"nice-a11y-ai__suggestions",children:S.suggestions.map((u,y)=>e.jsx("div",{children:u},y))})]})]}),e.jsxs("div",{className:"nice-a11y-ai__analyzer",children:[e.jsxs("h3",{children:["HTML Accessibility Analyzer (WCAG ",a,")"]}),e.jsx("textarea",{value:c,onChange:u=>g(u.target.value),placeholder:"Paste HTML code to analyze...",className:"nice-a11y-ai__input",rows:8,disabled:d}),e.jsxs("div",{className:"nice-a11y-ai__actions",children:[e.jsx("button",{type:"button",onClick:p,disabled:d||!c.trim(),children:d?e.jsx("span",{className:"nice-a11y-ai__spinner"}):"🔍 Analyze"}),e.jsx("button",{type:"button",onClick:b,disabled:d||!c.trim(),children:"🔧 Auto-Fix"})]})]}),v&&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:v.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:[v.summary.critical," Critical"]}),e.jsxs("span",{className:"serious",children:[v.summary.serious," Serious"]}),e.jsxs("span",{className:"moderate",children:[v.summary.moderate," Moderate"]}),e.jsxs("span",{className:"minor",children:[v.summary.minor," Minor"]})]})]}),e.jsx("div",{className:"nice-a11y-ai__issues",children:v.issues.map(u=>m?m(u):e.jsxs("div",{className:"nice-a11y-ai__issue",style:{background:be[u.severity].bg,borderLeftColor:be[u.severity].color},children:[e.jsxs("div",{className:"nice-a11y-ai__issue-header",children:[e.jsx("span",{className:"nice-a11y-ai__issue-icon",children:be[u.severity].icon}),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))}),v.recommendations.length>0&&e.jsxs("div",{className:"nice-a11y-ai__recommendations",children:[e.jsx("h4",{children:"General Recommendations"}),e.jsx("ul",{children:v.recommendations.map((u,y)=>e.jsx("li",{children:u},y))})]})]}),e.jsx("style",{children:`
2942
+ ${d}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:j.message)==null?void 0:N.content)||"",p=x.match(/```(?:html)?\s*([\s\S]*?)```/);return p?p[1].trim():x.trim()}catch{return d}},[w,r,n]),$=c.useCallback(()=>{h(null)},[]),g=c.useCallback(()=>{var d;(d=y.current)==null||d.abort(),o(!1)},[]);return c.useEffect(()=>()=>{var d;(d=y.current)==null||d.abort()},[]),{analyzeHTML:C,checkContrast:S,validateARIA:P,suggestAccessibleCode:k,loading:l,lastAudit:f,clearAudit:$,abort:g,isConfigured:!!w}}function Ce(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 ki(i,a,r){var t,n,s;try{const l=((n=(t=i.choices[0])==null?void 0:t.message)==null?void 0:n.content)||"",f=((s=(l.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,l])[1])==null?void 0:s.trim())||l,h=JSON.parse(f),y=(h.issues||[]).map((C,S)=>({id:C.id||`issue_${S}`,category:C.category||"semantic-html",severity:C.severity||"moderate",wcagCriteria:C.wcagCriteria||"N/A",wcagLevel:C.wcagLevel||"A",title:C.title||"Unknown Issue",description:C.description||"",element:C.element,selector:C.selector,impact:C.impact||"",suggestion:C.suggestion||"",codeExample:C.codeExample})),w={critical:y.filter(C=>C.severity==="critical").length,serious:y.filter(C=>C.severity==="serious").length,moderate:y.filter(C=>C.severity==="moderate").length,minor:y.filter(C=>C.severity==="minor").length,passed:0};return{timestamp:new Date,target:a,wcagLevel:r,issues:y,score:h.score??Ni(w),summary:w,recommendations:h.recommendations||[]}}catch{return Ce(a,r,"Failed to parse audit results")}}function Ni(i){const a=i.critical*25+i.serious*15+i.moderate*5+i.minor*2;return Math.max(0,100-a)}function he(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 ge(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 Ci(i,a,r){const t=[],n=he(i),s=he(a),l={r:Math.max(0,n.r-40),g:Math.max(0,n.g-40),b:Math.max(0,n.b-40)},o=`#${l.r.toString(16).padStart(2,"0")}${l.g.toString(16).padStart(2,"0")}${l.b.toString(16).padStart(2,"0")}`,f=ge(l),h=ge(s);(Math.max(f,h)+.05)/(Math.min(f,h)+.05)>=r&&t.push(`Try darker foreground: ${o}`);const w={r:Math.min(255,s.r+40),g:Math.min(255,s.g+40),b:Math.min(255,s.b+40)},C=`#${w.r.toString(16).padStart(2,"0")}${w.g.toString(16).padStart(2,"0")}${w.b.toString(16).padStart(2,"0")}`;return t.push(`Try lighter background: ${C}`),t}const _e={critical:{bg:"var(--nice-danger-bg, #ffebee)",color:"var(--nice-danger-dark, #c62828)",icon:"🚫"},serious:{bg:"var(--nice-warning-bg, #fff3e0)",color:"var(--nice-warning-dark, #e65100)",icon:"⚠️"},moderate:{bg:"var(--nice-warning-bg, #fff8e1)",color:"var(--nice-warning-dark, #f57f17)",icon:"⚡"},minor:{bg:"var(--nice-primary-bg, #e3f2fd)",color:"var(--nice-primary-dark, #1565c0)",icon:"ℹ️"}};function Si({config:i,wcagLevel:a="AA",onAuditComplete:r,showContrastChecker:t=!0,className:n,style:s,renderIssue:l}){const[o,f]=c.useState(""),[h,y]=c.useState("var(--nice-text, #333333)"),[w,C]=c.useState("var(--nice-bg, #fff)"),[S,P]=c.useState(null),{analyzeHTML:k,checkContrast:$,suggestAccessibleCode:g,loading:d,lastAudit:j,isConfigured:N}=$a({config:i,wcagLevel:a,onAuditComplete:r}),m=async()=>{!o.trim()||d||await k(o)},v=()=>{const p=$(h,w);P(p)},x=async()=>{if(!o.trim())return;const p=await g(o);f(p)};return N?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:h,onChange:p=>y(p.target.value)}),e.jsx("input",{type:"text",value:h,onChange:p=>y(p.target.value)})]}),e.jsxs("label",{children:["Background",e.jsx("input",{type:"color",value:w,onChange:p=>C(p.target.value)}),e.jsx("input",{type:"text",value:w,onChange:p=>C(p.target.value)})]}),e.jsx("button",{type:"button",onClick:v,children:"Check"})]}),S&&e.jsxs("div",{className:"nice-a11y-ai__contrast-result",children:[e.jsx("div",{className:"nice-a11y-ai__contrast-preview",style:{color:h,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: ",S.passesAA?"✅":"❌"]}),e.jsxs("span",{className:S.passesAALarge?"pass":"fail",children:["AA Large: ",S.passesAALarge?"✅":"❌"]}),e.jsxs("span",{className:S.passesAAA?"pass":"fail",children:["AAA: ",S.passesAAA?"✅":"❌"]})]})]}),S.suggestions&&S.suggestions.length>0&&e.jsx("div",{className:"nice-a11y-ai__suggestions",children:S.suggestions.map((p,_)=>e.jsx("div",{children:p},_))})]})]}),e.jsxs("div",{className:"nice-a11y-ai__analyzer",children:[e.jsxs("h3",{children:["HTML Accessibility Analyzer (WCAG ",a,")"]}),e.jsx("textarea",{value:o,onChange:p=>f(p.target.value),placeholder:"Paste HTML code to analyze...",className:"nice-a11y-ai__input",rows:8,disabled:d}),e.jsxs("div",{className:"nice-a11y-ai__actions",children:[e.jsx("button",{type:"button",onClick:m,disabled:d||!o.trim(),children:d?e.jsx("span",{className:"nice-a11y-ai__spinner"}):"🔍 Analyze"}),e.jsx("button",{type:"button",onClick:x,disabled:d||!o.trim(),children:"🔧 Auto-Fix"})]})]}),j&&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:j.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:[j.summary.critical," Critical"]}),e.jsxs("span",{className:"serious",children:[j.summary.serious," Serious"]}),e.jsxs("span",{className:"moderate",children:[j.summary.moderate," Moderate"]}),e.jsxs("span",{className:"minor",children:[j.summary.minor," Minor"]})]})]}),e.jsx("div",{className:"nice-a11y-ai__issues",children:j.issues.map(p=>l?l(p):e.jsxs("div",{className:"nice-a11y-ai__issue",style:{background:_e[p.severity].bg,borderLeftColor:_e[p.severity].color},children:[e.jsxs("div",{className:"nice-a11y-ai__issue-header",children:[e.jsx("span",{className:"nice-a11y-ai__issue-icon",children:_e[p.severity].icon}),e.jsx("span",{className:"nice-a11y-ai__issue-title",children:p.title}),e.jsxs("span",{className:"nice-a11y-ai__issue-wcag",children:["WCAG ",p.wcagCriteria," (",p.wcagLevel,")"]})]}),e.jsx("p",{className:"nice-a11y-ai__issue-desc",children:p.description}),p.element&&e.jsx("code",{className:"nice-a11y-ai__issue-element",children:p.element}),e.jsxs("div",{className:"nice-a11y-ai__issue-suggestion",children:[e.jsx("strong",{children:"Fix:"})," ",p.suggestion]}),p.codeExample&&e.jsx("pre",{className:"nice-a11y-ai__issue-example",children:p.codeExample})]},p.id))}),j.recommendations.length>0&&e.jsxs("div",{className:"nice-a11y-ai__recommendations",children:[e.jsx("h4",{children:"General Recommendations"}),e.jsx("ul",{children:j.recommendations.map((p,_)=>e.jsx("li",{children:p},_))})]})]}),e.jsx("style",{children:`
2917
2943
  .nice-a11y-ai {
2918
2944
  font-family: var(--nice-font-family, system-ui, sans-serif);
2919
2945
  }
@@ -3211,14 +3237,14 @@ ${d}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:v.message)==nu
3211
3237
  margin-bottom: var(--nice-space-1-5, 6px);
3212
3238
  font-size: 14px;
3213
3239
  }
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 ve=[{name:"home",category:"navigation",keywords:["home","house","start","main"],svgPath:"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"},{name:"menu",category:"navigation",keywords:["menu","hamburger","nav","bars"],svgPath:"M4 6h16M4 12h16M4 18h16"},{name:"arrow-left",category:"navigation",keywords:["back","previous","left","arrow"],svgPath:"M10 19l-7-7m0 0l7-7m-7 7h18"},{name:"arrow-right",category:"navigation",keywords:["next","forward","right","arrow"],svgPath:"M14 5l7 7m0 0l-7 7m7-7H3"},{name:"chevron-down",category:"navigation",keywords:["expand","dropdown","down","chevron"],svgPath:"M19 9l-7 7-7-7"},{name:"chevron-up",category:"navigation",keywords:["collapse","up","chevron"],svgPath:"M5 15l7-7 7 7"},{name:"plus",category:"action",keywords:["add","create","new","plus"],svgPath:"M12 4v16m8-8H4"},{name:"minus",category:"action",keywords:["remove","subtract","minus"],svgPath:"M20 12H4"},{name:"x",category:"action",keywords:["close","cancel","delete","remove","x"],svgPath:"M6 18L18 6M6 6l12 12"},{name:"check",category:"action",keywords:["done","complete","success","check","tick"],svgPath:"M5 13l4 4L19 7"},{name:"edit",category:"action",keywords:["edit","modify","pencil","write"],svgPath:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"},{name:"trash",category:"action",keywords:["delete","remove","trash","bin"],svgPath:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"},{name:"search",category:"action",keywords:["search","find","magnify","lookup"],svgPath:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"},{name:"filter",category:"action",keywords:["filter","sort","funnel"],svgPath:"M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"},{name:"download",category:"action",keywords:["download","save","export"],svgPath:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"},{name:"upload",category:"action",keywords:["upload","import","send"],svgPath:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"},{name:"refresh",category:"action",keywords:["refresh","reload","sync"],svgPath:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"},{name:"copy",category:"action",keywords:["copy","duplicate","clone"],svgPath:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"},{name:"mail",category:"communication",keywords:["email","mail","message","envelope"],svgPath:"M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"},{name:"phone",category:"communication",keywords:["phone","call","telephone","contact"],svgPath:"M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"},{name:"chat",category:"communication",keywords:["chat","message","comment","bubble"],svgPath:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"},{name:"bell",category:"notification",keywords:["notification","bell","alert","alarm"],svgPath:"M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"},{name:"file",category:"file",keywords:["file","document","page"],svgPath:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"},{name:"folder",category:"file",keywords:["folder","directory","category"],svgPath:"M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"},{name:"image",category:"image",keywords:["image","photo","picture","gallery"],svgPath:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"},{name:"video",category:"av",keywords:["video","movie","film","camera"],svgPath:"M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"},{name:"user",category:"social",keywords:["user","person","account","profile"],svgPath:"M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"},{name:"users",category:"social",keywords:["users","group","team","people"],svgPath:"M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"},{name:"settings",category:"action",keywords:["settings","config","gear","cog","preferences"],svgPath:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z"},{name:"calendar",category:"business",keywords:["calendar","date","schedule","event"],svgPath:"M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"},{name:"clock",category:"business",keywords:["time","clock","schedule","hour"],svgPath:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"credit-card",category:"finance",keywords:["payment","card","credit","money"],svgPath:"M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"},{name:"chart",category:"business",keywords:["chart","graph","analytics","statistics"],svgPath:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"},{name:"lock",category:"security",keywords:["lock","secure","private","password"],svgPath:"M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"},{name:"unlock",category:"security",keywords:["unlock","open","access"],svgPath:"M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"},{name:"shield",category:"security",keywords:["shield","security","protect","safe"],svgPath:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"},{name:"eye",category:"action",keywords:["view","show","visible","eye","visibility"],svgPath:"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"},{name:"eye-off",category:"action",keywords:["hide","invisible","hidden","eye-off"],svgPath:"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"},{name:"info",category:"alert",keywords:["info","information","help","about"],svgPath:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"warning",category:"alert",keywords:["warning","caution","alert","attention"],svgPath:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"},{name:"error",category:"alert",keywords:["error","danger","fail","problem"],svgPath:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"success",category:"alert",keywords:["success","done","complete","check-circle"],svgPath:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"star",category:"action",keywords:["star","favorite","bookmark","rating"],svgPath:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"},{name:"heart",category:"social",keywords:["heart","love","like","favorite"],svgPath:"M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"},{name:"share",category:"social",keywords:["share","send","forward"],svgPath:"M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z"},{name:"link",category:"action",keywords:["link","url","chain","hyperlink"],svgPath:"M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"},{name:"external-link",category:"action",keywords:["external","open","new-window"],svgPath:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"}];function wa(i={}){const{config:a,defaultLibrary:t="lucide",defaultStyle:r="outline",maxSuggestions:n=10,onSuggestion:s,onError:m}=i,c=X(),[g,f]=o.useState(!1),[j,w]=o.useState(null),N=o.useRef(null),S=a||(c==null?void 0:c.config),$=o.useCallback(C=>{const p=C.toLowerCase(),_=p.split(/\s+/);return ve.map(b=>{let u=0;return b.name===p?u+=100:b.name.includes(p)&&(u+=50),_.forEach(y=>{b.keywords.forEach(A=>{A===y?u+=30:(A.includes(y)||y.includes(A))&&(u+=15)})}),b.category===p&&(u+=20),{id:`icon_${b.name}`,name:b.name,displayName:b.name.replace(/-/g," ").replace(/\b\w/g,y=>y.toUpperCase()),category:b.category,style:r,library:t,relevanceScore:u,keywords:b.keywords,svgPath:b.svgPath}}).filter(b=>b.relevanceScore>0).sort((b,u)=>u.relevanceScore-b.relevanceScore).slice(0,n)},[t,r,n]),k=o.useCallback(async(C,p)=>{var u,y,A,R;const _=performance.now(),b=$(C);if(!S){const l={query:C,suggestions:b,latencyMs:performance.now()-_};return w(l),s==null||s(l),l}f(!0),(u=N.current)==null||u.abort(),N.current=new AbortController;try{const l=G(S),x=p?`
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 we=[{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 Ia(i={}){const{config:a,defaultLibrary:r="lucide",defaultStyle:t="outline",maxSuggestions:n=10,onSuggestion:s,onError:l}=i,o=Q(),[f,h]=c.useState(!1),[y,w]=c.useState(null),C=c.useRef(null),S=a||(o==null?void 0:o.config),P=c.useCallback(N=>{const m=N.toLowerCase(),v=m.split(/\s+/);return we.map(x=>{let p=0;return x.name===m?p+=100:x.name.includes(m)&&(p+=50),v.forEach(_=>{x.keywords.forEach(M=>{M===_?p+=30:(M.includes(_)||_.includes(M))&&(p+=15)})}),x.category===m&&(p+=20),{id:`icon_${x.name}`,name:x.name,displayName:x.name.replace(/-/g," ").replace(/\b\w/g,_=>_.toUpperCase()),category:x.category,style:t,library:r,relevanceScore:p,keywords:x.keywords,svgPath:x.svgPath}}).filter(x=>x.relevanceScore>0).sort((x,p)=>p.relevanceScore-x.relevanceScore).slice(0,n)},[r,t,n]),k=c.useCallback(async(N,m)=>{var p,_,M,R;const v=performance.now(),x=P(N);if(!S){const T={query:N,suggestions:x,latencyMs:performance.now()-v};return w(T),s==null||s(T),T}h(!0),(p=C.current)==null||p.abort(),C.current=new AbortController;try{const T=G(S),u=m?`
3215
3241
  Context:
3216
- - Component type: ${p.componentType||"any"}
3217
- - Purpose: ${p.purpose||"general"}
3218
- - Related icons: ${((y=p.relatedIcons)==null?void 0:y.join(", "))||"none"}
3219
- - Theme: ${p.theme||"light"}
3220
- - Preferred style: ${p.preferredStyle||r}
3221
- - Preferred library: ${p.preferredLibrary||t}`:"",D=(((R=(A=(await l.chat({messages:[{role:"system",content:`You are an icon recommendation expert. Suggest icons based on user query.
3242
+ - Component type: ${m.componentType||"any"}
3243
+ - Purpose: ${m.purpose||"general"}
3244
+ - Related icons: ${((_=m.relatedIcons)==null?void 0:_.join(", "))||"none"}
3245
+ - Theme: ${m.theme||"light"}
3246
+ - Preferred style: ${m.preferredStyle||t}
3247
+ - Preferred library: ${m.preferredLibrary||r}`:"",D=(((R=(M=(await T.chat({messages:[{role:"system",content:`You are an icon recommendation expert. Suggest icons based on user query.
3222
3248
  Return JSON array of 5-10 icon suggestions:
3223
3249
  [{
3224
3250
  "name": "icon-name",
@@ -3229,7 +3255,7 @@ Return JSON array of 5-10 icon suggestions:
3229
3255
  "usage": "Brief usage description"
3230
3256
  }]
3231
3257
 
3232
- Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Suggest icons for: "${C}"${x}`}],temperature:.5,maxTokens:1024})).choices[0])==null?void 0:A.message)==null?void 0:R.content)||"").match(/\[[\s\S]*\]/);let J=[];if(D)try{J=JSON.parse(D[0]).map((F,q)=>({id:F.id||`ai_icon_${q}`,name:F.name||"unknown",displayName:F.displayName||F.name||"Unknown",category:F.category||"action",style:(p==null?void 0:p.preferredStyle)||r,library:(p==null?void 0:p.preferredLibrary)||t,relevanceScore:F.relevanceScore||50,keywords:F.keywords||[],usage:F.usage}))}catch{}const H=Qt(b,J,n),Y={query:C,suggestions:H,latencyMs:performance.now()-_};return w(Y),s==null||s(Y),Y}catch(l){const x=l instanceof Error?l.message:"Suggestion failed",M={query:C,suggestions:b,latencyMs:performance.now()-_,error:x};return w(M),m==null||m(x),M}finally{f(!1)}},[S,t,r,n,$,s,m]),P=o.useCallback(C=>ve.filter(p=>p.category===C).map(p=>({id:`icon_${p.name}`,name:p.name,displayName:p.name.replace(/-/g," ").replace(/\b\w/g,_=>_.toUpperCase()),category:p.category,style:r,library:t,relevanceScore:100,keywords:p.keywords,svgPath:p.svgPath})),[t,r]),h=o.useMemo(()=>{const C=new Set;return ve.forEach(p=>C.add(p.category)),Array.from(C)},[]),d=o.useCallback(()=>{w(null)},[]),v=o.useCallback(()=>{var C;(C=N.current)==null||C.abort(),f(!1)},[]);return o.useEffect(()=>()=>{var C;(C=N.current)==null||C.abort()},[]),{suggestIcons:k,localSearch:$,getByCategory:P,categories:h,loading:g,lastResult:j,clearResults:d,abort:v,isConfigured:!!S}}function Qt(i,a,t){const r=new Set,n=[];for(const s of i)r.has(s.name)||(r.add(s.name),n.push(s));for(const s of a)!r.has(s.name)&&n.length<t&&(r.add(s.name),n.push(s));return n.slice(0,t)}function Zt({config:i,defaultLibrary:a="lucide",defaultStyle:t="outline",maxSuggestions:r=10,onSelect:n,showCategories:s=!0,showPreview:m=!0,className:c,style:g}){const[f,j]=o.useState(""),[w,N]=o.useState(null),[S,$]=o.useState(null),{suggestIcons:k,getByCategory:P,categories:h,loading:d,lastResult:v}=wa({config:i,defaultLibrary:a,defaultStyle:t,maxSuggestions:r}),C=async()=>{f.trim()&&(N(null),await k(f))},p=y=>{y.key==="Enter"&&C()},_=y=>{w===y?N(null):(N(y),j(""))},b=y=>{$(y),n==null||n(y)},u=w?P(w):(v==null?void 0:v.suggestions)||[];return e.jsxs("div",{className:`nice-icon-ai ${c||""}`,style:g,children:[e.jsxs("div",{className:"nice-icon-ai__search",children:[e.jsx("input",{type:"text",value:f,onChange:y=>j(y.target.value),onKeyDown:p,placeholder:"Search icons... (e.g., 'save', 'notification', 'user profile')",className:"nice-icon-ai__input",disabled:d}),e.jsx("button",{type:"button",onClick:C,className:"nice-icon-ai__search-btn",disabled:d||!f.trim(),children:d?e.jsx("span",{className:"nice-icon-ai__spinner"}):"🔍"})]}),s&&e.jsx("div",{className:"nice-icon-ai__categories",children:h.map(y=>e.jsx("button",{type:"button",className:`nice-icon-ai__category ${w===y?"nice-icon-ai__category--selected":""}`,onClick:()=>_(y),children:y},y))}),u.length>0&&e.jsx("div",{className:"nice-icon-ai__results",children:u.map(y=>e.jsxs("button",{type:"button",className:`nice-icon-ai__icon ${(S==null?void 0:S.id)===y.id?"nice-icon-ai__icon--selected":""}`,onClick:()=>b(y),title:y.displayName,children:[e.jsx(De,{icon:y}),e.jsx("span",{className:"nice-icon-ai__icon-name",children:y.displayName})]},y.id))}),m&&S&&e.jsxs("div",{className:"nice-icon-ai__preview",children:[e.jsx("div",{className:"nice-icon-ai__preview-icon",children:e.jsx(De,{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(y=>e.jsx("span",{className:"nice-icon-ai__keyword",children:y},y))}),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.jsx("button",{type:"button",onClick:()=>n==null?void 0:n(S),children:"✅ Use Icon"}),e.jsx("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(S.name)},children:"📋 Copy Name"}),S.svgPath&&e.jsx("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(`<svg viewBox="0 0 24 24"><path d="${S.svgPath}" /></svg>`)},children:"📋 Copy SVG"})]})]})]}),e.jsx("style",{children:`
3258
+ Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Suggest icons for: "${N}"${u}`}],temperature:.5,maxTokens:1024})).choices[0])==null?void 0:M.message)==null?void 0:R.content)||"").match(/\[[\s\S]*\]/);let J=[];if(D)try{J=JSON.parse(D[0]).map((F,U)=>({id:F.id||`ai_icon_${U}`,name:F.name||"unknown",displayName:F.displayName||F.name||"Unknown",category:F.category||"action",style:(m==null?void 0:m.preferredStyle)||t,library:(m==null?void 0:m.preferredLibrary)||r,relevanceScore:F.relevanceScore||50,keywords:F.keywords||[],usage:F.usage}))}catch{}const Y=Ti(x,J,n),V={query:N,suggestions:Y,latencyMs:performance.now()-v};return w(V),s==null||s(V),V}catch(T){const u=T instanceof Error?T.message:"Suggestion failed",b={query:N,suggestions:x,latencyMs:performance.now()-v,error:u};return w(b),l==null||l(u),b}finally{h(!1)}},[S,r,t,n,P,s,l]),$=c.useCallback(N=>we.filter(m=>m.category===N).map(m=>({id:`icon_${m.name}`,name:m.name,displayName:m.name.replace(/-/g," ").replace(/\b\w/g,v=>v.toUpperCase()),category:m.category,style:t,library:r,relevanceScore:100,keywords:m.keywords,svgPath:m.svgPath})),[r,t]),g=c.useMemo(()=>{const N=new Set;return we.forEach(m=>N.add(m.category)),Array.from(N)},[]),d=c.useCallback(()=>{w(null)},[]),j=c.useCallback(()=>{var N;(N=C.current)==null||N.abort(),h(!1)},[]);return c.useEffect(()=>()=>{var N;(N=C.current)==null||N.abort()},[]),{suggestIcons:k,localSearch:P,getByCategory:$,categories:g,loading:f,lastResult:y,clearResults:d,abort:j,isConfigured:!!S}}function Ti(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 Ai({config:i,defaultLibrary:a="lucide",defaultStyle:r="outline",maxSuggestions:t=10,onSelect:n,showCategories:s=!0,showPreview:l=!0,className:o,style:f}){const[h,y]=c.useState(""),[w,C]=c.useState(null),[S,P]=c.useState(null),{suggestIcons:k,getByCategory:$,categories:g,loading:d,lastResult:j}=Ia({config:i,defaultLibrary:a,defaultStyle:r,maxSuggestions:t}),N=async()=>{h.trim()&&(C(null),await k(h))},m=_=>{_.key==="Enter"&&N()},v=_=>{w===_?C(null):(C(_),y(""))},x=_=>{P(_),n==null||n(_)},p=w?$(w):(j==null?void 0:j.suggestions)||[];return e.jsxs("div",{className:`nice-icon-ai ${o||""}`,style:f,children:[e.jsxs("div",{className:"nice-icon-ai__search",children:[e.jsx("input",{type:"text",value:h,onChange:_=>y(_.target.value),onKeyDown:m,placeholder:"Search icons... (e.g., 'save', 'notification', 'user profile')",className:"nice-icon-ai__input",disabled:d}),e.jsx("button",{type:"button",onClick:N,className:"nice-icon-ai__search-btn",disabled:d||!h.trim(),children:d?e.jsx("span",{className:"nice-icon-ai__spinner"}):"🔍"})]}),s&&e.jsx("div",{className:"nice-icon-ai__categories",children:g.map(_=>e.jsx("button",{type:"button",className:`nice-icon-ai__category ${w===_?"nice-icon-ai__category--selected":""}`,onClick:()=>v(_),children:_},_))}),p.length>0&&e.jsx("div",{className:"nice-icon-ai__results",children:p.map(_=>e.jsxs("button",{type:"button",className:`nice-icon-ai__icon ${(S==null?void 0:S.id)===_.id?"nice-icon-ai__icon--selected":""}`,onClick:()=>x(_),title:_.displayName,children:[e.jsx(Ue,{icon:_}),e.jsx("span",{className:"nice-icon-ai__icon-name",children:_.displayName})]},_.id))}),l&&S&&e.jsxs("div",{className:"nice-icon-ai__preview",children:[e.jsx("div",{className:"nice-icon-ai__preview-icon",children:e.jsx(Ue,{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(_=>e.jsx("span",{className:"nice-icon-ai__keyword",children:_},_))}),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.jsx("button",{type:"button",onClick:()=>n==null?void 0:n(S),children:"✅ Use Icon"}),e.jsx("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(S.name)},children:"📋 Copy Name"}),S.svgPath&&e.jsx("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(`<svg viewBox="0 0 24 24"><path d="${S.svgPath}" /></svg>`)},children:"📋 Copy SVG"})]})]})]}),e.jsx("style",{children:`
3233
3259
  .nice-icon-ai {
3234
3260
  font-family: var(--nice-font-family, system-ui, sans-serif);
3235
3261
  }
@@ -3426,4 +3452,4 @@ Focus on semantic meaning and common UI patterns.`},{role:"user",content:`Sugges
3426
3452
  color: white;
3427
3453
  border: none;
3428
3454
  }
3429
- `})]})}function De({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=ye;exports.AnthropicProvider=ia;exports.AzureOpenAIProvider=ra;exports.CHART_CONFIG_TEMPLATE=ce;exports.CODE_COMPLETION_TEMPLATE=oe;exports.CostTracker=oa;exports.DATA_GRID_FILTER_TEMPLATE=re;exports.DATA_GRID_SORT_TEMPLATE=ne;exports.FORM_BUILDER_TEMPLATE=se;exports.GroqProvider=sa;exports.InMemoryCostStorage=Re;exports.LocalStorageCostStorage=ca;exports.NiceAIHintBubble=ke;exports.NiceAIProvider=ja;exports.NiceAccessibilityAI=Xt;exports.NiceChartAI=vt;exports.NiceCodeEditorAI=Ct;exports.NiceDataGridAI=mt;exports.NiceDataLabeler=tt;exports.NiceFormBuilderAI=gt;exports.NiceIconSuggestorAI=Zt;exports.NiceLayoutAI=Wt;exports.NiceMLStudio=et;exports.NiceModelInference=rt;exports.NiceReportBuilderAI=Ot;exports.NiceThemeGeneratorAI=Ft;exports.NiceWorkflowDesignerAI=Mt;exports.OllamaProvider=na;exports.OpenAIProvider=ta;exports.PROMPT_TEMPLATES=he;exports.REPORT_LAYOUT_TEMPLATE=de;exports.RateLimiter=Be;exports.ResilientLLMClient=la;exports.SUMMARIZE_DATA_TEMPLATE=we;exports.THEME_GENERATOR_TEMPLATE=ue;exports.TRANSLATION_TEMPLATE=_e;exports.WORKFLOW_GENERATOR_TEMPLATE=le;exports.build3DSceneContext=Ke;exports.buildAudioContext=Ve;exports.buildChartContext=Aa;exports.buildCodeEditorContext=We;exports.buildColorPickerContext=Ae;exports.buildDataGridContext=Ta;exports.buildDatePickerContext=Te;exports.buildDiagramLayoutContext=Ze;exports.buildFormFillContext=Ue;exports.buildGameEngineContext=Qe;exports.buildGraphicsContext=Ye;exports.buildHtmlEditorContext=Ge;exports.buildIconSearchContext=Xe;exports.buildNumberInputContext=Ce;exports.buildPresentationGenerateContext=ea;exports.buildSelectContext=Se;exports.buildSlideDesignContext=aa;exports.buildTextInputContext=Ne;exports.buildValidationContext=He;exports.colorControlContext=Qa;exports.compileTemplate=Z;exports.createLLMProvider=ae;exports.createProviderFromConfig=G;exports.createResilientClient=da;exports.createResilientClientWithDefaults=dt;exports.dateControlContext=Xa;exports.getTemplate=nt;exports.getTemplatesByCategory=st;exports.listTemplates=ct;exports.numberControlContext=Ka;exports.parseJSONResponse=qe;exports.parseSSEStream=Je;exports.selectControlContext=Ya;exports.textControlContext=Va;exports.useAI3DHint=Ba;exports.useAIAudioHint=Da;exports.useAICodeHint=Oa;exports.useAIColorHint=Ia;exports.useAIContext=X;exports.useAIDateHint=$a;exports.useAIDiagramLayout=Ua;exports.useAIFormFill=La;exports.useAIGraphicsHint=Fa;exports.useAIHtmlHint=Ea;exports.useAIIconSearch=Ja;exports.useAINpcHint=qa;exports.useAINumberHint=Ma;exports.useAIPresentationGenerate=Ha;exports.useAISelectHint=Pa;exports.useAISlideDesign=Wa;exports.useAITextHint=Ra;exports.useAIValidation=za;exports.useAccessibilityAI=_a;exports.useChartAI=ma;exports.useCodeEditorAI=ha;exports.useCostTracker=ot;exports.useDataGridAI=ua;exports.useFormBuilderAI=pa;exports.useIconSuggestorAI=wa;exports.useLayoutAI=va;exports.useNiceAIHint=V;exports.useReportBuilderAI=fa;exports.useThemeGeneratorAI=ba;exports.useWorkflowDesignerAI=ga;exports.withAIHint=Ga;
3455
+ `})]})}function Ue({icon:i,size:a=32}){return i.svgPath?e.jsx("svg",{viewBox:"0 0 24 24",width:a,height:a,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:i.svgPath})}):e.jsx("div",{style:{width:a,height:a,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-bg-secondary, #f0f0f0)",borderRadius:6,fontSize:a*.5,fontWeight:600,color:"var(--nice-text-secondary, #666)"},children:i.name.charAt(0).toUpperCase()})}exports.ACCESSIBILITY_CHECKER_TEMPLATE=je;exports.AnthropicProvider=ha;exports.AzureOpenAIProvider=ga;exports.CHART_CONFIG_TEMPLATE=de;exports.CODE_COMPLETION_TEMPLATE=ue;exports.CostTracker=va;exports.DATA_GRID_FILTER_TEMPLATE=ce;exports.DATA_GRID_SORT_TEMPLATE=oe;exports.FORM_BUILDER_TEMPLATE=le;exports.GroqProvider=ba;exports.InMemoryCostStorage=Ie;exports.LocalStorageCostStorage=xa;exports.NiceAIHintBubble=Se;exports.NiceAIProvider=za;exports.NiceAccessibilityAI=Si;exports.NiceChartAI=Kr;exports.NiceCodeEditorAI=ri;exports.NiceDataGridAI=Jr;exports.NiceDataLabeler=Pr;exports.NiceFormBuilderAI=qr;exports.NiceIconSuggestorAI=Ai;exports.NiceLayoutAI=wi;exports.NiceMLStudio=Rr;exports.NiceModelInference=Ir;exports.NiceReportBuilderAI=mi;exports.NiceThemeGeneratorAI=yi;exports.NiceWorkflowDesignerAI=ci;exports.OllamaProvider=ya;exports.OpenAIProvider=fa;exports.PROMPT_TEMPLATES=ye;exports.REPORT_LAYOUT_TEMPLATE=me;exports.RateLimiter=qe;exports.ResilientLLMClient=_a;exports.SUMMARIZE_DATA_TEMPLATE=Ne;exports.THEME_GENERATOR_TEMPLATE=fe;exports.TRANSLATION_TEMPLATE=ke;exports.WORKFLOW_GENERATOR_TEMPLATE=pe;exports.build3DSceneContext=ea;exports.buildAudioContext=Qe;exports.buildChartContext=Ba;exports.buildCodeEditorContext=Xe;exports.buildColorPickerContext=Pe;exports.buildDataGridContext=Ha;exports.buildDatePickerContext=Me;exports.buildDiagramLayoutContext=ta;exports.buildFormFillContext=Ke;exports.buildGameEngineContext=ia;exports.buildGraphicsContext=aa;exports.buildHtmlEditorContext=Ze;exports.buildIconSearchContext=ra;exports.buildNumberInputContext=Ae;exports.buildPresentationGenerateContext=na;exports.buildSelectContext=Re;exports.buildSlideDesignContext=sa;exports.buildTextInputContext=Te;exports.buildValidationContext=Ye;exports.colorControlContext=dr;exports.compileTemplate=ae;exports.createLLMProvider=te;exports.createProviderFromConfig=G;exports.createResilientClient=wa;exports.createResilientClientWithDefaults=Hr;exports.dateControlContext=lr;exports.getTemplate=zr;exports.getTemplatesByCategory=Lr;exports.listTemplates=Or;exports.numberControlContext=cr;exports.parseJSONResponse=Ve;exports.parseSSEStream=Ge;exports.selectControlContext=or;exports.textControlContext=sr;exports.useAI3DHint=Za;exports.useAIAudioHint=Xa;exports.useAICodeHint=Ka;exports.useAIColorHint=Wa;exports.useAIContext=Q;exports.useAIDateHint=qa;exports.useAIDiagramLayout=rr;exports.useAIFormFill=Va;exports.useAIGraphicsHint=Qa;exports.useAIHtmlHint=Ya;exports.useAIIconSearch=er;exports.useAINpcHint=ar;exports.useAINumberHint=Ja;exports.useAIPresentationGenerate=ir;exports.useAISelectHint=Ua;exports.useAISlideDesign=tr;exports.useAITextHint=Fa;exports.useAIValidation=Ga;exports.useAccessibilityAI=$a;exports.useChartAI=Na;exports.useCodeEditorAI=Ca;exports.useCostTracker=Er;exports.useDataGridAI=ja;exports.useFormBuilderAI=ka;exports.useIconSuggestorAI=Ia;exports.useLayoutAI=Ma;exports.useNiceAIHint=X;exports.useReportBuilderAI=Ta;exports.useThemeGeneratorAI=Ra;exports.useWorkflowDesignerAI=Sa;exports.withAIHint=nr;