@nice2dev/ui-ai 1.0.6 → 1.0.10

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.
Files changed (44) hide show
  1. package/dist/NiceAIHintBubble.d.ts.map +1 -1
  2. package/dist/NiceAIProvider.d.ts +1 -1
  3. package/dist/NiceAIProvider.d.ts.map +1 -1
  4. package/dist/NiceAccessibilityAI.d.ts +98 -0
  5. package/dist/NiceAccessibilityAI.d.ts.map +1 -0
  6. package/dist/NiceChartAI.d.ts +112 -0
  7. package/dist/NiceChartAI.d.ts.map +1 -0
  8. package/dist/NiceCodeEditorAI.d.ts +114 -0
  9. package/dist/NiceCodeEditorAI.d.ts.map +1 -0
  10. package/dist/NiceDataGridAI.d.ts +85 -0
  11. package/dist/NiceDataGridAI.d.ts.map +1 -0
  12. package/dist/NiceDataLabeler.d.ts.map +1 -1
  13. package/dist/NiceFormBuilderAI.d.ts +107 -0
  14. package/dist/NiceFormBuilderAI.d.ts.map +1 -0
  15. package/dist/NiceIconSuggestorAI.d.ts +81 -0
  16. package/dist/NiceIconSuggestorAI.d.ts.map +1 -0
  17. package/dist/NiceLayoutAI.d.ts +103 -0
  18. package/dist/NiceLayoutAI.d.ts.map +1 -0
  19. package/dist/NiceMLStudio.d.ts.map +1 -1
  20. package/dist/NiceModelInference.d.ts.map +1 -1
  21. package/dist/NiceReportBuilderAI.d.ts +176 -0
  22. package/dist/NiceReportBuilderAI.d.ts.map +1 -0
  23. package/dist/NiceThemeGeneratorAI.d.ts +186 -0
  24. package/dist/NiceThemeGeneratorAI.d.ts.map +1 -0
  25. package/dist/NiceWorkflowDesignerAI.d.ts +108 -0
  26. package/dist/NiceWorkflowDesignerAI.d.ts.map +1 -0
  27. package/dist/cost-tracker.d.ts +148 -0
  28. package/dist/cost-tracker.d.ts.map +1 -0
  29. package/dist/fallback-strategies.d.ts +120 -0
  30. package/dist/fallback-strategies.d.ts.map +1 -0
  31. package/dist/index.cjs +3426 -12
  32. package/dist/index.d.ts +32 -0
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.mjs +10496 -1431
  35. package/dist/integrations.d.ts.map +1 -1
  36. package/dist/llm-providers.d.ts +180 -0
  37. package/dist/llm-providers.d.ts.map +1 -0
  38. package/dist/prompt-templates.d.ts +64 -0
  39. package/dist/prompt-templates.d.ts.map +1 -0
  40. package/dist/rateLimiter.d.ts.map +1 -1
  41. package/dist/streaming.d.ts.map +1 -1
  42. package/dist/useNiceAIHint.d.ts.map +1 -1
  43. package/dist/wrappers.d.ts.map +1 -1
  44. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -1,15 +1,3429 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),d=require("react");class de{constructor(t={},a){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1,this.config={maxRequestsPerMinute:t.maxRequestsPerMinute??30,maxTokensPerSession:t.maxTokensPerSession??1e4,warnThresholdPercent:t.warnThresholdPercent??80},this.onWarning=a}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(t){this.tokenCount+=t,this.checkWarning()}getStatus(){this.pruneOldTimestamps();const t=this.config.maxTokensPerSession>0?this.tokenCount/this.config.maxTokensPerSession*100:0,a=this.config.maxRequestsPerMinute>0?this.timestamps.length/this.config.maxRequestsPerMinute*100:0;return{requestsThisMinute:this.timestamps.length,tokensThisSession:this.tokenCount,isLimited:!this.canRequest(),isWarning:t>=this.config.warnThresholdPercent||a>=this.config.warnThresholdPercent}}reset(){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1}pruneOldTimestamps(){const t=Date.now()-6e4;this.timestamps=this.timestamps.filter(a=>a>t)}checkWarning(){var a;if(this.warningEmitted)return;this.getStatus().isWarning&&(this.warningEmitted=!0,(a=this.onWarning)==null||a.call(this))}}const oe=d.createContext(null);function we({config:s,rateLimits:t,enabled:a=!0,onRateLimitWarning:l,children:c}){const n=d.useRef(null);n.current||(n.current=new de(t,l));const v=d.useCallback(()=>n.current.getStatus(),[]),N=d.useMemo(()=>({config:s,enabled:a,rateLimiter:n.current,getRateLimitStatus:v}),[s,a,v]);return e.jsx(oe.Provider,{value:N,children:c})}function Q(){return d.useContext(oe)}async function*ue(s,t){var n,v,N,C,f,I,D,T,k;const a=(n=s.body)==null?void 0:n.getReader();if(!a)throw new Error("Response body is not readable");const l=new TextDecoder;let c="";try{for(;!(t!=null&&t.aborted);){const{done:M,value:y}=await a.read();if(M)break;c+=l.decode(y,{stream:!0});const z=c.split(`
2
- `);c=z.pop()??"";for(const h of z){const b=h.trim();if(!(!b||b===":")){if(b.startsWith("data:")){const g=b.slice(5).trim();if(g==="[DONE]"){yield{token:"",done:!0};return}try{const L=JSON.parse(g),R=((C=(N=(v=L.choices)==null?void 0:v[0])==null?void 0:N.delta)==null?void 0:C.content)??"",$=((I=(f=L.choices)==null?void 0:f[0])==null?void 0:I.finish_reason)==="stop";(R||$)&&(yield{token:R,done:$,usage:L.usage})}catch{g&&(yield{token:g,done:!1})}continue}try{const g=JSON.parse(b),L=g.text??g.content??g.token??"";L&&(yield{token:L,done:!1})}catch{b&&(yield{token:b,done:!1})}}}}if(c.trim()){const M=c.trim();if(M.startsWith("data:")){const y=M.slice(5).trim();if(y&&y!=="[DONE]")try{const h=((k=(T=(D=JSON.parse(y).choices)==null?void 0:D[0])==null?void 0:T.delta)==null?void 0:k.content)??"";h&&(yield{token:h,done:!0})}catch{yield{token:y,done:!0}}}}}finally{a.releaseLock()}}async function me(s){var a,l,c,n;const t=await s.json();if((c=(l=(a=t.choices)==null?void 0:a[0])==null?void 0:l.message)!=null&&c.content)return{text:t.choices[0].message.content,usage:t.usage};if((n=t.message)!=null&&n.content)return{text:t.message.content};if(typeof t.text=="string")return{text:t.text};if(typeof t.content=="string")return{text:t.content};if(typeof t.response=="string")return{text:t.response};throw new Error("Unrecognized AI response format")}const Y=new Map;function ie(s,t){const a=t?{...s,fieldValue:void 0,formContext:void 0}:s;return JSON.stringify(a)}function ke(s,t){const a=[],l=t.systemPrompt??"You are a helpful assistant providing concise contextual hints for form fields. Keep responses short (1-3 sentences). Be specific and actionable.";a.push({role:"system",content:l});const c=[];if(s.fieldLabel&&c.push(`Field: "${s.fieldLabel}"`),s.fieldType&&c.push(`Type: ${s.fieldType}`),!t.privacyMode&&s.fieldValue!==void 0){const v=typeof s.fieldValue=="string"?s.fieldValue:JSON.stringify(s.fieldValue);c.push(`Current value: ${v}`)}s.validationRules&&Object.keys(s.validationRules).length>0&&c.push(`Validation: ${JSON.stringify(s.validationRules)}`),s.schema&&Object.keys(s.schema).length>0&&c.push(`Schema: ${JSON.stringify(s.schema)}`),!t.privacyMode&&s.formContext&&Object.keys(s.formContext).length>0&&c.push(`Form context: ${JSON.stringify(s.formContext)}`),s.customPrompt&&c.push(s.customPrompt);const n=c.length>0?`Provide a helpful hint for this field:
3
- ${c.join(`
4
- `)}`:"Provide a helpful suggestion.";return a.push({role:"user",content:n}),a}function q(s={},t={}){s=s??{},t=t??{};const{debounceMs:a=500,disabled:l=!1}=t,c=Q(),[n,v]=d.useState(""),[N,C]=d.useState(!1),[f,I]=d.useState(null),[D,T]=d.useState(!1),k=d.useRef(null),M=d.useRef(0),y=d.useCallback(async()=>{var H,V,j;if(!c||!c.enabled||l)return;const{config:b,rateLimiter:g}=c;if(!g.recordRequest()){I("Rate limit exceeded. Please wait before requesting another hint.");return}const L=ie(s,b.privacyMode??!1),R=Y.get(L);if(R){v(R),C(!1),I(null),T(!1);return}(H=k.current)==null||H.abort();const $=new AbortController;k.current=$,C(!0),I(null),v(""),T(!1);const F=ke(s,b),B=b.stream!==!1;try{const i={"Content-Type":"application/json",...b.headers};b.apiKey&&(i.Authorization=`Bearer ${b.apiKey}`);const m=JSON.stringify({model:b.model??"gpt-3.5-turbo",messages:F,temperature:b.temperature??.7,max_tokens:b.maxTokens??256,stream:B}),w=await fetch(b.endpoint,{method:"POST",headers:i,body:m,signal:$.signal});if(!w.ok){const p=await w.text().catch(()=>w.statusText);throw new Error(`AI request failed (${w.status}): ${p}`)}if(B){T(!0);let p="";for await(const E of ue(w,$.signal))if($.signal.aborted||(p+=E.token,v(p),(V=E.usage)!=null&&V.completion_tokens&&g.recordTokens(E.usage.completion_tokens),E.done))break;if(p.length>0){const E=Math.ceil(p.length/4);g.recordTokens(E)}Y.set(L,p)}else{const p=await me(w);v(p.text),Y.set(L,p.text),(j=p.usage)!=null&&j.completion_tokens?g.recordTokens(p.usage.completion_tokens):g.recordTokens(Math.ceil(p.text.length/4))}}catch(i){if(i instanceof DOMException&&i.name==="AbortError")return;I(i instanceof Error?i.message:"AI hint request failed")}finally{$.signal.aborted||(C(!1),T(!1))}},[c,s,l]);d.useEffect(()=>{if(!c||!c.enabled||l)return;const b=setTimeout(y,a);return()=>clearTimeout(b)},[s==null?void 0:s.fieldLabel,s==null?void 0:s.fieldType,s==null?void 0:s.fieldValue,s==null?void 0:s.customPrompt,a,l,c==null?void 0:c.enabled,M.current]),d.useEffect(()=>()=>{var b;(b=k.current)==null||b.abort()},[]);const z=d.useCallback(()=>{var b;(b=k.current)==null||b.abort(),C(!1),T(!1)},[]),h=d.useCallback(()=>{if(c){const b=ie(s,c.config.privacyMode??!1);Y.delete(b)}M.current+=1,y()},[c,s,y]);return!c||!c.enabled?{text:"",loading:!1,error:null,streaming:!1,abort:()=>{},refresh:()=>{},hint:null,fetchHint:async()=>{}}:{text:n,loading:N,error:f,streaming:D,abort:z,refresh:h,hint:n?{content:n}:null,fetchHint:async()=>{await y()}}}function Ie(){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 Te(s,t){if(s!=="auto"||!t)return s==="auto"?"top":s;const a=t.top,l=window.innerHeight-t.bottom,c=t.left,n=window.innerWidth-t.right,v=Math.max(a,l,c,n);return v===a?"top":v===l?"bottom":v===n?"right":"left"}function $e(s){const t={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 rgba(0,0,0,0.25)",wordWrap:"break-word"};switch(s){case"top":return{...t,bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:6};case"bottom":return{...t,top:"100%",left:"50%",transform:"translateX(-50%)",marginTop:6};case"left":return{...t,right:"100%",top:"50%",transform:"translateY(-50%)",marginRight:6};case"right":return{...t,left:"100%",top:"50%",transform:"translateY(-50%)",marginLeft:6};default:return{...t,bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:6}}}const Z=d.forwardRef(({context:s,position:t="auto",debounceMs:a=500,showOnHover:l=!1,triggerIcon:c,className:n,style:v},N)=>{var L;const C=Q(),[f,I]=d.useState(!1),[D,T]=d.useState(!1),k=d.useRef(null),M=d.useRef(null),y=q(s,{debounceMs:a,disabled:!D});d.useEffect(()=>{if(!f)return;const R=$=>{var B,H;const F=$.target;(B=k.current)!=null&&B.contains(F)||(H=M.current)!=null&&H.contains(F)||(I(!1),T(!1))};return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[f]),d.useEffect(()=>{if(!f)return;const R=$=>{$.key==="Escape"&&(I(!1),T(!1),y.abort())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[f,y]);const z=d.useCallback(R=>{if(R.stopPropagation(),l)return;const $=!f;I($),T($)},[f,l]),h=d.useCallback(()=>{l&&(I(!0),T(!0))},[l]),b=d.useCallback(()=>{l&&(I(!1),T(!1))},[l]);if(!C||!C.enabled)return null;const g=Te(t,((L=k.current)==null?void 0:L.getBoundingClientRect())??null);return e.jsxs("span",{ref:N,className:n,style:{position:"relative",display:"inline-flex",...v},onMouseEnter:h,onMouseLeave:b,children:[e.jsx("button",{ref:k,type:"button",onClick:z,"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:c??e.jsx(Ie,{})}),f&&e.jsxs("div",{ref:M,role:"tooltip",className:"ntd-ai-popover",style:$e(g),children:[y.loading&&!y.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..."})]}),y.text&&e.jsxs("div",{className:"ntd-ai-content",children:[y.text,y.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"}})]}),y.error&&e.jsx("div",{className:"ntd-ai-error",style:{color:"var(--ntd-ai-error, #f38ba8)"},children:y.error}),y.text&&!y.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:()=>y.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 R;(R=navigator.clipboard)==null||R.writeText(y.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"})]})]})]})});Z.displayName="NiceAIHintBubble";function ee(s,t,a){return{fieldLabel:s,fieldType:"text",fieldValue:t,validationRules:{...(a==null?void 0:a.maxLength)!=null?{maxLength:a.maxLength}:{},...a!=null&&a.pattern?{pattern:a.pattern}:{}},customPrompt:a!=null&&a.placeholder?`Placeholder: "${a.placeholder}". Suggest content or correct grammar.`:"Suggest content, correct grammar, or auto-complete the text."}}function te(s,t,a){return{fieldLabel:s,fieldType:"number",fieldValue:t,validationRules:{...(a==null?void 0:a.min)!=null?{min:a.min}:{},...(a==null?void 0:a.max)!=null?{max:a.max}:{},...(a==null?void 0:a.step)!=null?{step:a.step}:{}},customPrompt:a!=null&&a.unit?`Unit: ${a.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 ae(s,t,a){return{fieldLabel:s,fieldType:a!=null&&a.multiple?"multi-select":"select",fieldValue:t,schema:a!=null&&a.options?{availableOptions:a.options.slice(0,20).map(l=>l.label)}:{},customPrompt:"Suggest the most likely selection. Explain why this option is recommended."}}function se(s,t,a){const l=t instanceof Date?t.toISOString().split("T")[0]:t;return{fieldLabel:s,fieldType:"date",fieldValue:l,validationRules:{...a!=null&&a.min?{min:a.min}:{},...a!=null&&a.max?{max:a.max}:{},...a!=null&&a.disableWeekends?{noWeekends:!0}:{}},customPrompt:'Suggest a date. For example: "next business day", "end of month", "in 2 weeks". Explain your suggestion briefly.'}}function ne(s,t,a){return{fieldLabel:s,fieldType:"color",fieldValue:t,schema:a!=null&&a.palette?{currentPalette:a.palette}:{},customPrompt:a!=null&&a.industry?`Industry: ${a.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 Re(s,t){return{fieldLabel:s,fieldType:"data-grid",schema:{...t!=null&&t.columns?{columns:t.columns}:{},...(t==null?void 0:t.rowCount)!=null?{totalRows:t.rowCount}:{}},formContext:{...t!=null&&t.currentFilters?{filters:t.currentFilters}:{},...t!=null&&t.currentSorts?{sorts:t.currentSorts}:{}},customPrompt:"Suggest column configuration, useful filters, or highlight potential data anomalies."}}function Ae(s,t){return{fieldLabel:s,fieldType:"chart",schema:{...t!=null&&t.currentType?{chartType:t.currentType}:{},...(t==null?void 0:t.seriesCount)!=null?{series:t.seriesCount}:{},...(t==null?void 0:t.pointCount)!=null?{dataPoints:t.pointCount}:{}},customPrompt:t!=null&&t.dataDescription?`Data: ${t.dataDescription}. Suggest the best chart type and labeling strategy.`:"Suggest the most effective chart type for this data. Explain your recommendation."}}function he(s,t){return{fieldLabel:"Form auto-fill",fieldType:"form",schema:{fields:t},customPrompt:`User description: "${s}"
5
- Parse this description and return suggested values for each field as JSON: { ${t.map(a=>`"${a.label}": "value"`).join(", ")} }`}}function xe(s,t,a,l,c){return{fieldLabel:s,fieldType:t,fieldValue:a,validationRules:c==null?void 0:c.rules,customPrompt:`Current validation error: "${l}". 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 Pe(s,t,a){const l=d.useMemo(()=>ee(s,t,a),[s,t,a==null?void 0:a.placeholder,a==null?void 0:a.maxLength,a==null?void 0:a.pattern]);return q(l,a)}function Me(s,t,a){const l=d.useMemo(()=>te(s,t,a),[s,t,a==null?void 0:a.min,a==null?void 0:a.max,a==null?void 0:a.step,a==null?void 0:a.unit]);return q(l,a)}function Le(s,t,a){const l=d.useMemo(()=>ae(s,t,a),[s,t,a==null?void 0:a.multiple]);return q(l,a)}function De(s,t,a){const l=d.useMemo(()=>se(s,t,a),[s,t,a==null?void 0:a.min,a==null?void 0:a.max,a==null?void 0:a.disableWeekends]);return q(l,a)}function Oe(s,t,a){const l=d.useMemo(()=>ne(s,t,a),[s,t,a==null?void 0:a.industry]);return q(l,a)}function Ee(s,t,a,l,c){const n=d.useMemo(()=>l?xe(s,t,a,l,c):{fieldLabel:s,fieldType:t},[s,t,a,l]);return q(n,{...c,disabled:!l||(c==null?void 0:c.disabled)})}function Je(s,t,a){const l=d.useMemo(()=>s?he(s,t):{fieldLabel:"Form"},[s,t]);return q(l,{...a,disabled:!s||(a==null?void 0:a.disabled)})}function ge(s,t,a){const c=(t==null?void 0:t.split(`
6
- `))??[],n=(a==null?void 0:a.cursorLine)!=null?c.slice(Math.max(0,a.cursorLine-8),a.cursorLine+3).join(`
7
- `):c.slice(0,8*2).join(`
8
- `);return{fieldLabel:`Code editor (${s})`,fieldType:"code-editor",fieldValue:n||t,schema:{language:s,...a!=null&&a.framework?{framework:a.framework}:{},...(a==null?void 0:a.cursorLine)!=null?{cursorLine:a.cursorLine,cursorCol:a.cursorCol}:{}},customPrompt:`Language: ${s}${a!=null&&a.framework?`, framework: ${a.framework}`:""}.
9
- Provide a concise inline completion or improvement hint for the code near the cursor. Limit response to ${(a==null?void 0:a.maxSuggestLines)??5} lines of code. If unsure, suggest the most idiomatic approach for this language/framework.`}}function fe(s,t,a){var n;const l=(a==null?void 0:a.mode)??"grammar",c={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:s,fieldType:"html-editor",fieldValue:t==null?void 0:t.slice(0,2e3),schema:{mode:l,...(n=a==null?void 0:a.targetKeywords)!=null&&n.length?{targetKeywords:a.targetKeywords}:{},...a!=null&&a.locale?{locale:a.locale}:{}},customPrompt:c[l]}}function be(s,t){const a=(t==null?void 0:t.mode)??"tag",l=`"${s}"`+((t==null?void 0:t.bpm)!=null?`, BPM: ${t.bpm}`:"")+(t!=null&&t.key?`, Key: ${t.key}`:"")+(t!=null&&t.genre?`, Genre: ${t.genre}`:"")+((t==null?void 0:t.duration)!=null?`, Duration: ${t.duration}s`:""),c={tag:`Audio: ${l}. Suggest genre tags, mood descriptors and playlist categories. Return as JSON array of strings.`,bpm:`Audio: ${l}. Suggest likely BPM range and musical key based on metadata. Return as JSON: { bpm: number, key: string }.`,mix:`Track: ${l}. 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: ${s}`,fieldType:"audio",schema:{mode:a,...(t==null?void 0:t.bpm)!=null?{bpm:t.bpm}:{},...t!=null&&t.key?{key:t.key}:{},...(t==null?void 0:t.duration)!=null?{duration:t.duration}:{},...t!=null&&t.genre?{genre:t.genre}:{}},customPrompt:c[a]}}function je(s,t){var n;const a=(t==null?void 0:t.mode)??"material",l=(t==null?void 0:t.targetDevice)??"web",c={material:`Scene "${s}", ${(t==null?void 0:t.meshCount)??"?"} meshes. Materials: ${((n=t==null?void 0:t.materials)==null?void 0:n.join(", "))||"none"}. Suggest PBR properties (roughness, metalness, baseColor) and texture maps for each material.`,optimize:`Scene "${s}", triangles: ${(t==null?void 0:t.triangleCount)??"?"}, target: ${l}. Identify budget issues and suggest LOD levels, mesh merging, and texture atlas strategy.`,lighting:`Scene "${s}", target: ${l}. Suggest a complete lighting setup (types, intensity, color, shadow settings) for realistic rendering.`,animation:`Rig in scene "${s}". Suggest animation approach (FK/IK, bone count), keyframe timing and easing curves for natural movement.`};return{fieldLabel:`3D scene: ${s}`,fieldType:"3d-scene",schema:{mode:a,...(t==null?void 0:t.meshCount)!=null?{meshes:t.meshCount}:{},...(t==null?void 0:t.triangleCount)!=null?{triangles:t.triangleCount}:{},...t!=null&&t.targetDevice?{target:t.targetDevice}:{}},customPrompt:c[a]}}function ye(s,t){const a=(t==null?void 0:t.mode)??"palette",l=(t==null?void 0:t.width)!=null?`${t.width}×${t.height??"?"}px`:"unknown dimensions",c={filter:`Image "${s}" (${l}). Suggest CSS/SVG filter parameters (brightness, contrast, saturate, hue-rotate, blur) as JSON: { brightness, contrast, saturate, hueRotate, blur }.`,palette:`Image "${s}". Extract or suggest a harmonious 5-color palette as JSON: { primary, secondary, accent, background, text }.`,upscale:`Image "${s}" at ${l}. Recommend upscaling strategy: model (ESRGAN/RealSR/SRCNN), scale factor, and expected quality gain.`,"style-transfer":`Image "${s}", target style: "${(t==null?void 0:t.targetStyle)??"artistic"}". Suggest style-transfer settings as JSON: { contentWeight, styleWeight, iterations, patchSize }.`};return{fieldLabel:`Graphics: ${s}`,fieldType:"graphics",schema:{mode:a,...(t==null?void 0:t.width)!=null?{width:t.width,height:t.height}:{},...t!=null&&t.targetStyle?{targetStyle:t.targetStyle}:{}},customPrompt:c[a]}}function ve(s,t){var a;return{fieldLabel:"Icon search",fieldType:"icon-picker",fieldValue:s,schema:{...t!=null&&t.style?{iconStyle:t.style}:{},...(t==null?void 0:t.limit)!=null?{maxResults:t.limit}:{},...(a=t==null?void 0:t.availableIcons)!=null&&a.length?{sampleIcons:t.availableIcons.slice(0,30)}:{}},customPrompt:`User query: "${s}"
10
- Return the ${(t==null?void 0:t.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 qe(s,t,a){const l=d.useMemo(()=>ge(s,t,a),[s,t,a==null?void 0:a.cursorLine,a==null?void 0:a.cursorCol,a==null?void 0:a.framework]);return q(l,a)}function ze(s,t,a){const l=d.useMemo(()=>fe(s,t,a),[s,t,a==null?void 0:a.mode,a==null?void 0:a.locale]);return q(l,a)}function Fe(s,t){const a=d.useMemo(()=>be(s,t),[s,t==null?void 0:t.bpm,t==null?void 0:t.key,t==null?void 0:t.duration,t==null?void 0:t.mode]);return q(a,t)}function Be(s,t){const a=d.useMemo(()=>je(s,t),[s,t==null?void 0:t.meshCount,t==null?void 0:t.triangleCount,t==null?void 0:t.targetDevice,t==null?void 0:t.mode]);return q(a,t)}function He(s,t){const a=d.useMemo(()=>ye(s,t),[s,t==null?void 0:t.width,t==null?void 0:t.height,t==null?void 0:t.mode,t==null?void 0:t.targetStyle]);return q(a,t)}function Ue(s,t){const a=d.useMemo(()=>ve(s,t),[s,t==null?void 0:t.limit,t==null?void 0:t.style]);return q(a,{...t,disabled:!s||(t==null?void 0:t.disabled)})}function Ne(s,t){var n;const a=(t==null?void 0:t.mode)??"npc-decision",l=(t==null?void 0:t.genre)??"fantasy",c={"npc-decision":`You are an AI game director. The NPC "${s}" must make a decision. Available BT nodes: ${JSON.stringify((t==null?void 0:t.btStatus)??[])}. Game state: ${JSON.stringify((t==null?void 0:t.gameState)??{})}. Return the name of the BT node to activate next, and one sentence of reasoning.`,dialogue:`You are a ${l} RPG writer. Write a short in-character dialogue line for NPC "${s}". Game state: ${JSON.stringify((t==null?void 0:t.gameState)??{})}. Max 2 sentences, no narrative descriptions.`,"procedural-level":`You are a ${l} game designer. Suggest a procedural level layout for a zone containing "${s}". Describe room count, enemy placement, loot, and one unique mechanic. Keep it under 150 words.`,"quest-description":`You are a ${l} quest designer. Write a compelling quest description involving "${s}". Include: objective, giver NPC, rewards, and a short flavour paragraph. Keep it under 120 words.`,"item-description":`You are a ${l} lore writer. Write a short item description for an item related to "${s}". Include: item name, rarity, flavour text, and one special property. Keep it under 80 words.`};return{fieldLabel:s,fieldType:`game-engine:${a}`,fieldValue:t==null?void 0:t.gameState,customPrompt:c[a],schema:{genre:l,mode:a,btNodes:(n=t==null?void 0:t.btStatus)==null?void 0:n.map(v=>v.node)}}}function _e(s,t){const a=d.useMemo(()=>Ne(s,t),[s,t==null?void 0:t.mode,t==null?void 0:t.genre,JSON.stringify(t==null?void 0:t.btStatus),JSON.stringify(t==null?void 0:t.gameState)]);return q(a,t)}function Ce(s,t,a){const l=(a==null?void 0:a.mode)??"layout",c=(a==null?void 0:a.diagramType)??"flowchart",n={layout:`You are a diagram layout optimizer. Given this ${c} with ${s.length} nodes and ${t.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 ${c} 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 ${c} 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 ${c}. Consider semantic relationships, data flow patterns, and visual clustering. Return JSON: { groups: [{ name: string, nodeIds: string[], color?: string }] }`},v=s.map(C=>{var f;return{id:C.id,type:C.type,label:(f=C.label)==null?void 0:f.slice(0,30),pos:[Math.round(C.x),Math.round(C.y)]}}),N=t.map(C=>({id:C.id,src:C.source,tgt:C.target}));return{fieldLabel:`Diagram (${c})`,fieldType:`diagram:${l}`,fieldValue:JSON.stringify({nodes:v,edges:N}),schema:{diagramType:c,mode:l,nodeCount:s.length,edgeCount:t.length,containerSize:a==null?void 0:a.containerSize},customPrompt:n[l]}}function Ve(s,t,a){const l=d.useMemo(()=>Ce(s,t,a),[JSON.stringify(s),JSON.stringify(t),a==null?void 0:a.mode,a==null?void 0:a.diagramType]);return q(l,{...a,disabled:s.length===0||(a==null?void 0:a.disabled)})}function pe(s,t){const a=(t==null?void 0:t.mode)??"generate",l=(t==null?void 0:t.presentationType)??"business",c=(t==null?void 0:t.duration)??15,n=Math.ceil(c/2),v={generate:`You are a presentation designer. Create a ${l} presentation outline based on: "${s}". Target audience: ${(t==null?void 0:t.audience)??"general"}. Duration: ${c} minutes (~${n} 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: "${s}". 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: "${s}". Add supporting details, examples, and transitions. Target: ${n} slides. Return JSON: { slides: [{ title: string, content: string, transitions?: string, animations?: string[] }] }`,improve:`You are a presentation coach. Review and improve this presentation structure: "${s}". Suggest: better flow, stronger opening/closing, clearer data visualization. Return JSON: { improvements: [{ slide: number, issue: string, suggestion: string }], score: number }`};return{fieldLabel:`Presentation (${l})`,fieldType:`presentation:${a}`,fieldValue:s,schema:{presentationType:l,mode:a,duration:c,slideCount:n,audience:t==null?void 0:t.audience,hasData:(t==null?void 0:t.dataContext)!=null},customPrompt:v[a]}}function Ge(s,t){const a=d.useMemo(()=>pe(s,t),[s,t==null?void 0:t.mode,t==null?void 0:t.presentationType,t==null?void 0:t.duration,t==null?void 0:t.audience]);return q(a,{...t,disabled:!s||(t==null?void 0:t.disabled)})}function Se(s,t){var c;const a=(t==null?void 0:t.mode)??"all",l={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:s.title??"Slide Design",fieldType:`slide-design:${a}`,fieldValue:JSON.stringify(s),schema:{mode:a,hasElements:(((c=s.elements)==null?void 0:c.length)??0)>0,layout:s.layout,brandColors:t==null?void 0:t.brandColors},customPrompt:l[a]}}function Ke(s,t){const a=d.useMemo(()=>Se(s,t),[JSON.stringify(s),t==null?void 0:t.mode,JSON.stringify(t==null?void 0:t.brandColors)]);return q(a,t)}function We(s,t,a){const l=d.forwardRef((c,n)=>{const{aiEnabled:v=!0,aiPosition:N="right",aiPrompt:C,aiDebounceMs:f=500,aiShowOnHover:I=!1,aiTriggerIcon:D,...T}=c,k=d.useMemo(()=>{const M=t(T);return C&&(M.customPrompt=C),M},[T,C]);return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(s,{...T,ref:n}),v&&e.jsx(Z,{context:k,position:N,debounceMs:f,showOnHover:I,triggerIcon:D})]})});return l.displayName=a??`withAIHint(${s.displayName??s.name??"Component"})`,l}function Ye(s){return ee(s.label??"Text",s.value,{placeholder:s.placeholder,maxLength:s.maxLength})}function Xe(s){return te(s.label??"Number",s.value,{min:s.min,max:s.max,step:s.step})}function Qe(s){return ae(s.label??"Select",s.value,{options:s.options,multiple:s.multiple})}function Ze(s){return se(s.label??"Date",s.value,{min:s.min,max:s.max})}function et(s){return ne(s.label??"Color",s.value)}const tt={id:crypto.randomUUID(),name:"New ML Project",type:"classification",status:"draft",datasets:[],experiments:[],models:[],createdAt:new Date,updatedAt:new Date},re={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"}]},le={classification:["accuracy","precision","recall","f1-score","auc-roc"],regression:["mse","rmse","mae","r2"],clustering:["silhouette","calinski-harabasz","davies-bouldin"]},at=({project:s,onProjectChange:t,onExperimentRun:a,onModelDeploy:l,className:c=""})=>{var j;const[n,v]=d.useState(s||tt),[N,C]=d.useState("data"),[f,I]=d.useState(null),[D,T]=d.useState(null),[k,M]=d.useState(null),[y,z]=d.useState(!1),[h,b]=d.useState({algorithm:"",hyperparameters:{},preprocessing:[]}),g=d.useCallback(i=>{const m={...n,...i,updatedAt:new Date};v(m),t==null||t(m)},[n,t]),L=async i=>{for(const m of Array.from(i)){const w={id:crypto.randomUUID(),name:m.name.replace(/\.[^.]+$/,""),type:"tabular",source:{type:"file",uri:m.name},size:m.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(m.name.endsWith(".csv")){const E=(await m.text()).split(`
11
- `),G=E[0].split(",").map(K=>K.trim());w.rowCount=E.length-1,w.columns=G.map(K=>({name:K,type:"text",nullable:!0,unique:0,missing:0})),w.splits=w.splits.map(K=>({...K,rowCount:Math.floor(w.rowCount*K.ratio)}))}g({datasets:[...n.datasets,w]})}},R=i=>{g({datasets:n.datasets.filter(m=>m.id!==i)}),f===i&&I(null)},$=async()=>{if(!h.algorithm||!f)return;const i={id:crypto.randomUUID(),name:`Experiment ${n.experiments.length+1}`,status:"pending",config:h,metrics:[],artifacts:[],logs:[]};if(g({experiments:[...n.experiments,i]}),z(!1),a){g({experiments:n.experiments.map(m=>m.id===i.id?{...m,status:"running",startedAt:new Date}:m)});try{await a(i);const m=(le[n.type]||le.classification).map(w=>({name:w,value:Math.random()*.3+.7,split:"validation"}));g({experiments:n.experiments.map(w=>w.id===i.id?{...w,status:"completed",completedAt:new Date,metrics:m}:w)})}catch{g({experiments:n.experiments.map(m=>m.id===i.id?{...m,status:"failed"}:m)})}}},F=i=>{const m=n.experiments.find(p=>p.id===i);if(!m)return;const w={id:crypto.randomUUID(),name:`Model from ${m.name}`,version:"1.0.0",algorithm:m.config.algorithm,experimentId:i,status:"registered",metrics:m.metrics,size:Math.floor(Math.random()*100)*1024*1024,artifacts:[],deployments:[],createdAt:new Date};g({models:[...n.models,w]})},B=async i=>{const m=n.models.find(p=>p.id===i);if(!m||!l)return;const w=await l(m);g({models:n.models.map(p=>p.id===i?{...p,status:"production",deployments:[...p.deployments,w]}:p)})},H=i=>i<1024?`${i} B`:i<1024*1024?`${(i/1024).toFixed(1)} KB`:i<1024*1024*1024?`${(i/1024/1024).toFixed(1)} MB`:`${(i/1024/1024/1024).toFixed(1)} GB`,V=i=>{switch(i){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 ${c}`,children:[e.jsxs("header",{className:"ml-studio__header",children:[e.jsxs("div",{className:"header__info",children:[e.jsx("input",{type:"text",value:n.name,onChange:i=>g({name:i.target.value}),className:"project-name-input"}),e.jsxs("select",{value:n.type,onChange:i=>g({type:i.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(i=>e.jsx("button",{className:`tab-button ${N===i?"tab-button--active":""}`,onClick:()=>C(i),children:i.charAt(0).toUpperCase()+i.slice(1)},i))})]}),e.jsxs("div",{className:"ml-studio__content",children:[N==="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:i=>i.target.files&&L(i.target.files),hidden:!0}),"+ Upload Dataset"]})]}),e.jsx("div",{className:"datasets-grid",children:n.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"})]}):n.datasets.map(i=>e.jsxs("div",{className:`dataset-card ${f===i.id?"dataset-card--selected":""}`,onClick:()=>I(i.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("span",{className:"dataset-icon",children:"📁"}),e.jsx("h3",{children:i.name}),e.jsx("button",{className:"remove-button",onClick:m=>{m.stopPropagation(),R(i.id)},children:"×"})]}),e.jsxs("div",{className:"card-stats",children:[e.jsxs("span",{children:[i.rowCount.toLocaleString()," rows"]}),e.jsxs("span",{children:[i.columns.length," columns"]}),e.jsx("span",{children:H(i.size)})]}),e.jsx("div",{className:"splits-bar",children:i.splits.map(m=>e.jsx("div",{className:`split split--${m.name}`,style:{width:`${m.ratio*100}%`},title:`${m.name}: ${(m.ratio*100).toFixed(0)}%`},m.name))})]},i.id))}),f&&e.jsx("div",{className:"dataset-details",children:(()=>{const i=n.datasets.find(m=>m.id===f);return i?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:i.columns.map(m=>e.jsxs("tr",{children:[e.jsx("td",{children:m.name}),e.jsx("td",{children:e.jsxs("select",{value:m.type,onChange:w=>{g({datasets:n.datasets.map(p=>p.id===i.id?{...p,columns:p.columns.map(E=>E.name===m.name?{...E,type:w.target.value}:E)}:p)})},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:m.missing}),e.jsx("td",{children:m.unique})]},m.name))})]})]}):null})()})]}),N==="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:()=>z(!0),disabled:n.datasets.length===0,children:"+ New Experiment"})]}),y&&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:i=>I(i.target.value),children:[e.jsx("option",{value:"",children:"Select dataset..."}),n.datasets.map(i=>e.jsx("option",{value:i.id,children:i.name},i.id))]})]}),e.jsxs("label",{children:["Algorithm",e.jsxs("select",{value:h.algorithm,onChange:i=>b({...h,algorithm:i.target.value}),children:[e.jsx("option",{value:"",children:"Select algorithm..."}),(re[n.type]||re.classification).map(i=>e.jsx("option",{value:i.id,children:i.name},i.id))]})]}),f&&e.jsxs("label",{children:["Target Column",e.jsxs("select",{value:h.targetColumn||"",onChange:i=>b({...h,targetColumn:i.target.value}),children:[e.jsx("option",{value:"",children:"Select target..."}),(j=n.datasets.find(i=>i.id===f))==null?void 0:j.columns.map(i=>e.jsx("option",{value:i.name,children:i.name},i.name))]})]})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{className:"secondary-button",onClick:()=>z(!1),children:"Cancel"}),e.jsx("button",{className:"primary-button",onClick:$,disabled:!h.algorithm||!f,children:"Run Experiment"})]})]}),e.jsx("div",{className:"experiments-list",children:n.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"})]}):n.experiments.map(i=>e.jsxs("div",{className:`experiment-card ${D===i.id?"experiment-card--selected":""}`,onClick:()=>T(i.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:i.name}),e.jsx("span",{className:`status-badge ${V(i.status)}`,children:i.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Algorithm: ",i.config.algorithm]}),i.duration&&e.jsxs("span",{children:["Duration: ",Math.round(i.duration),"s"]})]}),i.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:i.metrics.slice(0,3).map(m=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:m.name}),e.jsxs("span",{className:"metric-value",children:[(m.value*100).toFixed(1),"%"]})]},m.name))}),i.status==="completed"&&e.jsx("button",{className:"action-button",onClick:m=>{m.stopPropagation(),F(i.id)},children:"Register Model"})]},i.id))})]}),N==="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:n.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"})]}):n.models.map(i=>e.jsxs("div",{className:`model-card ${k===i.id?"model-card--selected":""}`,onClick:()=>M(i.id),children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:i.name}),e.jsx("span",{className:`status-badge ${V(i.status)}`,children:i.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Algorithm: ",i.algorithm]}),e.jsxs("span",{children:["Version: ",i.version]}),e.jsxs("span",{children:["Size: ",H(i.size)]})]}),i.metrics.length>0&&e.jsx("div",{className:"metrics-row",children:i.metrics.slice(0,3).map(m=>e.jsxs("div",{className:"metric-item",children:[e.jsx("span",{className:"metric-name",children:m.name}),e.jsxs("span",{className:"metric-value",children:[(m.value*100).toFixed(1),"%"]})]},m.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:m=>{m.stopPropagation(),B(i.id)},disabled:i.status==="production",children:i.status==="production"?"Deployed":"Deploy"})]})]},i.id))})]}),N==="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:n.models.filter(i=>i.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"})]}):n.models.filter(i=>i.deployments.length>0).flatMap(i=>i.deployments.map(m=>({model:i,deployment:m}))).map(({model:i,deployment:m})=>e.jsxs("div",{className:"deployment-card",children:[e.jsxs("div",{className:"card-header",children:[e.jsx("h3",{children:m.name}),e.jsx("span",{className:`status-badge ${V(m.status)}`,children:m.status})]}),e.jsxs("div",{className:"card-meta",children:[e.jsxs("span",{children:["Model: ",i.name]}),e.jsxs("span",{children:["Endpoint: ",m.endpoint]})]}),e.jsxs("div",{className:"resources-info",children:[e.jsxs("span",{children:["CPU: ",m.resources.cpu," cores"]}),e.jsxs("span",{children:["Memory: ",m.resources.memory," GB"]}),e.jsxs("span",{children:["Replicas: ",m.resources.replicas]})]})]},m.id))})]})]})]})},st={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},ce=["#ef4444","#f97316","#f59e0b","#84cc16","#22c55e","#14b8a6","#06b6d4","#3b82f6","#6366f1","#8b5cf6","#a855f7","#d946ef","#ec4899","#f43f5e"],nt=({project:s,onProjectChange:t,onLabelSave:a,onExport:l,className:c=""})=>{var W;const[n,v]=d.useState(s||st),[N,C]=d.useState("label"),[f,I]=d.useState(0),[D,T]=d.useState(null),[k,M]=d.useState("select"),[y,z]=d.useState(!1),[h,b]=d.useState(null),[g,L]=d.useState(1),[R,$]=d.useState(!1),[F,B]=d.useState("all"),H=d.useRef(null),V=d.useRef(null),j=n.items[f];d.useEffect(()=>{s&&v(s)},[s]);const i=d.useCallback(r=>{const u={...n,...r};u.statistics={totalItems:u.items.length,labeled:u.items.filter(x=>x.status!=="pending").length,reviewed:u.items.filter(x=>x.status==="review"||x.status==="approved").length,approved:u.items.filter(x=>x.status==="approved").length,byClass:u.labelSchema.classes.map(x=>({classId:x.id,count:u.items.flatMap(A=>A.labels).filter(A=>A.classId===x.id).length}))},v(u),t==null||t(u)},[n,t]),m=()=>{const r={id:crypto.randomUUID(),name:`Class ${n.labelSchema.classes.length+1}`,color:ce[n.labelSchema.classes.length%ce.length],shortcut:String(n.labelSchema.classes.length+1)};i({labelSchema:{...n.labelSchema,classes:[...n.labelSchema.classes,r]}})},w=r=>{i({labelSchema:{...n.labelSchema,classes:n.labelSchema.classes.filter(u=>u.id!==r)},items:n.items.map(u=>({...u,labels:u.labels.filter(x=>x.classId!==r)}))})},p=(r,u)=>{i({labelSchema:{...n.labelSchema,classes:n.labelSchema.classes.map(x=>x.id===r?{...x,...u}:x)}})},E=(r,u)=>{if(!j)return;const x={id:crypto.randomUUID(),classId:r,type:n.type==="classification"?"class":n.type==="bounding-box"?"bbox":"class",data:u||{},createdBy:"current-user",createdAt:new Date},A={...j,labels:[...j.labels,x],status:"labeled"};i({items:n.items.map(U=>U.id===j.id?A:U)}),a==null||a(A)},G=r=>{if(!j)return;const u={...j,labels:j.labels.filter(x=>x.id!==r),status:j.labels.length<=1?"pending":"labeled"};i({items:n.items.map(x=>x.id===j.id?u:x)})},K=r=>{var U;if(k!=="bbox"||!D)return;const u=(U=H.current)==null?void 0:U.getBoundingClientRect();if(!u)return;const x=(r.clientX-u.left)/g,A=(r.clientY-u.top)/g;z(!0),b({x,y:A,width:0,height:0})},X=r=>{var U;if(!y||!h)return;const u=(U=H.current)==null?void 0:U.getBoundingClientRect();if(!u)return;const x=(r.clientX-u.left)/g,A=(r.clientY-u.top)/g;b({...h,width:x-h.x,height:A-h.y})},o=()=>{!y||!h||!D||(z(!1),Math.abs(h.width)>10&&Math.abs(h.height)>10&&E(D,{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)}),b(null))},S=r=>{const u=F==="all"?n.items:n.items.filter(A=>A.status===F),x=u.findIndex(A=>A.id===(j==null?void 0:j.id));if(r==="prev"&&x>0){const A=u[x-1];I(n.items.findIndex(U=>U.id===A.id))}else if(r==="next"&&x<u.length-1){const A=u[x+1];I(n.items.findIndex(U=>U.id===A.id))}},J=()=>{if(!j)return;const r={...j,status:"approved"};i({items:n.items.map(u=>u.id===j.id?r:u)}),S("next")},O=()=>{if(!j)return;const r={...j,status:"rejected"};i({items:n.items.map(u=>u.id===j.id?r:u)}),S("next")},P=async r=>{l&&await l(r)};d.useEffect(()=>{const r=u=>{const x=u.key,A=n.labelSchema.classes.find(U=>U.shortcut===x);A&&(n.type==="classification"?(E(A.id),S("next")):T(A.id)),u.key==="ArrowLeft"||u.key==="a"?S("prev"):(u.key==="ArrowRight"||u.key==="d")&&S("next"),u.key==="Enter"?J():u.key==="Backspace"&&O()};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[j,n.labelSchema.classes,n.type]);const _=r=>{switch(r){case"approved":return"#22c55e";case"labeled":return"#3b82f6";case"review":return"#f59e0b";case"rejected":return"#ef4444";default:return"#6b7280"}};return e.jsxs("div",{className:`nice-data-labeler ${c}`,children:[e.jsxs("header",{className:"labeler__header",children:[e.jsxs("div",{className:"header__info",children:[e.jsx("input",{type:"text",value:n.name,onChange:r=>i({name:r.target.value}),className:"project-name-input"}),e.jsxs("div",{className:"progress-bar",children:[e.jsx("div",{className:"progress-fill",style:{width:`${n.statistics.labeled/Math.max(n.statistics.totalItems,1)*100}%`}}),e.jsxs("span",{className:"progress-text",children:[n.statistics.labeled," / ",n.statistics.totalItems," labeled"]})]})]}),e.jsx("div",{className:"header__tabs",children:["label","schema","review","export"].map(r=>e.jsx("button",{className:`tab-button ${N===r?"tab-button--active":""}`,onClick:()=>C(r),children:r.charAt(0).toUpperCase()+r.slice(1)},r))}),e.jsx("button",{className:"shortcuts-button",onClick:()=>$(!R),children:"⌨️ Shortcuts"})]}),e.jsxs("div",{className:"labeler__content",children:[N==="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 ${k==="select"?"tool-button--active":""}`,onClick:()=>M("select"),children:"↖️ Select"}),(n.type==="bounding-box"||n.type==="multi-label")&&e.jsx("button",{className:`tool-button ${k==="bbox"?"tool-button--active":""}`,onClick:()=>M("bbox"),children:"⬜ Box"}),n.type==="polygon"&&e.jsx("button",{className:`tool-button ${k==="polygon"?"tool-button--active":""}`,onClick:()=>M("polygon"),children:"⬡ Polygon"})]}),e.jsxs("div",{className:"zoom-group",children:[e.jsx("button",{onClick:()=>L(Math.max(.25,g-.25)),children:"-"}),e.jsxs("span",{children:[Math.round(g*100),"%"]}),e.jsx("button",{onClick:()=>L(Math.min(4,g+.25)),children:"+"})]}),e.jsxs("div",{className:"navigation-group",children:[e.jsx("button",{onClick:()=>S("prev"),disabled:f===0,children:"← Prev"}),e.jsxs("span",{children:[f+1," / ",n.items.length]}),e.jsx("button",{onClick:()=>S("next"),disabled:f>=n.items.length-1,children:"Next →"})]})]}),e.jsxs("div",{className:"label-workspace",children:[e.jsx("div",{className:"canvas-container",ref:V,children:j?e.jsxs(e.Fragment,{children:[j.data.type==="image"&&e.jsxs(e.Fragment,{children:[e.jsx("img",{src:j.data.url,alt:"Labeling item",className:"labeling-image",style:{transform:`scale(${g})`}}),e.jsx("canvas",{ref:H,className:"labeling-canvas",onMouseDown:K,onMouseMove:X,onMouseUp:o,onMouseLeave:o,style:{transform:`scale(${g})`,cursor:k==="bbox"?"crosshair":"default"}}),e.jsxs("div",{className:"annotations-overlay",style:{transform:`scale(${g})`},children:[j.labels.filter(r=>r.type==="bbox"&&r.data.x!==void 0).map(r=>{const u=n.labelSchema.classes.find(x=>x.id===r.classId);return e.jsxs("div",{className:"bbox-annotation",style:{left:r.data.x,top:r.data.y,width:r.data.width,height:r.data.height,borderColor:(u==null?void 0:u.color)||"#ff0000"},children:[e.jsx("span",{className:"bbox-label",style:{backgroundColor:(u==null?void 0:u.color)||"#ff0000"},children:u==null?void 0:u.name}),e.jsx("button",{className:"bbox-remove",onClick:()=>G(r.id),children:"×"})]},r.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:(W=n.labelSchema.classes.find(r=>r.id===D))==null?void 0:W.color}})]})]}),j.data.type==="text"&&e.jsx("div",{className:"text-labeling",children:e.jsx("p",{className:"text-content",children:j.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:n.labelSchema.classes.map(r=>e.jsxs("button",{className:`class-button ${D===r.id?"class-button--active":""}`,style:{borderLeftColor:r.color},onClick:()=>{n.type==="classification"?(E(r.id),S("next")):T(r.id)},children:[e.jsx("span",{className:"class-color",style:{backgroundColor:r.color}}),e.jsx("span",{className:"class-name",children:r.name}),r.shortcut&&e.jsx("span",{className:"class-shortcut",children:r.shortcut})]},r.id))}),j&&j.labels.length>0&&e.jsxs("div",{className:"current-labels",children:[e.jsx("h4",{children:"Labels"}),j.labels.map(r=>{const u=n.labelSchema.classes.find(x=>x.id===r.classId);return e.jsxs("div",{className:"label-item",children:[e.jsx("span",{className:"label-color",style:{backgroundColor:u==null?void 0:u.color}}),e.jsx("span",{className:"label-name",children:u==null?void 0:u.name}),e.jsx("button",{onClick:()=>G(r.id),children:"×"})]},r.id)})]}),N==="label"&&j&&e.jsxs("div",{className:"label-actions",children:[e.jsx("button",{className:"approve-button",onClick:J,children:"✓ Approve"}),e.jsx("button",{className:"reject-button",onClick:O,children:"✗ Reject"})]})]})]})]}),N==="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:m,children:"+ Add Class"})]}),e.jsxs("div",{className:"schema-settings",children:[e.jsxs("label",{children:["Labeling Type",e.jsxs("select",{value:n.type,onChange:r=>i({type:r.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:n.dataType,onChange:r=>i({dataType:r.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:n.labelSchema.classes.map((r,u)=>e.jsxs("div",{className:"class-editor",children:[e.jsx("input",{type:"color",value:r.color,onChange:x=>p(r.id,{color:x.target.value}),className:"color-picker"}),e.jsx("input",{type:"text",value:r.name,onChange:x=>p(r.id,{name:x.target.value}),className:"class-name-input",placeholder:"Class name"}),e.jsx("input",{type:"text",value:r.shortcut||"",onChange:x=>p(r.id,{shortcut:x.target.value}),className:"shortcut-input",placeholder:"Key",maxLength:1}),e.jsx("button",{className:"remove-class-button",onClick:()=>w(r.id),children:"🗑️"})]},r.id))}),e.jsxs("div",{className:"guidelines-section",children:[e.jsx("h3",{children:"Labeling Guidelines"}),e.jsx("textarea",{value:n.guidelines||"",onChange:r=>i({guidelines:r.target.value}),placeholder:"Enter labeling guidelines for annotators...",rows:6})]})]}),N==="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:F,onChange:r=>B(r.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:n.items.filter(r=>F==="all"||r.status===F).map((r,u)=>{var x;return e.jsxs("div",{className:`item-card ${f===n.items.indexOf(r)?"item-card--active":""}`,onClick:()=>{I(n.items.indexOf(r)),C("label")},children:[r.data.type==="image"&&e.jsx("img",{src:r.data.url,alt:`Item ${u+1}`,className:"item-thumbnail"}),r.data.type==="text"&&e.jsxs("p",{className:"item-text-preview",children:[(x=r.data.text)==null?void 0:x.slice(0,100),"..."]}),e.jsxs("div",{className:"item-footer",children:[e.jsx("span",{className:"status-dot",style:{backgroundColor:_(r.status)}}),e.jsxs("span",{children:[r.labels.length," labels"]})]})]},r.id)})})]}),N==="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:n.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:n.statistics.labeled}),e.jsx("span",{className:"stat-label",children:"Labeled"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:n.statistics.approved}),e.jsx("span",{className:"stat-label",children:"Approved"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("span",{className:"stat-value",children:n.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:()=>P("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:()=>P("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:()=>P("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:()=>P("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:n.statistics.byClass.map(r=>{const u=n.labelSchema.classes.find(A=>A.id===r.classId),x=r.count/Math.max(n.statistics.labeled,1)*100;return e.jsxs("div",{className:"distribution-row",children:[e.jsx("span",{className:"class-name",style:{color:u==null?void 0:u.color},children:u==null?void 0:u.name}),e.jsx("div",{className:"bar-container",children:e.jsx("div",{className:"bar-fill",style:{width:`${x}%`,backgroundColor:u==null?void 0:u.color}})}),e.jsx("span",{className:"count",children:r.count})]},r.classId)})})]})]})]}),R&&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"})]}),n.labelSchema.classes.map(r=>r.shortcut&&e.jsxs("div",{className:"shortcut-item",children:[e.jsx("span",{className:"keys",children:r.shortcut}),e.jsxs("span",{className:"description",children:["Label as ",r.name]})]},r.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:s,onInference:t,showMetrics:a=!0,showLogs:l=!0,className:c=""})=>{const[n,v]=d.useState(s||it),[N,C]=d.useState("test"),[f,I]=d.useState("text"),[D,T]=d.useState(""),[k,M]=d.useState("{}"),[y,z]=d.useState(null),[h,b]=d.useState({temperature:.7,topK:50,topP:.9,maxTokens:256,threshold:.5}),[g,L]=d.useState(null),[R,$]=d.useState(!1),[F,B]=d.useState(null),[H,V]=d.useState([]),[j,i]=d.useState(null),m=d.useRef(null),w=o=>{var J;const S=(J=o.target.files)==null?void 0:J[0];if(S){const O=new FileReader;O.onload=P=>{var _;z((_=P.target)==null?void 0:_.result)},O.readAsDataURL(S)}},p=async()=>{if(!t){B("No inference handler provided");return}$(!0),B(null),L(null);const o=[];switch(f){case"text":o.push({type:"text",data:D});break;case"image":y&&o.push({type:"image",data:y});break;case"json":try{o.push({type:"json",data:JSON.parse(k)})}catch{B("Invalid JSON input"),$(!1);return}break;case"tabular":try{o.push({type:"tabular",data:JSON.parse(k)})}catch{B("Invalid tabular data"),$(!1);return}break}const S={inputs:o,parameters:h};try{const J=Date.now(),O=await t(S),P=Date.now()-J;L(O),v(_=>({..._,metrics:{..._.metrics,requestsTotal:_.metrics.requestsTotal+1,latencyP50:(_.metrics.latencyP50+P)/2},logs:[{timestamp:new Date,requestId:O.requestId,duration:P,status:"success",inputSize:JSON.stringify(o).length,outputSize:JSON.stringify(O.predictions).length},..._.logs.slice(0,99)]}))}catch(J){const O=J instanceof Error?J.message:"Inference failed";B(O),v(P=>({...P,metrics:{...P.metrics,requestsTotal:P.metrics.requestsTotal+1,errorRate:(P.metrics.errorRate*P.metrics.requestsTotal+1)/(P.metrics.requestsTotal+1)},logs:[{timestamp:new Date,requestId:crypto.randomUUID(),duration:0,status:"error",inputSize:JSON.stringify(o).length,outputSize:0,error:O},...P.logs.slice(0,99)]}))}finally{$(!1)}},E=async o=>{if(t){i(0),V([]);for(let S=0;S<o.length;S++){const J={inputs:[o[S]],parameters:h};try{const O=await t(J);V(P=>[...P,O])}catch(O){console.error("Batch item failed:",O)}i((S+1)/o.length*100)}i(null)}},G=o=>o<1e3?`${o.toFixed(0)}ms`:`${(o/1e3).toFixed(2)}s`,K=o=>o.toLocaleTimeString(),X=(o,S)=>e.jsxs("div",{className:"prediction-item",children:[o.label&&e.jsxs("div",{className:"prediction-label",children:[e.jsx("span",{className:"label-name",children:o.label}),o.confidence!==void 0&&e.jsxs("span",{className:"confidence-badge",style:{backgroundColor:`hsl(${o.confidence*120}, 70%, 40%)`},children:[(o.confidence*100).toFixed(1),"%"]})]}),o.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:o.score.toFixed(4)})]}),o.text&&e.jsx("div",{className:"prediction-text",children:e.jsx("pre",{children:o.text})}),o.bbox&&e.jsx("div",{className:"prediction-bbox",children:e.jsxs("span",{children:["Box: (",o.bbox.x,", ",o.bbox.y,") - ",o.bbox.width,"×",o.bbox.height]})}),o.raw!==void 0&&o.raw!==null&&e.jsxs("details",{className:"raw-output",children:[e.jsx("summary",{children:"Raw Output"}),e.jsx("pre",{children:JSON.stringify(o.raw,null,2)})]})]},S);return e.jsxs("div",{className:`nice-model-inference ${c}`,children:[e.jsxs("header",{className:"inference__header",children:[e.jsxs("div",{className:"header__info",children:[e.jsx("h2",{children:n.name}),e.jsx("span",{className:`status-badge status-badge--${n.status}`,children:n.status})]}),e.jsxs("div",{className:"header__tabs",children:[e.jsx("button",{className:`tab-button ${N==="test"?"tab-button--active":""}`,onClick:()=>C("test"),children:"Test"}),e.jsx("button",{className:`tab-button ${N==="batch"?"tab-button--active":""}`,onClick:()=>C("batch"),children:"Batch"}),a&&e.jsx("button",{className:`tab-button ${N==="metrics"?"tab-button--active":""}`,onClick:()=>C("metrics"),children:"Metrics"}),l&&e.jsx("button",{className:`tab-button ${N==="logs"?"tab-button--active":""}`,onClick:()=>C("logs"),children:"Logs"})]})]}),e.jsxs("div",{className:"inference__content",children:[N==="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(o=>e.jsx("button",{className:`type-button ${f===o?"type-button--active":""}`,onClick:()=>I(o),children:o.charAt(0).toUpperCase()+o.slice(1)},o))}),e.jsxs("div",{className:"input-area",children:[f==="text"&&e.jsx("textarea",{value:D,onChange:o=>T(o.target.value),placeholder:"Enter text input...",rows:6,className:"text-input"}),f==="image"&&e.jsx("div",{className:"image-input",children:y?e.jsxs("div",{className:"image-preview",children:[e.jsx("img",{src:y,alt:"Input preview"}),e.jsx("button",{className:"clear-button",onClick:()=>z(null),children:"Clear"})]}):e.jsxs("label",{className:"upload-zone",children:[e.jsx("input",{ref:m,type:"file",accept:"image/*",onChange:w,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:k,onChange:o=>M(o.target.value),placeholder:f==="json"?`{
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),c=require("react");class Fe{constructor(t={},i){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1,this.config={maxRequestsPerMinute:t.maxRequestsPerMinute??30,maxTokensPerSession:t.maxTokensPerSession??1e4,warnThresholdPercent:t.warnThresholdPercent??80},this.onWarning=i}canRequest(){return this.pruneOldTimestamps(),!(this.timestamps.length>=this.config.maxRequestsPerMinute||this.tokenCount>=this.config.maxTokensPerSession)}recordRequest(){return this.canRequest()?(this.timestamps.push(Date.now()),!0):!1}recordTokens(t){this.tokenCount+=t,this.checkWarning()}getStatus(){this.pruneOldTimestamps();const t=this.config.maxTokensPerSession>0?this.tokenCount/this.config.maxTokensPerSession*100:0,i=this.config.maxRequestsPerMinute>0?this.timestamps.length/this.config.maxRequestsPerMinute*100:0;return{requestsThisMinute:this.timestamps.length,tokensThisSession:this.tokenCount,isLimited:!this.canRequest(),isWarning:t>=this.config.warnThresholdPercent||i>=this.config.warnThresholdPercent}}reset(){this.timestamps=[],this.tokenCount=0,this.warningEmitted=!1}pruneOldTimestamps(){const t=Date.now()-6e4;this.timestamps=this.timestamps.filter(i=>i>t)}checkWarning(){var i;if(this.warningEmitted)return;this.getStatus().isWarning&&(this.warningEmitted=!0,(i=this.onWarning)==null||i.call(this))}}const Be=c.createContext(null);function jt({config:a,rateLimits:t,enabled:i=!0,onRateLimitWarning:r,children:n}){const s=c.useRef(null);s.current||(s.current=new Fe(t,r));const p=c.useCallback(()=>s.current.getStatus(),[]),o=c.useMemo(()=>({config:a,enabled:i,rateLimiter:s.current,getRateLimitStatus:p}),[a,i,p]);return e.jsx(Be.Provider,{value:o,children:n})}function X(){return c.useContext(Be)}async function*Je(a,t){var s,p,o,g,f,j,w,N,S;const i=(s=a.body)==null?void 0:s.getReader();if(!i)throw new Error("Response body is not readable");const r=new TextDecoder;let n="";try{for(;!(t!=null&&t.aborted);){const{done:$,value:k}=await i.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 y=d.slice(5).trim();if(y==="[DONE]"){yield{token:"",done:!0};return}try{const C=JSON.parse(y),m=((g=(o=(p=C.choices)==null?void 0:p[0])==null?void 0:o.delta)==null?void 0:g.content)??"",_=((j=(f=C.choices)==null?void 0:f[0])==null?void 0:j.finish_reason)==="stop";(m||_)&&(yield{token:m,done:_,usage:C.usage})}catch{y&&(yield{token:y,done:!1})}continue}try{const y=JSON.parse(d),C=y.text??y.content??y.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{i.releaseLock()}}async function qe(a){var i,r,n,s;const t=await a.json();if((n=(r=(i=t.choices)==null?void 0:i[0])==null?void 0:r.message)!=null&&n.content)return{text:t.choices[0].message.content,usage:t.usage};if((s=t.message)!=null&&s.content)return{text:t.message.content};if(typeof t.text=="string")return{text:t.text};if(typeof t.content=="string")return{text:t.content};if(typeof t.response=="string")return{text:t.response};throw new Error("Unrecognized AI response format")}const ae=new Map;function $e(a,t){const i=t?{...a,fieldValue:void 0,formContext:void 0}:a;return JSON.stringify(i)}function kt(a,t){const i=[],r=t.systemPrompt??"You are a helpful assistant providing concise contextual hints for form fields. Keep responses short (1-3 sentences). Be specific and actionable.";i.push({role:"system",content:r});const n=[];if(a.fieldLabel&&n.push(`Field: "${a.fieldLabel}"`),a.fieldType&&n.push(`Type: ${a.fieldType}`),!t.privacyMode&&a.fieldValue!==void 0){const p=typeof a.fieldValue=="string"?a.fieldValue:JSON.stringify(a.fieldValue);n.push(`Current value: ${p}`)}a.validationRules&&Object.keys(a.validationRules).length>0&&n.push(`Validation: ${JSON.stringify(a.validationRules)}`),a.schema&&Object.keys(a.schema).length>0&&n.push(`Schema: ${JSON.stringify(a.schema)}`),!t.privacyMode&&a.formContext&&Object.keys(a.formContext).length>0&&n.push(`Form context: ${JSON.stringify(a.formContext)}`),a.customPrompt&&n.push(a.customPrompt);const s=n.length>0?`Provide a helpful hint for this field:
3
+ ${n.join(`
4
+ `)}`:"Provide a helpful suggestion.";return i.push({role:"user",content:s}),i}function V(a={},t={}){a=a??{},t=t??{};const{debounceMs:i=500,disabled:r=!1}=t,n=X(),[s,p]=c.useState(""),[o,g]=c.useState(!1),[f,j]=c.useState(null),[w,N]=c.useState(!1),S=c.useRef(null),$=c.useRef(0),k=c.useCallback(async()=>{var v,A,R;if(!n||!n.enabled||r)return;const{config:d,rateLimiter:y}=n;if(!y.recordRequest()){j("Rate limit exceeded. Please wait before requesting another hint.");return}const C=$e(a,d.privacyMode??!1),m=ae.get(C);if(m){p(m),g(!1),j(null),N(!1);return}(v=S.current)==null||v.abort();const _=new AbortController;S.current=_,g(!0),j(null),p(""),N(!1);const b=kt(a,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,p(z),(A=D.usage)!=null&&A.completion_tokens&&y.recordTokens(D.usage.completion_tokens),D.done))break;if(z.length>0){const D=Math.ceil(z.length/4);y.recordTokens(D)}ae.set(C,z)}else{const z=await qe(M);p(z.text),ae.set(C,z.text),(R=z.usage)!=null&&R.completion_tokens?y.recordTokens(z.usage.completion_tokens):y.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,a,r]);c.useEffect(()=>{if(!n||!n.enabled||r)return;const d=setTimeout(k,i);return()=>clearTimeout(d)},[a==null?void 0:a.fieldLabel,a==null?void 0:a.fieldType,a==null?void 0:a.fieldValue,a==null?void 0:a.customPrompt,i,r,n==null?void 0:n.enabled,$.current]),c.useEffect(()=>()=>{var d;(d=S.current)==null||d.abort()},[]);const P=c.useCallback(()=>{var d;(d=S.current)==null||d.abort(),g(!1),N(!1)},[]),h=c.useCallback(()=>{if(n){const d=$e(a,n.config.privacyMode??!1);ae.delete(d)}$.current+=1,k()},[n,a,k]);return!n||!n.enabled?{text:"",loading:!1,error:null,streaming:!1,abort:()=>{},refresh:()=>{},hint:null,fetchHint:async()=>{}}:{text:s,loading:o,error:f,streaming:w,abort:P,refresh:h,hint:s?{content:s}:null,fetchHint:async()=>{await k()}}}function Nt(){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 Ct(a,t){if(a!=="auto"||!t)return a==="auto"?"top":a;const i=t.top,r=window.innerHeight-t.bottom,n=t.left,s=window.innerWidth-t.right,p=Math.max(i,r,n,s);return p===i?"top":p===r?"bottom":p===s?"right":"left"}function St(a){const t={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 rgba(0,0,0,0.25)",wordWrap:"break-word"};switch(a){case"top":return{...t,bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:6};case"bottom":return{...t,top:"100%",left:"50%",transform:"translateX(-50%)",marginTop:6};case"left":return{...t,right:"100%",top:"50%",transform:"translateY(-50%)",marginRight:6};case"right":return{...t,left:"100%",top:"50%",transform:"translateY(-50%)",marginLeft:6};default:return{...t,bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:6}}}const ke=c.forwardRef(({context:a,position:t="auto",debounceMs:i=500,showOnHover:r=!1,triggerIcon:n,className:s,style:p},o)=>{var C;const g=X(),[f,j]=c.useState(!1),[w,N]=c.useState(!1),S=c.useRef(null),$=c.useRef(null),k=V(a,{debounceMs:i,disabled:!w});c.useEffect(()=>{if(!f)return;const m=_=>{var u,v;const b=_.target;(u=S.current)!=null&&u.contains(b)||(v=$.current)!=null&&v.contains(b)||(j(!1),N(!1))};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[f]),c.useEffect(()=>{if(!f)return;const m=_=>{_.key==="Escape"&&(j(!1),N(!1),k.abort())};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[f,k]);const P=c.useCallback(m=>{if(m.stopPropagation(),r)return;const _=!f;j(_),N(_)},[f,r]),h=c.useCallback(()=>{r&&(j(!0),N(!0))},[r]),d=c.useCallback(()=>{r&&(j(!1),N(!1))},[r]);if(!g||!g.enabled)return null;const y=Ct(t,((C=S.current)==null?void 0:C.getBoundingClientRect())??null);return e.jsxs("span",{ref:o,className:s,style:{position:"relative",display:"inline-flex",...p},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(Nt,{})}),f&&e.jsxs("div",{ref:$,role:"tooltip",className:"ntd-ai-popover",style:St(y),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"})]})]})]})});ke.displayName="NiceAIHintBubble";function Ne(a,t,i){return{fieldLabel:a,fieldType:"text",fieldValue:t,validationRules:{...(i==null?void 0:i.maxLength)!=null?{maxLength:i.maxLength}:{},...i!=null&&i.pattern?{pattern:i.pattern}:{}},customPrompt:i!=null&&i.placeholder?`Placeholder: "${i.placeholder}". Suggest content or correct grammar.`:"Suggest content, correct grammar, or auto-complete the text."}}function Ce(a,t,i){return{fieldLabel:a,fieldType:"number",fieldValue:t,validationRules:{...(i==null?void 0:i.min)!=null?{min:i.min}:{},...(i==null?void 0:i.max)!=null?{max:i.max}:{},...(i==null?void 0:i.step)!=null?{step:i.step}:{}},customPrompt:i!=null&&i.unit?`Unit: ${i.unit}. Suggest a reasonable value or range for this field.`:"Suggest a reasonable value or range for this field based on the label and constraints."}}function Se(a,t,i){return{fieldLabel:a,fieldType:i!=null&&i.multiple?"multi-select":"select",fieldValue:t,schema:i!=null&&i.options?{availableOptions:i.options.slice(0,20).map(r=>r.label)}:{},customPrompt:"Suggest the most likely selection. Explain why this option is recommended."}}function Te(a,t,i){const r=t instanceof Date?t.toISOString().split("T")[0]:t;return{fieldLabel:a,fieldType:"date",fieldValue:r,validationRules:{...i!=null&&i.min?{min:i.min}:{},...i!=null&&i.max?{max:i.max}:{},...i!=null&&i.disableWeekends?{noWeekends:!0}:{}},customPrompt:'Suggest a date. For example: "next business day", "end of month", "in 2 weeks". Explain your suggestion briefly.'}}function Ae(a,t,i){return{fieldLabel:a,fieldType:"color",fieldValue:t,schema:i!=null&&i.palette?{currentPalette:i.palette}:{},customPrompt:i!=null&&i.industry?`Industry: ${i.industry}. Suggest a color palette (3-5 hex colors) suitable for this context.`:"Suggest a color or palette of colors that works well for this context. Provide hex values."}}function Tt(a,t){return{fieldLabel:a,fieldType:"data-grid",schema:{...t!=null&&t.columns?{columns:t.columns}:{},...(t==null?void 0:t.rowCount)!=null?{totalRows:t.rowCount}:{}},formContext:{...t!=null&&t.currentFilters?{filters:t.currentFilters}:{},...t!=null&&t.currentSorts?{sorts:t.currentSorts}:{}},customPrompt:"Suggest column configuration, useful filters, or highlight potential data anomalies."}}function At(a,t){return{fieldLabel:a,fieldType:"chart",schema:{...t!=null&&t.currentType?{chartType:t.currentType}:{},...(t==null?void 0:t.seriesCount)!=null?{series:t.seriesCount}:{},...(t==null?void 0:t.pointCount)!=null?{dataPoints:t.pointCount}:{}},customPrompt:t!=null&&t.dataDescription?`Data: ${t.dataDescription}. Suggest the best chart type and labeling strategy.`:"Suggest the most effective chart type for this data. Explain your recommendation."}}function Ue(a,t){return{fieldLabel:"Form auto-fill",fieldType:"form",schema:{fields:t},customPrompt:`User description: "${a}"
5
+ Parse this description and return suggested values for each field as JSON: { ${t.map(i=>`"${i.label}": "value"`).join(", ")} }`}}function He(a,t,i,r,n){return{fieldLabel:a,fieldType:t,fieldValue:i,validationRules:n==null?void 0:n.rules,customPrompt:`Current validation error: "${r}". Provide a friendly, specific error message with an example of a valid value. Do NOT say "field is required" — instead explain what the user should enter.`}}function Rt(a,t,i){const r=c.useMemo(()=>Ne(a,t,i),[a,t,i==null?void 0:i.placeholder,i==null?void 0:i.maxLength,i==null?void 0:i.pattern]);return V(r,i)}function Mt(a,t,i){const r=c.useMemo(()=>Ce(a,t,i),[a,t,i==null?void 0:i.min,i==null?void 0:i.max,i==null?void 0:i.step,i==null?void 0:i.unit]);return V(r,i)}function Pt(a,t,i){const r=c.useMemo(()=>Se(a,t,i),[a,t,i==null?void 0:i.multiple]);return V(r,i)}function $t(a,t,i){const r=c.useMemo(()=>Te(a,t,i),[a,t,i==null?void 0:i.min,i==null?void 0:i.max,i==null?void 0:i.disableWeekends]);return V(r,i)}function It(a,t,i){const r=c.useMemo(()=>Ae(a,t,i),[a,t,i==null?void 0:i.industry]);return V(r,i)}function zt(a,t,i,r,n){const s=c.useMemo(()=>r?He(a,t,i,r,n):{fieldLabel:a,fieldType:t},[a,t,i,r]);return V(s,{...n,disabled:!r||(n==null?void 0:n.disabled)})}function Lt(a,t,i){const r=c.useMemo(()=>a?Ue(a,t):{fieldLabel:"Form"},[a,t]);return V(r,{...i,disabled:!a||(i==null?void 0:i.disabled)})}function We(a,t,i){const n=(t==null?void 0:t.split(`
6
+ `))??[],s=(i==null?void 0:i.cursorLine)!=null?n.slice(Math.max(0,i.cursorLine-8),i.cursorLine+3).join(`
7
+ `):n.slice(0,8*2).join(`
8
+ `);return{fieldLabel:`Code editor (${a})`,fieldType:"code-editor",fieldValue:s||t,schema:{language:a,...i!=null&&i.framework?{framework:i.framework}:{},...(i==null?void 0:i.cursorLine)!=null?{cursorLine:i.cursorLine,cursorCol:i.cursorCol}:{}},customPrompt:`Language: ${a}${i!=null&&i.framework?`, framework: ${i.framework}`:""}.
9
+ Provide a concise inline completion or improvement hint for the code near the cursor. Limit response to ${(i==null?void 0:i.maxSuggestLines)??5} lines of code. If unsure, suggest the most idiomatic approach for this language/framework.`}}function Ge(a,t,i){var s;const r=(i==null?void 0:i.mode)??"grammar",n={seo:"Analyze this HTML for SEO: missing meta tags, heading hierarchy (h1→h2→h3), keyword density, image alt attributes. Return a prioritized list of improvements.",accessibility:"Audit this HTML for WCAG 2.1 AA issues: missing aria labels, alt text, heading structure, color contrast hints, keyboard navigation. List specific fixes.",grammar:"Fix grammar, punctuation, and writing style in the visible text content. Return the corrected text only (no HTML tags in response).",cleanup:"Clean up malformed, redundant, or overly nested HTML. Simplify structure while preserving semantics and content."};return{fieldLabel:a,fieldType:"html-editor",fieldValue:t==null?void 0:t.slice(0,2e3),schema:{mode:r,...(s=i==null?void 0:i.targetKeywords)!=null&&s.length?{targetKeywords:i.targetKeywords}:{},...i!=null&&i.locale?{locale:i.locale}:{}},customPrompt:n[r]}}function Ve(a,t){const i=(t==null?void 0:t.mode)??"tag",r=`"${a}"`+((t==null?void 0:t.bpm)!=null?`, BPM: ${t.bpm}`:"")+(t!=null&&t.key?`, Key: ${t.key}`:"")+(t!=null&&t.genre?`, Genre: ${t.genre}`:"")+((t==null?void 0:t.duration)!=null?`, Duration: ${t.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: ${a}`,fieldType:"audio",schema:{mode:i,...(t==null?void 0:t.bpm)!=null?{bpm:t.bpm}:{},...t!=null&&t.key?{key:t.key}:{},...(t==null?void 0:t.duration)!=null?{duration:t.duration}:{},...t!=null&&t.genre?{genre:t.genre}:{}},customPrompt:n[i]}}function Ke(a,t){var s;const i=(t==null?void 0:t.mode)??"material",r=(t==null?void 0:t.targetDevice)??"web",n={material:`Scene "${a}", ${(t==null?void 0:t.meshCount)??"?"} meshes. Materials: ${((s=t==null?void 0:t.materials)==null?void 0:s.join(", "))||"none"}. Suggest PBR properties (roughness, metalness, baseColor) and texture maps for each material.`,optimize:`Scene "${a}", triangles: ${(t==null?void 0:t.triangleCount)??"?"}, target: ${r}. Identify budget issues and suggest LOD levels, mesh merging, and texture atlas strategy.`,lighting:`Scene "${a}", target: ${r}. Suggest a complete lighting setup (types, intensity, color, shadow settings) for realistic rendering.`,animation:`Rig in scene "${a}". Suggest animation approach (FK/IK, bone count), keyframe timing and easing curves for natural movement.`};return{fieldLabel:`3D scene: ${a}`,fieldType:"3d-scene",schema:{mode:i,...(t==null?void 0:t.meshCount)!=null?{meshes:t.meshCount}:{},...(t==null?void 0:t.triangleCount)!=null?{triangles:t.triangleCount}:{},...t!=null&&t.targetDevice?{target:t.targetDevice}:{}},customPrompt:n[i]}}function Ye(a,t){const i=(t==null?void 0:t.mode)??"palette",r=(t==null?void 0:t.width)!=null?`${t.width}×${t.height??"?"}px`:"unknown dimensions",n={filter:`Image "${a}" (${r}). Suggest CSS/SVG filter parameters (brightness, contrast, saturate, hue-rotate, blur) as JSON: { brightness, contrast, saturate, hueRotate, blur }.`,palette:`Image "${a}". Extract or suggest a harmonious 5-color palette as JSON: { primary, secondary, accent, background, text }.`,upscale:`Image "${a}" at ${r}. Recommend upscaling strategy: model (ESRGAN/RealSR/SRCNN), scale factor, and expected quality gain.`,"style-transfer":`Image "${a}", target style: "${(t==null?void 0:t.targetStyle)??"artistic"}". Suggest style-transfer settings as JSON: { contentWeight, styleWeight, iterations, patchSize }.`};return{fieldLabel:`Graphics: ${a}`,fieldType:"graphics",schema:{mode:i,...(t==null?void 0:t.width)!=null?{width:t.width,height:t.height}:{},...t!=null&&t.targetStyle?{targetStyle:t.targetStyle}:{}},customPrompt:n[i]}}function Xe(a,t){var i;return{fieldLabel:"Icon search",fieldType:"icon-picker",fieldValue:a,schema:{...t!=null&&t.style?{iconStyle:t.style}:{},...(t==null?void 0:t.limit)!=null?{maxResults:t.limit}:{},...(i=t==null?void 0:t.availableIcons)!=null&&i.length?{sampleIcons:t.availableIcons.slice(0,30)}:{}},customPrompt:`User query: "${a}"
10
+ Return the ${(t==null?void 0:t.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 Ot(a,t,i){const r=c.useMemo(()=>We(a,t,i),[a,t,i==null?void 0:i.cursorLine,i==null?void 0:i.cursorCol,i==null?void 0:i.framework]);return V(r,i)}function Et(a,t,i){const r=c.useMemo(()=>Ge(a,t,i),[a,t,i==null?void 0:i.mode,i==null?void 0:i.locale]);return V(r,i)}function Dt(a,t){const i=c.useMemo(()=>Ve(a,t),[a,t==null?void 0:t.bpm,t==null?void 0:t.key,t==null?void 0:t.duration,t==null?void 0:t.mode]);return V(i,t)}function Ft(a,t){const i=c.useMemo(()=>Ke(a,t),[a,t==null?void 0:t.meshCount,t==null?void 0:t.triangleCount,t==null?void 0:t.targetDevice,t==null?void 0:t.mode]);return V(i,t)}function Bt(a,t){const i=c.useMemo(()=>Ye(a,t),[a,t==null?void 0:t.width,t==null?void 0:t.height,t==null?void 0:t.mode,t==null?void 0:t.targetStyle]);return V(i,t)}function Jt(a,t){const i=c.useMemo(()=>Xe(a,t),[a,t==null?void 0:t.limit,t==null?void 0:t.style]);return V(i,{...t,disabled:!a||(t==null?void 0:t.disabled)})}function Qe(a,t){var s;const i=(t==null?void 0:t.mode)??"npc-decision",r=(t==null?void 0:t.genre)??"fantasy",n={"npc-decision":`You are an AI game director. The NPC "${a}" must make a decision. Available BT nodes: ${JSON.stringify((t==null?void 0:t.btStatus)??[])}. Game state: ${JSON.stringify((t==null?void 0:t.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 "${a}". Game state: ${JSON.stringify((t==null?void 0:t.gameState)??{})}. Max 2 sentences, no narrative descriptions.`,"procedural-level":`You are a ${r} game designer. Suggest a procedural level layout for a zone containing "${a}". 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 "${a}". 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 "${a}". Include: item name, rarity, flavour text, and one special property. Keep it under 80 words.`};return{fieldLabel:a,fieldType:`game-engine:${i}`,fieldValue:t==null?void 0:t.gameState,customPrompt:n[i],schema:{genre:r,mode:i,btNodes:(s=t==null?void 0:t.btStatus)==null?void 0:s.map(p=>p.node)}}}function qt(a,t){const i=c.useMemo(()=>Qe(a,t),[a,t==null?void 0:t.mode,t==null?void 0:t.genre,JSON.stringify(t==null?void 0:t.btStatus),JSON.stringify(t==null?void 0:t.gameState)]);return V(i,t)}function Ze(a,t,i){const r=(i==null?void 0:i.mode)??"layout",n=(i==null?void 0:i.diagramType)??"flowchart",s={layout:`You are a diagram layout optimizer. Given this ${n} with ${a.length} nodes and ${t.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 }] }`},p=a.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)]}}),o=t.map(g=>({id:g.id,src:g.source,tgt:g.target}));return{fieldLabel:`Diagram (${n})`,fieldType:`diagram:${r}`,fieldValue:JSON.stringify({nodes:p,edges:o}),schema:{diagramType:n,mode:r,nodeCount:a.length,edgeCount:t.length,containerSize:i==null?void 0:i.containerSize},customPrompt:s[r]}}function Ut(a,t,i){const r=c.useMemo(()=>Ze(a,t,i),[JSON.stringify(a),JSON.stringify(t),i==null?void 0:i.mode,i==null?void 0:i.diagramType]);return V(r,{...i,disabled:a.length===0||(i==null?void 0:i.disabled)})}function et(a,t){const i=(t==null?void 0:t.mode)??"generate",r=(t==null?void 0:t.presentationType)??"business",n=(t==null?void 0:t.duration)??15,s=Math.ceil(n/2),p={generate:`You are a presentation designer. Create a ${r} presentation outline based on: "${a}". Target audience: ${(t==null?void 0:t.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: "${a}". 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: "${a}". 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: "${a}". Suggest: better flow, stronger opening/closing, clearer data visualization. Return JSON: { improvements: [{ slide: number, issue: string, suggestion: string }], score: number }`};return{fieldLabel:`Presentation (${r})`,fieldType:`presentation:${i}`,fieldValue:a,schema:{presentationType:r,mode:i,duration:n,slideCount:s,audience:t==null?void 0:t.audience,hasData:(t==null?void 0:t.dataContext)!=null},customPrompt:p[i]}}function Ht(a,t){const i=c.useMemo(()=>et(a,t),[a,t==null?void 0:t.mode,t==null?void 0:t.presentationType,t==null?void 0:t.duration,t==null?void 0:t.audience]);return V(i,{...t,disabled:!a||(t==null?void 0:t.disabled)})}function tt(a,t){var n;const i=(t==null?void 0:t.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:a.title??"Slide Design",fieldType:`slide-design:${i}`,fieldValue:JSON.stringify(a),schema:{mode:i,hasElements:(((n=a.elements)==null?void 0:n.length)??0)>0,layout:a.layout,brandColors:t==null?void 0:t.brandColors},customPrompt:r[i]}}function Wt(a,t){const i=c.useMemo(()=>tt(a,t),[JSON.stringify(a),t==null?void 0:t.mode,JSON.stringify(t==null?void 0:t.brandColors)]);return V(i,t)}function Gt(a,t,i){const r=c.forwardRef((n,s)=>{const{aiEnabled:p=!0,aiPosition:o="right",aiPrompt:g,aiDebounceMs:f=500,aiShowOnHover:j=!1,aiTriggerIcon:w,...N}=n,S=c.useMemo(()=>{const $=t(N);return g&&($.customPrompt=g),$},[N,g]);return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[e.jsx(a,{...N,ref:s}),p&&e.jsx(ke,{context:S,position:o,debounceMs:f,showOnHover:j,triggerIcon:w})]})});return r.displayName=i??`withAIHint(${a.displayName??a.name??"Component"})`,r}function Vt(a){return Ne(a.label??"Text",a.value,{placeholder:a.placeholder,maxLength:a.maxLength})}function Kt(a){return Ce(a.label??"Number",a.value,{min:a.min,max:a.max,step:a.step})}function Yt(a){return Se(a.label??"Select",a.value,{options:a.options,multiple:a.multiple})}function Xt(a){return Te(a.label??"Date",a.value,{min:a.min,max:a.max})}function Qt(a){return Ae(a.label??"Color",a.value)}const Zt={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"]},ei=({project:a,onProjectChange:t,onExperimentRun:i,onModelDeploy:r,className:n=""})=>{var R;const[s,p]=c.useState(a||Zt),[o,g]=c.useState("data"),[f,j]=c.useState(null),[w,N]=c.useState(null),[S,$]=c.useState(null),[k,P]=c.useState(!1),[h,d]=c.useState({algorithm:"",hyperparameters:{},preprocessing:[]}),y=c.useCallback(l=>{const x={...s,...l,updatedAt:new Date};p(x),t==null||t(x)},[s,t]),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)}))}y({datasets:[...s.datasets,M]})}},m=l=>{y({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(y({experiments:[...s.experiments,l]}),P(!1),i){y({experiments:s.experiments.map(x=>x.id===l.id?{...x,status:"running",startedAt:new Date}:x)});try{await i(l);const x=(ze[s.type]||ze.classification).map(M=>({name:M,value:Math.random()*.3+.7,split:"validation"}));y({experiments:s.experiments.map(M=>M.id===l.id?{...M,status:"completed",completedAt:new Date,metrics:x}:M)})}catch{y({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};y({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);y({models:s.models.map(z=>z.id===l?{...z,status:"production",deployments:[...z.deployments,M]}:z)})},v=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=>y({name:l.target.value}),className:"project-name-input"}),e.jsxs("select",{value:s.type,onChange:l=>y({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 ${o===l?"tab-button--active":""}`,onClick:()=>g(l),children:l.charAt(0).toUpperCase()+l.slice(1)},l))})]}),e.jsxs("div",{className:"ml-studio__content",children:[o==="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(),m(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:v(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=>{y({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})()})]}),o==="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))})]}),o==="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: ",v(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))})]}),o==="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))})]})]})]})},ti={id:crypto.randomUUID(),name:"New Labeling Project",type:"classification",dataType:"image",status:"setup",labelSchema:{classes:[],attributes:[]},items:[],collaborators:[],statistics:{totalItems:0,labeled:0,reviewed:0,approved:0,byClass:[]},createdAt:new Date},Le=["#ef4444","#f97316","#f59e0b","#84cc16","#22c55e","#14b8a6","#06b6d4","#3b82f6","#6366f1","#8b5cf6","#a855f7","#d946ef","#ec4899","#f43f5e"],ii=({project:a,onProjectChange:t,onLabelSave:i,onExport:r,className:n=""})=>{var Q;const[s,p]=c.useState(a||ti),[o,g]=c.useState("label"),[f,j]=c.useState(0),[w,N]=c.useState(null),[S,$]=c.useState("select"),[k,P]=c.useState(!1),[h,d]=c.useState(null),[y,C]=c.useState(1),[m,_]=c.useState(!1),[b,u]=c.useState("all"),v=c.useRef(null),A=c.useRef(null),R=s.items[f];c.useEffect(()=>{a&&p(a)},[a]);const l=c.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}))},p(L),t==null||t(L)},[s,t]),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(F=>F.id===R.id?O:F)}),i==null||i(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 F;if(S!=="bbox"||!w)return;const L=(F=v.current)==null?void 0:F.getBoundingClientRect();if(!L)return;const E=(T.clientX-L.left)/y,O=(T.clientY-L.top)/y;P(!0),d({x:E,y:O,width:0,height:0})},Y=T=>{var F;if(!k||!h)return;const L=(F=v.current)==null?void 0:F.getBoundingClientRect();if(!L)return;const E=(T.clientX-L.left)/y,O=(T.clientY-L.top)/y;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))},B=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(F=>F.id===O.id))}else if(T==="next"&&E<L.length-1){const O=L[E+1];j(s.items.findIndex(F=>F.id===O.id))}},q=()=>{if(!R)return;const T={...R,status:"approved"};l({items:s.items.map(L=>L.id===R.id?T:L)}),B("next")},W=()=>{if(!R)return;const T={...R,status:"rejected"};l({items:s.items.map(L=>L.id===R.id?T:L)}),B("next")},U=async T=>{r&&await r(T)};c.useEffect(()=>{const T=L=>{const E=L.key,O=s.labelSchema.classes.find(F=>F.shortcut===E);O&&(s.type==="classification"?(D(O.id),B("next")):N(O.id)),L.key==="ArrowLeft"||L.key==="a"?B("prev"):(L.key==="ArrowRight"||L.key==="d")&&B("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"#22c55e";case"labeled":return"#3b82f6";case"review":return"#f59e0b";case"rejected":return"#ef4444";default:return"#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 ${o===T?"tab-button--active":""}`,onClick:()=>g(T),children:T.charAt(0).toUpperCase()+T.slice(1)},T))}),e.jsx("button",{className:"shortcuts-button",onClick:()=>_(!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:()=>$("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,y-.25)),children:"-"}),e.jsxs("span",{children:[Math.round(y*100),"%"]}),e.jsx("button",{onClick:()=>C(Math.min(4,y+.25)),children:"+"})]}),e.jsxs("div",{className:"navigation-group",children:[e.jsx("button",{onClick:()=>B("prev"),disabled:f===0,children:"← Prev"}),e.jsxs("span",{children:[f+1," / ",s.items.length]}),e.jsx("button",{onClick:()=>B("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(${y})`}}),e.jsx("canvas",{ref:v,className:"labeling-canvas",onMouseDown:H,onMouseMove:Y,onMouseUp:I,onMouseLeave:I,style:{transform:`scale(${y})`,cursor:S==="bbox"?"crosshair":"default"}}),e.jsxs("div",{className:"annotations-overlay",style:{transform:`scale(${y})`},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)||"#ff0000"},children:[e.jsx("span",{className:"bbox-label",style:{backgroundColor:(L==null?void 0:L.color)||"#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),B("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)})]}),o==="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"})]})]})]})]}),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: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})]})]}),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: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)})})]}),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:()=>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)})})]})]})]}),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:()=>_(!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))]})]})})]})},ai={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:[]},ri=({endpoint:a,onInference:t,showMetrics:i=!0,showLogs:r=!0,className:n=""})=>{const[s,p]=c.useState(a||ai),[o,g]=c.useState("test"),[f,j]=c.useState("text"),[w,N]=c.useState(""),[S,$]=c.useState("{}"),[k,P]=c.useState(null),[h,d]=c.useState({temperature:.7,topK:50,topP:.9,maxTokens:256,threshold:.5}),[y,C]=c.useState(null),[m,_]=c.useState(!1),[b,u]=c.useState(null),[v,A]=c.useState([]),[R,l]=c.useState(null),x=c.useRef(null),M=I=>{var q;const B=(q=I.target.files)==null?void 0:q[0];if(B){const W=new FileReader;W.onload=U=>{var K;P((K=U.target)==null?void 0:K.result)},W.readAsDataURL(B)}},z=async()=>{if(!t){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 B={inputs:I,parameters:h};try{const q=Date.now(),W=await t(B),U=Date.now()-q;C(W),p(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),p(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(t){l(0),A([]);for(let B=0;B<I.length;B++){const q={inputs:[I[B]],parameters:h};try{const W=await t(q);A(U=>[...U,W])}catch(W){console.error("Batch item failed:",W)}l((B+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,B)=>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)})]})]},B);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:()=>g("test"),children:"Test"}),e.jsx("button",{className:`tab-button ${o==="batch"?"tab-button--active":""}`,onClick:()=>g("batch"),children:"Batch"}),i&&e.jsx("button",{className:`tab-button ${o==="metrics"?"tab-button--active":""}`,onClick:()=>g("metrics"),children:"Metrics"}),r&&e.jsx("button",{className:`tab-button ${o==="logs"?"tab-button--active":""}`,onClick:()=>g("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(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"?`{
12
12
  "key": "value"
13
13
  }`:`[
14
14
  {"col1": "value1", "col2": "value2"}
15
- ]`,rows:10,className:"json-input"})]}),e.jsxs("div",{className:"parameters-section",children:[e.jsx("h4",{children:"Parameters"}),e.jsxs("div",{className:"parameters-grid",children:[e.jsxs("label",{children:["Temperature",e.jsx("input",{type:"number",value:h.temperature,onChange:o=>b({...h,temperature:parseFloat(o.target.value)}),min:"0",max:"2",step:"0.1"})]}),e.jsxs("label",{children:["Top K",e.jsx("input",{type:"number",value:h.topK,onChange:o=>b({...h,topK:parseInt(o.target.value)}),min:"1",max:"100"})]}),e.jsxs("label",{children:["Top P",e.jsx("input",{type:"number",value:h.topP,onChange:o=>b({...h,topP:parseFloat(o.target.value)}),min:"0",max:"1",step:"0.05"})]}),e.jsxs("label",{children:["Threshold",e.jsx("input",{type:"number",value:h.threshold,onChange:o=>b({...h,threshold:parseFloat(o.target.value)}),min:"0",max:"1",step:"0.05"})]})]})]}),e.jsx("button",{className:"run-button",onClick:p,disabled:R||!D&&!y&&k==="{}",children:R?"Running...":"Run Inference"})]}),e.jsxs("div",{className:"output-section",children:[e.jsx("h3",{children:"Output"}),F&&e.jsxs("div",{className:"error-message",children:[e.jsx("span",{className:"error-icon",children:"⚠️"}),F]}),g&&e.jsxs("div",{className:"result-container",children:[e.jsxs("div",{className:"result-meta",children:[e.jsxs("span",{children:["Request ID: ",g.requestId]}),e.jsxs("span",{children:["Latency: ",G(g.latency)]}),e.jsxs("span",{children:["Model: ",g.modelVersion]})]}),e.jsx("div",{className:"predictions-list",children:g.predictions.map((o,S)=>X(o,S))})]}),!F&&!g&&e.jsxs("div",{className:"empty-output",children:[e.jsx("span",{className:"icon",children:"📤"}),e.jsx("p",{children:"Run inference to see results"})]})]})]}),N==="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 o=>{var J;const S=(J=o.target.files)==null?void 0:J[0];if(S){const O=await S.text();try{const P=JSON.parse(O);if(Array.isArray(P)){const _=P.map(W=>({type:"json",data:W}));E(_)}}catch{B("Invalid batch file format")}}},hidden:!0}),e.jsx("span",{className:"upload-icon",children:"📁"}),e.jsx("span",{children:"Upload JSON array file"})]})]}),j!==null&&e.jsxs("div",{className:"batch-progress",children:[e.jsx("div",{className:"progress-bar",children:e.jsx("div",{className:"progress-fill",style:{width:`${j}%`}})}),e.jsxs("span",{children:[Math.round(j),"%"]})]}),H.length>0&&e.jsxs("div",{className:"batch-results",children:[e.jsxs("h3",{children:["Results (",H.length,")"]}),e.jsx("div",{className:"results-list",children:H.map((o,S)=>e.jsxs("div",{className:"batch-result-item",children:[e.jsxs("span",{className:"result-index",children:["#",S+1]}),o.predictions.map((J,O)=>e.jsxs("span",{className:"result-prediction",children:[J.label,": ",(J.confidence||J.score||0*100).toFixed(1),"%"]},O))]},S))})]})]}),N==="metrics"&&a&&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:n.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:n.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:G(n.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:G(n.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:G(n.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:[n.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:[(n.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(o=>e.jsxs("div",{className:"histogram-bar",children:[e.jsx("div",{className:"bar-fill",style:{height:`${Math.min(100,n.metrics.latencyP50*o/100)}px`}}),e.jsxs("span",{className:"percentile-label",children:["P",o]})]},o))})]})]}),N==="logs"&&l&&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:()=>v(o=>({...o,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:n.logs.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"empty-logs",children:"No logs yet"})}):n.logs.map((o,S)=>e.jsxs("tr",{className:`log-row log-row--${o.status}`,children:[e.jsx("td",{children:K(o.timestamp)}),e.jsx("td",{className:"request-id",children:o.requestId.slice(0,8)}),e.jsx("td",{children:G(o.duration)}),e.jsx("td",{children:e.jsx("span",{className:`status-badge status-badge--${o.status}`,children:o.status})}),e.jsxs("td",{children:[o.inputSize," B"]}),e.jsxs("td",{children:[o.outputSize," B"]})]},S))})]})})]})]})]})};exports.NiceAIHintBubble=Z;exports.NiceAIProvider=we;exports.NiceDataLabeler=nt;exports.NiceMLStudio=at;exports.NiceModelInference=rt;exports.RateLimiter=de;exports.build3DSceneContext=je;exports.buildAudioContext=be;exports.buildChartContext=Ae;exports.buildCodeEditorContext=ge;exports.buildColorPickerContext=ne;exports.buildDataGridContext=Re;exports.buildDatePickerContext=se;exports.buildDiagramLayoutContext=Ce;exports.buildFormFillContext=he;exports.buildGameEngineContext=Ne;exports.buildGraphicsContext=ye;exports.buildHtmlEditorContext=fe;exports.buildIconSearchContext=ve;exports.buildNumberInputContext=te;exports.buildPresentationGenerateContext=pe;exports.buildSelectContext=ae;exports.buildSlideDesignContext=Se;exports.buildTextInputContext=ee;exports.buildValidationContext=xe;exports.colorControlContext=et;exports.dateControlContext=Ze;exports.numberControlContext=Xe;exports.parseJSONResponse=me;exports.parseSSEStream=ue;exports.selectControlContext=Qe;exports.textControlContext=Ye;exports.useAI3DHint=Be;exports.useAIAudioHint=Fe;exports.useAICodeHint=qe;exports.useAIColorHint=Oe;exports.useAIContext=Q;exports.useAIDateHint=De;exports.useAIDiagramLayout=Ve;exports.useAIFormFill=Je;exports.useAIGraphicsHint=He;exports.useAIHtmlHint=ze;exports.useAIIconSearch=Ue;exports.useAINpcHint=_e;exports.useAINumberHint=Me;exports.useAIPresentationGenerate=Ge;exports.useAISelectHint=Le;exports.useAISlideDesign=Ke;exports.useAITextHint=Pe;exports.useAIValidation=Ee;exports.useNiceAIHint=q;exports.withAIHint=We;
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:m||!w&&!k&&S==="{}",children:m?"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]}),y&&e.jsxs("div",{className:"result-container",children:[e.jsxs("div",{className:"result-meta",children:[e.jsxs("span",{children:["Request ID: ",y.requestId]}),e.jsxs("span",{children:["Latency: ",J(y.latency)]}),e.jsxs("span",{children:["Model: ",y.modelVersion]})]}),e.jsx("div",{className:"predictions-list",children:y.predictions.map((I,B)=>Y(I,B))})]}),!b&&!y&&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 I=>{var q;const B=(q=I.target.files)==null?void 0:q[0];if(B){const W=await B.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),"%"]})]}),v.length>0&&e.jsxs("div",{className:"batch-results",children:[e.jsxs("h3",{children:["Results (",v.length,")"]}),e.jsx("div",{className:"results-list",children:v.map((I,B)=>e.jsxs("div",{className:"batch-result-item",children:[e.jsxs("span",{className:"result-index",children:["#",B+1]}),I.predictions.map((q,W)=>e.jsxs("span",{className:"result-prediction",children:[q.label,": ",(q.confidence||q.score||0*100).toFixed(1),"%"]},W))]},B))})]})]}),o==="metrics"&&i&&e.jsxs("div",{className:"metrics-panel",children:[e.jsxs("div",{className:"metrics-grid",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:s.metrics.requestsTotal}),e.jsx("span",{className:"metric-label",children:"Total Requests"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children:s.metrics.requestsPerSecond.toFixed(1)}),e.jsx("span",{className:"metric-label",children:"Requests/sec"})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("span",{className:"metric-value",children: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))})]})]}),o==="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:()=>p(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,B)=>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"]})]},B))})]})})]})]})]})};class ie{constructor(t){this.abortController=null,this.config={timeout:3e4,maxRetries:3,retryDelay:1e3,...t}}async healthCheck(){try{return(await this.chat({messages:[{role:"user",content:"Hi"}],maxTokens:5})).choices.length>0}catch{return!1}}async fetchWithRetry(t,i,r=this.config.maxRetries){let n=null;for(let s=0;s<=r;s++)try{this.abortController=new AbortController;const p=setTimeout(()=>{var g;return(g=this.abortController)==null?void 0:g.abort()},this.config.timeout),o=await fetch(t,{...i,signal:this.abortController.signal});if(clearTimeout(p),o.ok)return o;if(o.status>=400&&o.status<500){const g=await o.text();throw new Error(`API Error ${o.status}: ${g}`)}n=new Error(`HTTP ${o.status}`)}catch(p){n=p,s<r&&await this.delay(this.config.retryDelay*(s+1))}throw n??new Error("Request failed after retries")}delay(t){return new Promise(i=>setTimeout(i,t))}async parseSSEStream(t,i,r,n){var g;const s=(g=t.body)==null?void 0:g.getReader();if(!s){n==null||n(new Error("No response body"));return}const p=new TextDecoder;let o="";try{for(;;){const{done:f,value:j}=await s.read();if(f)break;o+=p.decode(j,{stream:!0});const w=o.split(`
16
+ `);o=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);i(this.normalizeStreamChunk($))}catch{}}}r==null||r()}catch(f){n==null||n(f)}finally{s.releaseLock()}}}class it extends ie{constructor(t){super(t),this.type="openai",this.name="OpenAI",this.baseUrl=t.baseUrl||"https://api.openai.com/v1"}async chat(t){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(t))})).json();return this.normalizeResponse(r,t)}async chatStream(t,i,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify({...this.buildRequestBody(t),stream:!0})});await this.parseSSEStream(s,i,r,n)}catch(s){n==null||n(s)}}async listModels(){return((await(await this.fetchWithRetry(`${this.baseUrl}/models`,{method:"GET",headers:{Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers}})).json()).data||[]).filter(r=>r.id.includes("gpt")).map(r=>r.id)}buildRequestBody(t){return{model:t.model||this.config.model||"gpt-4o-mini",messages:t.messages,temperature:t.temperature??.7,max_tokens:t.maxTokens??1024,top_p:t.topP,frequency_penalty:t.frequencyPenalty,presence_penalty:t.presencePenalty,stop:t.stop,functions:t.functions,function_call:t.functionCall}}normalizeResponse(t,i){const r=t;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(t){const i=t;return{id:i.id,choices:i.choices.map(r=>({index:r.index,delta:r.delta,finishReason:r.finish_reason}))}}estimateCost(t,i,r){const n={"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4-turbo":{input:10,output:30},"gpt-4":{input:30,output:60},"gpt-3.5-turbo":{input:.5,output:1.5}},s=Object.keys(n).find(o=>t.includes(o)),p=s?n[s]:n["gpt-4o-mini"];return i/1e6*p.input+r/1e6*p.output}}class at extends ie{constructor(t){super(t),this.type="anthropic",this.name="Anthropic Claude",this.baseUrl=t.baseUrl||"https://api.anthropic.com/v1"}async chat(t){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(t))})).json();return this.normalizeResponse(r)}async chatStream(t,i,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.config.apiKey,"anthropic-version":"2023-06-01",...this.config.headers},body:JSON.stringify({...this.buildRequestBody(t),stream:!0})});await this.parseAnthropicStream(s,i,r,n)}catch(s){n==null||n(s)}}buildRequestBody(t){const i=t.messages.find(n=>n.role==="system"),r=t.messages.filter(n=>n.role!=="system");return{model:t.model||this.config.model||"claude-3-5-sonnet-20241022",max_tokens:t.maxTokens??1024,system:i==null?void 0:i.content,messages:r.map(n=>({role:n.role==="assistant"?"assistant":"user",content:n.content})),temperature:t.temperature??.7}}normalizeResponse(t){const i=t,r=i.content.find(n=>n.type==="text");return{id:i.id,model:i.model,choices:[{index:0,message:{role:"assistant",content:(r==null?void 0:r.text)||""},finishReason:i.stop_reason==="end_turn"?"stop":"length"}],usage:{promptTokens:i.usage.input_tokens,completionTokens:i.usage.output_tokens,totalTokens:i.usage.input_tokens+i.usage.output_tokens},estimatedCost:this.estimateCost(i.model,i.usage.input_tokens,i.usage.output_tokens)}}normalizeStreamChunk(t){var r;const i=t;return{id:"",choices:[{index:i.index||0,delta:{content:((r=i.delta)==null?void 0:r.text)||""},finishReason:i.type==="message_stop"?"stop":null}]}}async parseAnthropicStream(t,i,r,n){var g;const s=(g=t.body)==null?void 0:g.getReader();if(!s){n==null||n(new Error("No response body"));return}const p=new TextDecoder;let o="";try{for(;;){const{done:f,value:j}=await s.read();if(f)break;o+=p.decode(j,{stream:!0});const w=o.split(`
17
+ `);o=w.pop()||"";for(const N of w)if(N.startsWith("data: "))try{const S=JSON.parse(N.slice(6));if(S.type==="content_block_delta")i(this.normalizeStreamChunk(S));else if(S.type==="message_stop"){r==null||r();return}}catch{}}r==null||r()}catch(f){n==null||n(f)}finally{s.releaseLock()}}estimateCost(t,i,r){const n={"claude-3-5-sonnet":{input:3,output:15},"claude-3-5-haiku":{input:.25,output:1.25},"claude-3-opus":{input:15,output:75},"claude-3-sonnet":{input:3,output:15},"claude-3-haiku":{input:.25,output:1.25}},s=Object.keys(n).find(o=>t.includes(o)),p=s?n[s]:n["claude-3-5-sonnet"];return i/1e6*p.input+r/1e6*p.output}}class rt extends ie{constructor(t){if(super(t),this.type="azure-openai",this.name="Azure OpenAI",!t.baseUrl||!t.deployment)throw new Error("Azure OpenAI requires baseUrl and deployment")}async chat(t){const i=`${this.config.baseUrl}/openai/deployments/${this.config.deployment}/chat/completions?api-version=${this.config.apiVersion||"2024-02-01"}`,n=await(await this.fetchWithRetry(i,{method:"POST",headers:{"Content-Type":"application/json","api-key":this.config.apiKey,...this.config.headers},body:JSON.stringify(this.buildRequestBody(t))})).json();return this.normalizeResponse(n)}async chatStream(t,i,r,n){const s=`${this.config.baseUrl}/openai/deployments/${this.config.deployment}/chat/completions?api-version=${this.config.apiVersion||"2024-02-01"}`;try{const p=await this.fetchWithRetry(s,{method:"POST",headers:{"Content-Type":"application/json","api-key":this.config.apiKey,...this.config.headers},body:JSON.stringify({...this.buildRequestBody(t),stream:!0})});await this.parseSSEStream(p,i,r,n)}catch(p){n==null||n(p)}}buildRequestBody(t){return{messages:t.messages,temperature:t.temperature??.7,max_tokens:t.maxTokens??1024,top_p:t.topP,frequency_penalty:t.frequencyPenalty,presence_penalty:t.presencePenalty,stop:t.stop}}normalizeResponse(t){const i=t;return{id:i.id,model:i.model,choices:i.choices.map(r=>({index:r.index,message:r.message,finishReason:r.finish_reason})),usage:{promptTokens:i.usage.prompt_tokens,completionTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens}}}normalizeStreamChunk(t){const i=t;return{id:i.id,choices:i.choices.map(r=>({index:r.index,delta:r.delta,finishReason:r.finish_reason}))}}}class nt extends ie{constructor(t){super(t),this.type="ollama",this.name="Ollama (Local)",this.baseUrl=t.baseUrl||"http://localhost:11434"}async chat(t){const r=await(await this.fetchWithRetry(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json",...this.config.headers},body:JSON.stringify({model:t.model||this.config.model||"llama3",messages:t.messages,stream:!1,options:{temperature:t.temperature??.7,num_predict:t.maxTokens??1024}})})).json();return this.normalizeResponse(r)}async chatStream(t,i,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json",...this.config.headers},body:JSON.stringify({model:t.model||this.config.model||"llama3",messages:t.messages,stream:!0,options:{temperature:t.temperature??.7,num_predict:t.maxTokens??1024}})});await this.parseOllamaStream(s,i,r,n)}catch(s){n==null||n(s)}}async listModels(){try{return((await(await this.fetchWithRetry(`${this.baseUrl}/api/tags`,{method:"GET"})).json()).models||[]).map(r=>r.name)}catch{return[]}}normalizeResponse(t){const i=t;return{id:`ollama-${Date.now()}`,model:i.model,choices:[{index:0,message:i.message,finishReason:i.done?"stop":null}],usage:{promptTokens:i.prompt_eval_count||0,completionTokens:i.eval_count||0,totalTokens:(i.prompt_eval_count||0)+(i.eval_count||0)},estimatedCost:0}}normalizeStreamChunk(t){var r;const i=t;return{id:`ollama-${Date.now()}`,choices:[{index:0,delta:{content:((r=i.message)==null?void 0:r.content)||""},finishReason:i.done?"stop":null}]}}async parseOllamaStream(t,i,r,n){var g;const s=(g=t.body)==null?void 0:g.getReader();if(!s){n==null||n(new Error("No response body"));return}const p=new TextDecoder;let o="";try{for(;;){const{done:f,value:j}=await s.read();if(f)break;o+=p.decode(j,{stream:!0});const w=o.split(`
18
+ `);o=w.pop()||"";for(const N of w)if(N.trim())try{const S=JSON.parse(N);if(i(this.normalizeStreamChunk(S)),S.done){r==null||r();return}}catch{}}r==null||r()}catch(f){n==null||n(f)}finally{s.releaseLock()}}}class st extends ie{constructor(t){super(t),this.type="groq",this.name="Groq",this.baseUrl=t.baseUrl||"https://api.groq.com/openai/v1"}async chat(t){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:t.model||this.config.model||"llama-3.1-70b-versatile",messages:t.messages,temperature:t.temperature??.7,max_tokens:t.maxTokens??1024})})).json();return this.normalizeResponse(r)}async chatStream(t,i,r,n){try{const s=await this.fetchWithRetry(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},body:JSON.stringify({model:t.model||this.config.model||"llama-3.1-70b-versatile",messages:t.messages,temperature:t.temperature??.7,max_tokens:t.maxTokens??1024,stream:!0})});await this.parseSSEStream(s,i,r,n)}catch(s){n==null||n(s)}}normalizeResponse(t){const i=t;return{id:i.id,model:i.model,choices:i.choices.map(r=>({index:r.index,message:r.message,finishReason:r.finish_reason})),usage:{promptTokens:i.usage.prompt_tokens,completionTokens:i.usage.completion_tokens,totalTokens:i.usage.total_tokens},estimatedCost:0}}normalizeStreamChunk(t){const i=t;return{id:i.id,choices:i.choices.map(r=>({index:r.index,delta:r.delta,finishReason:r.finish_reason}))}}}function te(a){switch(a.type){case"openai":return new it(a);case"anthropic":return new at(a);case"azure-openai":return new rt(a);case"ollama":return new nt(a);case"groq":return new st(a);default:throw new Error(`Unsupported provider type: ${a.type}`)}}function G(a){const t=a.endpoint.toLowerCase();let i="custom";t.includes("openai.com")?i="openai":t.includes("anthropic.com")?i="anthropic":t.includes("azure.com")||t.includes("openai.azure.com")?i="azure-openai":t.includes("localhost:11434")||t.includes("ollama")?i="ollama":t.includes("groq.com")&&(i="groq");const r=new URL(a.endpoint),n=`${r.protocol}//${r.host}`;return te({type:i,apiKey:a.apiKey,baseUrl:n,model:a.model,headers:a.headers})}function Z(a,t){for(const n of a.variables)if(n.required&&!(n.name in t)&&!n.default)throw new Error(`Missing required variable: ${n.name}`);const i={};for(const n of a.variables)i[n.name]=t[n.name]??n.default;const r=n=>n.replace(/\{\{(\w+)\}\}/g,(s,p)=>{const o=i[p];return o===void 0?`{{${p}}}`:typeof o=="object"?JSON.stringify(o,null,2):String(o)});return{system:r(a.system),user:r(a.user),metadata:{templateId:a.id,variables:i,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.
19
+ Given column definitions and a natural language query, generate a JSON filter configuration.
20
+
21
+ Available filter operators:
22
+ - equals, notEquals
23
+ - contains, notContains, startsWith, endsWith
24
+ - greaterThan, lessThan, greaterThanOrEqual, lessThanOrEqual
25
+ - between, inList
26
+ - isEmpty, isNotEmpty
27
+ - isNull, isNotNull
28
+
29
+ Output format:
30
+ {
31
+ "filters": [
32
+ {
33
+ "column": "columnId",
34
+ "operator": "operatorName",
35
+ "value": "filterValue"
36
+ }
37
+ ],
38
+ "logic": "and" | "or"
39
+ }
40
+
41
+ Be precise and only use columns that exist. If a query is ambiguous, make reasonable assumptions.`,user:`Columns: {{columns}}
42
+
43
+ Query: "{{query}}"
44
+
45
+ Generate the filter configuration:`,variables:[{name:"columns",description:"JSON array of column definitions with id, label, and type",required:!0,type:"json"},{name:"query",description:"Natural language filter query",required:!0,type:"string"}],examples:[{input:{columns:[{id:"name",label:"Name",type:"string"},{id:"age",label:"Age",type:"number"},{id:"city",label:"City",type:"string"}],query:"people older than 30 from New York"},output:`{
46
+ "filters": [
47
+ { "column": "age", "operator": "greaterThan", "value": 30 },
48
+ { "column": "city", "operator": "equals", "value": "New York" }
49
+ ],
50
+ "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.
52
+ Given columns and a natural language request, generate sort configuration.
53
+
54
+ Output format:
55
+ {
56
+ "sort": [
57
+ { "column": "columnId", "direction": "asc" | "desc" }
58
+ ]
59
+ }
60
+
61
+ Keywords mapping:
62
+ - "highest", "most", "largest", "newest" → desc
63
+ - "lowest", "least", "smallest", "oldest" → asc
64
+ - "alphabetically", "A-Z" → asc
65
+ - "reverse alphabetically", "Z-A" → desc`,user:`Columns: {{columns}}
66
+
67
+ Request: "{{query}}"
68
+
69
+ Generate sort configuration:`,variables:[{name:"columns",description:"Column definitions",required:!0,type:"json"},{name:"query",description:"Natural language sort request",required:!0,type:"string"}],suggestedTemperature:.1,maxTokens:256},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.
70
+
71
+ Available field types:
72
+ - text, email, phone, url, password
73
+ - number, currency, percentage
74
+ - date, time, datetime
75
+ - select, multiselect, radio, checkbox
76
+ - textarea, richtext, markdown
77
+ - file, image
78
+ - slider, rating
79
+ - color, signature
80
+
81
+ Output JSON format:
82
+ {
83
+ "title": "Form Title",
84
+ "description": "Optional description",
85
+ "fields": [
86
+ {
87
+ "id": "fieldId",
88
+ "type": "fieldType",
89
+ "label": "Field Label",
90
+ "required": true/false,
91
+ "placeholder": "Optional placeholder",
92
+ "validation": { "min": 0, "max": 100, "pattern": "regex" },
93
+ "options": [{ "value": "v", "label": "L" }] // for select types
94
+ }
95
+ ],
96
+ "layout": {
97
+ "columns": 1 | 2 | 3,
98
+ "sections": [{ "title": "Section", "fields": ["fieldId1", "fieldId2"] }]
99
+ }
100
+ }`,user:`Create a form for: {{description}}
101
+
102
+ {{#if schema}}
103
+ Existing data schema for reference:
104
+ {{schema}}
105
+ {{/if}}
106
+
107
+ {{#if context}}
108
+ Additional context: {{context}}
109
+ {{/if}}
110
+
111
+ Generate the form configuration:`,variables:[{name:"description",description:"Natural language form description",required:!0,type:"string"},{name:"schema",description:"Optional existing data schema",required:!1,type:"json"},{name:"context",description:"Additional context or requirements",required:!1,type:"string"}],examples:[{input:{description:"Contact form with name, email, and message"},output:`{
112
+ "title": "Contact Us",
113
+ "fields": [
114
+ { "id": "name", "type": "text", "label": "Full Name", "required": true },
115
+ { "id": "email", "type": "email", "label": "Email Address", "required": true },
116
+ { "id": "message", "type": "textarea", "label": "Message", "required": true }
117
+ ],
118
+ "layout": { "columns": 1 }
119
+ }`}],suggestedTemperature:.5,maxTokens:2048},oe={id:"chart-config",name:"Chart Configuration Generator",description:"Generate chart configuration from data description",category:"chart-config",system:`You are a data visualization expert. Generate chart configurations from descriptions.
120
+
121
+ Available chart types:
122
+ - line, area, bar, column
123
+ - pie, donut, funnel
124
+ - scatter, bubble
125
+ - heatmap, treemap
126
+ - radar, polar
127
+ - candlestick (for financial)
128
+ - sankey (for flows)
129
+ - gauge (for KPIs)
130
+
131
+ Output JSON format:
132
+ {
133
+ "type": "chartType",
134
+ "title": "Chart Title",
135
+ "subtitle": "Optional subtitle",
136
+ "data": {
137
+ "source": "fieldName or expression",
138
+ "xAxis": "categoryField",
139
+ "yAxis": "valueField",
140
+ "series": [{ "name": "Series Name", "field": "fieldName" }]
141
+ },
142
+ "options": {
143
+ "legend": true/false,
144
+ "tooltip": true/false,
145
+ "animation": true/false,
146
+ "stacked": true/false,
147
+ "colors": ["#hex1", "#hex2"]
148
+ }
149
+ }`,user:`Request: "{{request}}"
150
+
151
+ {{#if data}}
152
+ Available data fields: {{data}}
153
+ {{/if}}
154
+
155
+ {{#if context}}
156
+ Context: {{context}}
157
+ {{/if}}
158
+
159
+ Generate the chart configuration:`,variables:[{name:"request",description:"Natural language chart request",required:!0,type:"string"},{name:"data",description:"Available data fields",required:!1,type:"json"},{name:"context",description:"Additional context",required:!1,type:"string"}],suggestedTemperature:.4,maxTokens:1024},ce={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
+
161
+ Rules:
162
+ - Match the existing code style
163
+ - Use the same language features and patterns
164
+ - Keep completions concise and focused
165
+ - Do not repeat existing code
166
+ - Only output the completion, not the full code`,user:"Language: {{language}}\n\nContext (code before cursor):\n```{{language}}\n{{prefix}}\n```\n\nContext (code after cursor):\n```{{language}}\n{{suffix}}\n```\n\nComplete the code at the cursor position:",variables:[{name:"language",description:"Programming language",required:!0,type:"string"},{name:"prefix",description:"Code before cursor",required:!0,type:"string"},{name:"suffix",description:"Code after cursor",required:!1,type:"string",default:""}],suggestedModel:"gpt-4o",suggestedTemperature:.2,maxTokens:512},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.
167
+
168
+ Output BPMN-compatible JSON:
169
+ {
170
+ "id": "process-id",
171
+ "name": "Process Name",
172
+ "nodes": [
173
+ {
174
+ "id": "node-id",
175
+ "type": "start" | "end" | "task" | "gateway" | "event",
176
+ "name": "Node Name",
177
+ "description": "Optional description",
178
+ "assignee": "role or person",
179
+ "form": "formId if task has a form"
180
+ }
181
+ ],
182
+ "edges": [
183
+ {
184
+ "id": "edge-id",
185
+ "source": "sourceNodeId",
186
+ "target": "targetNodeId",
187
+ "condition": "optional condition expression"
188
+ }
189
+ ],
190
+ "swimlanes": [
191
+ { "id": "lane-id", "name": "Role/Department", "nodes": ["node-id-1", "node-id-2"] }
192
+ ]
193
+ }
194
+
195
+ Gateway types:
196
+ - exclusive (XOR): one path based on condition
197
+ - parallel (AND): all paths execute
198
+ - inclusive (OR): one or more paths`,user:`Process description: {{description}}
199
+
200
+ {{#if roles}}
201
+ Available roles: {{roles}}
202
+ {{/if}}
203
+
204
+ {{#if systems}}
205
+ Systems involved: {{systems}}
206
+ {{/if}}
207
+
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.
209
+
210
+ Available report elements:
211
+ - header, footer
212
+ - title, subtitle, text
213
+ - table, pivot-table
214
+ - chart (line, bar, pie, etc.)
215
+ - kpi-card, metric
216
+ - image, logo
217
+ - page-break, section-break
218
+
219
+ Output JSON:
220
+ {
221
+ "title": "Report Title",
222
+ "orientation": "portrait" | "landscape",
223
+ "pageSize": "A4" | "Letter",
224
+ "header": { "left": "text", "center": "text", "right": "{{pageNumber}}" },
225
+ "footer": { "center": "© Company {{year}}" },
226
+ "sections": [
227
+ {
228
+ "title": "Section Title",
229
+ "elements": [
230
+ {
231
+ "type": "elementType",
232
+ "config": { ... element-specific config ... }
233
+ }
234
+ ]
235
+ }
236
+ ],
237
+ "dataBindings": {
238
+ "bindingName": "dataSource.field"
239
+ }
240
+ }`,user:`Report request: {{description}}
241
+
242
+ {{#if dataSources}}
243
+ Available data sources: {{dataSources}}
244
+ {{/if}}
245
+
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.
247
+ Generate a complete theme from brand colors following accessibility guidelines.
248
+
249
+ Rules:
250
+ - Ensure WCAG 2.1 AA contrast ratios (4.5:1 for text, 3:1 for large text)
251
+ - Generate semantic colors (success, warning, error, info)
252
+ - Create consistent color scales (50-900)
253
+ - Define both light and dark mode
254
+
255
+ Output JSON:
256
+ {
257
+ "name": "Theme Name",
258
+ "colors": {
259
+ "primary": { "50": "#...", "100": "#...", ..., "900": "#..." },
260
+ "secondary": { ... },
261
+ "neutral": { ... },
262
+ "success": { ... },
263
+ "warning": { ... },
264
+ "error": { ... },
265
+ "info": { ... }
266
+ },
267
+ "typography": {
268
+ "fontFamily": { "heading": "...", "body": "...", "mono": "..." },
269
+ "fontSize": { "xs": "0.75rem", "sm": "0.875rem", ... },
270
+ "fontWeight": { "normal": 400, "medium": 500, "bold": 700 }
271
+ },
272
+ "spacing": { "xs": "0.25rem", "sm": "0.5rem", ... },
273
+ "borderRadius": { "sm": "0.25rem", "md": "0.5rem", ... },
274
+ "shadows": { "sm": "...", "md": "...", "lg": "..." },
275
+ "darkMode": {
276
+ "colors": { ... modified colors for dark mode ... }
277
+ }
278
+ }`,user:`Brand colors:
279
+ - Primary: {{primaryColor}}
280
+ - Secondary: {{secondaryColor}}
281
+ {{#if accentColor}}- Accent: {{accentColor}}{{/if}}
282
+
283
+ {{#if industry}}Industry: {{industry}}{{/if}}
284
+ {{#if style}}Style preference: {{style}}{{/if}}
285
+
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},ve={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
+ Analyze code for accessibility issues and provide fixes.
288
+
289
+ Check for:
290
+ - Missing alt text on images
291
+ - Missing labels on form inputs
292
+ - Insufficient color contrast
293
+ - Missing ARIA attributes
294
+ - Keyboard navigation issues
295
+ - Focus management
296
+ - Heading hierarchy
297
+ - Link text quality
298
+ - Form error handling
299
+
300
+ Output JSON:
301
+ {
302
+ "issues": [
303
+ {
304
+ "line": 42,
305
+ "severity": "error" | "warning" | "info",
306
+ "rule": "WCAG criterion (e.g., 1.1.1)",
307
+ "message": "Description of issue",
308
+ "fix": "Suggested fix (code snippet)"
309
+ }
310
+ ],
311
+ "score": 0-100,
312
+ "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.
314
+ Translate text while:
315
+ - Preserving placeholders like {name}, {{count}}, %s
316
+ - Maintaining ICU message format syntax
317
+ - Keeping appropriate tone for UI (concise, clear)
318
+ - Preserving HTML/markdown formatting
319
+ - Using proper plural forms for the target language
320
+
321
+ Output JSON:
322
+ {
323
+ "translations": {
324
+ "key": "translated text"
325
+ },
326
+ "notes": "Optional translator notes"
327
+ }`,user:`Translate from {{sourceLanguage}} to {{targetLanguage}}:
328
+
329
+ {{texts}}
330
+
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.
332
+
333
+ Provide:
334
+ - Key statistics (min, max, mean, median)
335
+ - Trends and patterns
336
+ - Anomalies and outliers
337
+ - Comparisons if multiple periods/groups
338
+ - Business recommendations
339
+
340
+ Format output as structured JSON:
341
+ {
342
+ "summary": "One paragraph executive summary",
343
+ "keyMetrics": [
344
+ { "name": "Metric Name", "value": "123", "trend": "up" | "down" | "stable" }
345
+ ],
346
+ "insights": [
347
+ { "type": "trend" | "anomaly" | "comparison", "text": "Insight text" }
348
+ ],
349
+ "recommendations": ["Action item 1", "Action item 2"]
350
+ }`,user:`Analyze this data:
351
+ {{data}}
352
+
353
+ {{#if context}}Context: {{context}}{{/if}}
354
+
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,[oe.id]:oe,[ce.id]:ce,[le.id]:le,[de.id]:de,[ue.id]:ue,[ve.id]:ve,[_e.id]:_e,[we.id]:we};function ni(a){return he[a]}function si(a){return Object.values(he).filter(t=>t.category===a)}function oi(){return Object.keys(he)}class Re{constructor(){this.records=new Map}async save(t,i){const r=this.records.get(t)||[];this.records.set(t,[...r,...i])}async load(t,i,r){const n=this.records.get(t)||[];return!i&&!r?n:n.filter(s=>!(i&&s.timestamp<i.getTime()||r&&s.timestamp>r.getTime()))}async clear(t,i){if(!i)this.records.delete(t);else{const r=this.records.get(t)||[];this.records.set(t,r.filter(n=>n.timestamp>=i.getTime()))}}}class ot{constructor(){this.prefix="nice2dev-ai-cost:"}async save(t,i){if(typeof window>"u")return;const r=`${this.prefix}${t}`,s=[...JSON.parse(localStorage.getItem(r)||"[]"),...i],p=Date.now()-30*24*60*60*1e3,o=s.filter(g=>g.timestamp>p);localStorage.setItem(r,JSON.stringify(o))}async load(t,i,r){if(typeof window>"u")return[];const n=`${this.prefix}${t}`,s=JSON.parse(localStorage.getItem(n)||"[]");return!i&&!r?s:s.filter(p=>!(i&&p.timestamp<i.getTime()||r&&p.timestamp>r.getTime()))}async clear(t,i){if(typeof window>"u")return;const r=`${this.prefix}${t}`;if(!i)localStorage.removeItem(r);else{const n=JSON.parse(localStorage.getItem(r)||"[]");localStorage.setItem(r,JSON.stringify(n.filter(s=>s.timestamp>=i.getTime())))}}}class ct{constructor(t,i){this.pendingRecords=[],this.flushTimer=null,this.alertCallbacks=[],this.minuteCounter=new Map,this.dayCounter=new Map,this.storage=t||new Re,this.budgetConfig={monthlyBudget:100,dailyBudget:10,maxTokensPerRequest:4096,maxRequestsPerMinute:30,maxRequestsPerDay:1e3,alertThresholds:[50,80,90,100],...i}}async recordUsage(t,i){const r={...i,id:this.generateId(),timestamp:Date.now()};this.pendingRecords.push(r),this.updateCounters(t),this.scheduleFlush(t);const n=await this.getBudgetStatus(t);this.checkAlerts(t,n)}async canMakeRequest(t){const i=await this.getBudgetStatus(t);return i.isOverBudget?{allowed:!1,reason:"Budget exceeded"}:this.budgetConfig.maxRequestsPerMinute&&i.requestsThisMinute>=this.budgetConfig.maxRequestsPerMinute?{allowed:!1,reason:"Rate limit exceeded (per minute)"}:this.budgetConfig.maxRequestsPerDay&&i.requestsToday>=this.budgetConfig.maxRequestsPerDay?{allowed:!1,reason:"Daily request limit exceeded"}:{allowed:!0}}async getBudgetStatus(t){const i=new Date,r=new Date(i.getFullYear(),i.getMonth(),i.getDate()),n=new Date(i.getFullYear(),i.getMonth(),1),s=await this.storage.load(t,r),p=await this.storage.load(t,n),o=s.reduce(($,k)=>$+k.estimatedCost,0),g=p.reduce(($,k)=>$+k.estimatedCost,0),f=this.budgetConfig.dailyBudget||1/0,j=this.budgetConfig.monthlyBudget||1/0,w=f?o/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:o,dailyRemaining:Math.max(0,f-o),dailyPercent:w,monthlyUsed:g,monthlyRemaining:Math.max(0,j-g),monthlyPercent:N,requestsToday:s.length,requestsThisMinute:this.getMinuteCount(t),isOverBudget:o>=f||g>=j,alerts:S}}async getUsageStats(t,i,r){const n=await this.storage.load(t,i,r),s={totalRequests:n.length,totalTokens:0,totalPromptTokens:0,totalCompletionTokens:0,totalCost:0,averageLatency:0,errorCount:0,cacheHitRate:0,byModel:{},byFeature:{},byDay:{}};let p=0,o=0;for(const g of n){s.totalTokens+=g.totalTokens,s.totalPromptTokens+=g.promptTokens,s.totalCompletionTokens+=g.completionTokens,s.totalCost+=g.estimatedCost,p+=g.latencyMs,g.error&&s.errorCount++,g.cached&&o++,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=p/n.length,s.cacheHitRate=o/n.length),s}onAlert(t){return this.alertCallbacks.push(t),()=>{const i=this.alertCallbacks.indexOf(t);i>=0&&this.alertCallbacks.splice(i,1)}}setBudgetConfig(t){this.budgetConfig={...this.budgetConfig,...t}}async clearUsage(t,i){await this.storage.clear(t,i)}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}updateCounters(t){const i=Date.now(),r=i-6e4,n=this.minuteCounter.get(t)||[];n.push(i),this.minuteCounter.set(t,n.filter(o=>o>r));const s=new Date().toISOString().split("T")[0],p=`${t}:${s}`;this.dayCounter.set(p,(this.dayCounter.get(p)||0)+1)}getMinuteCount(t){const r=Date.now()-6e4;return(this.minuteCounter.get(t)||[]).filter(s=>s>r).length}scheduleFlush(t){this.flushTimer||(this.flushTimer=setTimeout(async()=>{this.flushTimer=null,this.pendingRecords.length>0&&(await this.storage.save(t,this.pendingRecords),this.pendingRecords=[])},1e3))}checkAlerts(t,i){if(i.alerts.length!==0)for(const r of i.alerts)for(const n of this.alertCallbacks)try{n(r,i)}catch{}}}function ci(a,t){const i=c.useRef(null),[r,n]=c.useState(null),[s,p]=c.useState(null),[o,g]=c.useState(!0);c.useEffect(()=>{const N=typeof window<"u"?new ot:new Re;i.current=new ct(N,t);const S=i.current.onAlert($=>{console.warn(`[AI Cost Alert] ${$}`)});return()=>{S()}},[]);const f=c.useCallback(async()=>{if(i.current){g(!0);try{const[N,S]=await Promise.all([i.current.getBudgetStatus(a),i.current.getUsageStats(a)]);n(N),p(S)}finally{g(!1)}}},[a]);c.useEffect(()=>{f()},[f]);const j=c.useCallback(async N=>{i.current&&(await i.current.recordUsage(a,N),await f())},[a,f]),w=c.useCallback(async()=>i.current?i.current.canMakeRequest(a):{allowed:!0},[a]);return{status:r,stats:s,loading:o,recordUsage:j,canMakeRequest:w,refresh:f}}class li{constructor(t=100,i=36e5){this.cache=new Map,this.maxSize=t,this.ttl=i}hashRequest(t){const i=JSON.stringify({messages:t.messages,model:t.model,temperature:t.temperature});let r=0;for(let n=0;n<i.length;n++){const s=i.charCodeAt(n);r=(r<<5)-r+s,r=r&r}return r.toString(36)}get(t){const i=this.hashRequest(t),r=this.cache.get(i);return r?Date.now()-r.timestamp>this.ttl?(this.cache.delete(i),null):r.response:null}set(t,i){const r=this.hashRequest(t);if(this.cache.size>=this.maxSize){const n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(r,{request:r,response:i,timestamp:Date.now()})}clear(){this.cache.clear()}}class lt{constructor(t,i){this.backupProviders=[],this.circuitBreakers=new Map,this.primaryProvider=t,this.config={strategies:["retry","failover","cache","graceful-degrade"],maxRetries:3,retryDelay:1e3,backoffMultiplier:2,backupProviders:[],cacheTTL:36e5,offlineConfig:void 0,circuitBreakerThreshold:5,circuitBreakerResetTime:6e4,onFallback:void 0,...i},this.cache=new li(100,this.config.cacheTTL);for(const r of this.config.backupProviders||[])this.backupProviders.push(te(r));this.config.offlineConfig&&(this.offlineProvider=te(this.config.offlineConfig))}async chat(t){if(this.isCircuitOpen(this.primaryProvider.type))return this.executeWithFallback(t,new Error("Circuit breaker open"));try{const i=await this.primaryProvider.chat(t);return this.cache.set(t,i),this.resetCircuitBreaker(this.primaryProvider.type),i}catch(i){return this.recordFailure(this.primaryProvider.type),this.executeWithFallback(t,i)}}async executeWithFallback(t,i){var r,n;for(const s of this.config.strategies)try{const p=await this.executeStrategy(s,t,i);if(p)return(n=(r=this.config).onFallback)==null||n.call(r,s,i),p}catch{}throw new Error(`All fallback strategies failed. Original error: ${i.message}`)}async executeStrategy(t,i,r){switch(t){case"retry":return this.retryStrategy(i);case"failover":return this.failoverStrategy(i);case"cache":return this.cacheStrategy(i);case"offline":return this.offlineStrategy(i);case"graceful-degrade":return this.gracefulDegradeStrategy(i,r);case"circuit-breaker":return this.openCircuitBreaker(this.primaryProvider.type),null;default:return null}}async retryStrategy(t){let i=this.config.retryDelay;for(let r=0;r<this.config.maxRetries;r++){await this.delay(i);try{const n=await this.primaryProvider.chat(t);return this.cache.set(t,n),n}catch{i*=this.config.backoffMultiplier}}return null}async failoverStrategy(t){for(const i of this.backupProviders)if(!this.isCircuitOpen(i.type))try{const r=await i.chat(t);return this.cache.set(t,r),r}catch{this.recordFailure(i.type)}return null}cacheStrategy(t){const i=this.cache.get(t);return i?{...i,id:`cached-${i.id}`}:null}async offlineStrategy(t){if(!this.offlineProvider)return null;try{return await this.offlineProvider.chat(t)}catch{return null}}gracefulDegradeStrategy(t,i){const r=[...t.messages].reverse().find(n=>n.role==="user");return{id:`degraded-${Date.now()}`,model:"fallback",choices:[{index:0,message:{role:"assistant",content:this.generateDegradedResponse((r==null?void 0:r.content)||"",i)},finishReason:"stop"}],usage:{promptTokens:0,completionTokens:0,totalTokens:0}}}generateDegradedResponse(t,i){return t.toLowerCase().includes("filter")||t.toLowerCase().includes("show")?JSON.stringify({filters:[],logic:"and"}):t.toLowerCase().includes("form")||t.toLowerCase().includes("create")?JSON.stringify({title:"Form",fields:[{id:"field1",type:"text",label:"Field 1"}]}):t.toLowerCase().includes("chart")||t.toLowerCase().includes("graph")?JSON.stringify({type:"bar",title:"Chart",data:{source:"data"}}):`I'm sorry, I couldn't process your request at this time. The service is temporarily unavailable. Please try again later or contact support. (Error: ${i.message.substring(0,50)})`}isCircuitOpen(t){const i=this.circuitBreakers.get(t);return i&&i.isOpen?Date.now()-i.lastFailure>this.config.circuitBreakerResetTime?(this.resetCircuitBreaker(t),!1):!0:!1}recordFailure(t){const i=this.circuitBreakers.get(t)||{failures:0,lastFailure:0,isOpen:!1};i.failures++,i.lastFailure=Date.now(),i.failures>=this.config.circuitBreakerThreshold&&(i.isOpen=!0),this.circuitBreakers.set(t,i)}openCircuitBreaker(t){this.circuitBreakers.set(t,{failures:this.config.circuitBreakerThreshold,lastFailure:Date.now(),isOpen:!0})}resetCircuitBreaker(t){this.circuitBreakers.delete(t)}delay(t){return new Promise(i=>setTimeout(i,t))}addBackupProvider(t){this.backupProviders.push(t)}setOfflineProvider(t){this.offlineProvider=t}clearCache(){this.cache.clear()}resetAllCircuitBreakers(){this.circuitBreakers.clear()}getCircuitBreakerStatus(){const t={};for(const[i,r]of this.circuitBreakers)t[i]={...r};return t}async healthCheck(){const t={};t[this.primaryProvider.type]=await this.primaryProvider.healthCheck();for(const i of this.backupProviders)t[`backup-${i.type}`]=await i.healthCheck();return this.offlineProvider&&(t.offline=await this.offlineProvider.healthCheck()),t}}function dt(a,t){const i=te(a);return new lt(i,t)}function di(a,t){const i={strategies:["retry","failover","cache","graceful-degrade"],maxRetries:3,retryDelay:1e3,backoffMultiplier:2,backupProviders:t?[t]:[],circuitBreakerThreshold:5,circuitBreakerResetTime:6e4};return typeof window>"u"&&(i.offlineConfig={type:"ollama",model:"llama3"}),dt(a,i)}function ut(a){const{columns:t,config:i,onFilterGenerated:r,onSortGenerated:n,onError:s}=a,p=X(),[o,g]=c.useState(!1),[f,j]=c.useState(null),[w,N]=c.useState(null),[S,$]=c.useState([]),k=c.useRef(null),P=i||(p==null?void 0:p.config),h=c.useMemo(()=>t.map(m=>({id:m.id,label:m.label,type:m.type,...m.options?{options:m.options}:{}})),[t]),d=c.useCallback(async m=>{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(m);const _=performance.now();(b=k.current)==null||b.abort(),k.current=new AbortController;try{const u=G(P),v=m.toLowerCase(),A=v.includes("sort")||v.includes("order")||v.includes("arrange")||v.includes("by highest")||v.includes("by lowest"),R=v.includes("show")||v.includes("find")||v.includes("filter")||v.includes("where")||v.includes("with")||v.includes("only")||!A,l={type:"combined"};if(R){const x=Z(re,{columns:h,query:m}),M=await u.chat({messages:[{role:"system",content:x.system},{role:"user",content:x.user}],temperature:.2,maxTokens:512}),z=ui(M);z&&(l.filterConfig=z,l.type="filter",r==null||r(z))}if(A){const x=Z(ne,{columns:h,query:m}),M=await u.chat({messages:[{role:"system",content:x.system},{role:"user",content:x.user}],temperature:.1,maxTokens:256}),z=mi(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:m,result:l}]),l}catch(u){const v=u instanceof Error?u.message:"AI request failed",A={type:"filter",error:v,latencyMs:performance.now()-_};return N(A),s==null||s(v),A}finally{g(!1)}},[P,h,r,n,s]),y=c.useCallback(()=>{j(null),N(null)},[]),C=c.useCallback(()=>{var m;(m=k.current)==null||m.abort(),g(!1)},[]);return c.useEffect(()=>()=>{var m;(m=k.current)==null||m.abort()},[]),{processQuery:d,loading:o,lastQuery:f,lastResult:w,history:S,clearResults:y,abort:C,isConfigured:!!P}}function ui(a){var t,i,r;try{const n=((i=(t=a.choices[0])==null?void 0:t.message)==null?void 0:i.content)||"",p=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,o=JSON.parse(p);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 mi(a){var t,i,r;try{const n=((i=(t=a.choices[0])==null?void 0:t.message)==null?void 0:i.content)||"",p=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,o=JSON.parse(p);if(o.sort&&Array.isArray(o.sort))return{sort:o.sort,confidence:o.confidence}}catch{}return null}function pi({columns:a,config:t,onFilter:i,onSort:r,placeholder:n='Ask AI to filter or sort data... (e.g., "show orders from last week")',showHistory:s=!0,showSuggestions:p=!0,className:o,style:g}){const[f,j]=c.useState(""),[w,N]=c.useState(!1),S=c.useRef(null),{processQuery:$,loading:k,lastResult:P,history:h,isConfigured:d}=ut({columns:a,config:t,onFilterGenerated:i,onSortGenerated:r}),y=c.useMemo(()=>{if(!p||a.length===0)return[];const u=[],v=a.filter(x=>x.type==="string");v.length>0&&u.push(`Show ${v[0].label}s containing "example"`);const A=a.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=a.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=a.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)},[a,p]),C=async()=>{!f.trim()||k||(await $(f.trim()),N(!1))},m=u=>{u.key==="Enter"?(u.preventDefault(),C()):u.key==="Escape"&&N(!1)},_=u=>{var v;j(u),N(!1),(v=S.current)==null||v.focus()},b=u=>{j(u),N(!1),$(u)};return d?e.jsxs("div",{className:`nice-datagrid-ai ${o||""}`,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:m,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&&(y.length>0||s&&h.length>0)&&e.jsxs("div",{className:"nice-datagrid-ai__dropdown",children:[p&&y.length>0&&e.jsxs("div",{className:"nice-datagrid-ai__section",children:[e.jsx("div",{className:"nice-datagrid-ai__section-title",children:"Suggestions"}),y.map((u,v)=>e.jsxs("button",{type:"button",className:"nice-datagrid-ai__item",onClick:()=>_(u),children:[e.jsx("span",{className:"nice-datagrid-ai__item-icon",children:"💡"}),u]},v))]}),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,v)=>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:"⚠️"})]},v))]})]}),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:`
356
+ .nice-datagrid-ai {
357
+ position: relative;
358
+ font-family: var(--nice-font-family, system-ui, sans-serif);
359
+ }
360
+
361
+ .nice-datagrid-ai--disabled {
362
+ opacity: 0.5;
363
+ }
364
+
365
+ .nice-datagrid-ai__input-wrapper {
366
+ display: flex;
367
+ align-items: center;
368
+ gap: 8px;
369
+ padding: 8px 12px;
370
+ border: 1px solid var(--nice-border-color, #e0e0e0);
371
+ border-radius: var(--nice-border-radius, 8px);
372
+ background: var(--nice-input-bg, #fff);
373
+ transition: border-color 0.2s, box-shadow 0.2s;
374
+ }
375
+
376
+ .nice-datagrid-ai__input-wrapper:focus-within {
377
+ border-color: var(--nice-primary, #0066cc);
378
+ box-shadow: 0 0 0 3px var(--nice-primary-light, rgba(0, 102, 204, 0.15));
379
+ }
380
+
381
+ .nice-datagrid-ai__icon {
382
+ color: var(--nice-text-muted, #666);
383
+ flex-shrink: 0;
384
+ }
385
+
386
+ .nice-datagrid-ai__input {
387
+ flex: 1;
388
+ border: none;
389
+ background: transparent;
390
+ font-size: 14px;
391
+ outline: none;
392
+ color: var(--nice-text-color, #333);
393
+ }
394
+
395
+ .nice-datagrid-ai__input::placeholder {
396
+ color: var(--nice-text-muted, #999);
397
+ }
398
+
399
+ .nice-datagrid-ai__submit {
400
+ display: flex;
401
+ align-items: center;
402
+ justify-content: center;
403
+ width: 28px;
404
+ height: 28px;
405
+ border: none;
406
+ border-radius: 6px;
407
+ background: var(--nice-primary, #0066cc);
408
+ color: white;
409
+ cursor: pointer;
410
+ transition: background 0.2s, transform 0.1s;
411
+ }
412
+
413
+ .nice-datagrid-ai__submit:hover:not(:disabled) {
414
+ background: var(--nice-primary-dark, #0052a3);
415
+ }
416
+
417
+ .nice-datagrid-ai__submit:active {
418
+ transform: scale(0.95);
419
+ }
420
+
421
+ .nice-datagrid-ai__submit:disabled {
422
+ opacity: 0.5;
423
+ cursor: not-allowed;
424
+ }
425
+
426
+ .nice-datagrid-ai__spinner {
427
+ width: 16px;
428
+ height: 16px;
429
+ border: 2px solid var(--nice-border-color, #e0e0e0);
430
+ border-top-color: var(--nice-primary, #0066cc);
431
+ border-radius: 50%;
432
+ animation: nice-spin 0.8s linear infinite;
433
+ }
434
+
435
+ @keyframes nice-spin {
436
+ to { transform: rotate(360deg); }
437
+ }
438
+
439
+ .nice-datagrid-ai__dropdown {
440
+ position: absolute;
441
+ top: 100%;
442
+ left: 0;
443
+ right: 0;
444
+ margin-top: 4px;
445
+ background: var(--nice-dropdown-bg, #fff);
446
+ border: 1px solid var(--nice-border-color, #e0e0e0);
447
+ border-radius: var(--nice-border-radius, 8px);
448
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
449
+ z-index: 100;
450
+ max-height: 300px;
451
+ overflow-y: auto;
452
+ }
453
+
454
+ .nice-datagrid-ai__section {
455
+ padding: 8px 0;
456
+ }
457
+
458
+ .nice-datagrid-ai__section:not(:last-child) {
459
+ border-bottom: 1px solid var(--nice-border-color, #e0e0e0);
460
+ }
461
+
462
+ .nice-datagrid-ai__section-title {
463
+ padding: 4px 12px;
464
+ font-size: 11px;
465
+ font-weight: 600;
466
+ text-transform: uppercase;
467
+ color: var(--nice-text-muted, #666);
468
+ }
469
+
470
+ .nice-datagrid-ai__item {
471
+ display: flex;
472
+ align-items: center;
473
+ gap: 8px;
474
+ width: 100%;
475
+ padding: 8px 12px;
476
+ border: none;
477
+ background: transparent;
478
+ text-align: left;
479
+ font-size: 13px;
480
+ color: var(--nice-text-color, #333);
481
+ cursor: pointer;
482
+ transition: background 0.15s;
483
+ }
484
+
485
+ .nice-datagrid-ai__item:hover {
486
+ background: var(--nice-hover-bg, #f5f5f5);
487
+ }
488
+
489
+ .nice-datagrid-ai__item-icon {
490
+ flex-shrink: 0;
491
+ }
492
+
493
+ .nice-datagrid-ai__item-error {
494
+ margin-left: auto;
495
+ }
496
+
497
+ .nice-datagrid-ai__result {
498
+ display: flex;
499
+ gap: 8px;
500
+ margin-top: 8px;
501
+ flex-wrap: wrap;
502
+ align-items: center;
503
+ }
504
+
505
+ .nice-datagrid-ai__badge {
506
+ display: inline-flex;
507
+ align-items: center;
508
+ padding: 4px 8px;
509
+ border-radius: 4px;
510
+ font-size: 12px;
511
+ font-weight: 500;
512
+ }
513
+
514
+ .nice-datagrid-ai__badge--filter {
515
+ background: var(--nice-info-light, #e3f2fd);
516
+ color: var(--nice-info, #1976d2);
517
+ }
518
+
519
+ .nice-datagrid-ai__badge--sort {
520
+ background: var(--nice-success-light, #e8f5e9);
521
+ color: var(--nice-success, #2e7d32);
522
+ }
523
+
524
+ .nice-datagrid-ai__latency {
525
+ font-size: 11px;
526
+ color: var(--nice-text-muted, #999);
527
+ }
528
+
529
+ .nice-datagrid-ai__error {
530
+ margin-top: 8px;
531
+ padding: 8px 12px;
532
+ background: var(--nice-error-light, #ffebee);
533
+ color: var(--nice-error, #c62828);
534
+ border-radius: 4px;
535
+ font-size: 13px;
536
+ }
537
+ `})]}):e.jsx("div",{className:`nice-datagrid-ai nice-datagrid-ai--disabled ${o||""}`,style:g,children:e.jsx("input",{type:"text",placeholder:"AI not configured",disabled:!0,className:"nice-datagrid-ai__input"})})}function mt(a={}){const{config:t,schema:i,context:r,onFormGenerated:n,onError:s}=a,p=X(),[o,g]=c.useState(!1),[f,j]=c.useState(null),[w,N]=c.useState(null),[S,$]=c.useState([]),k=c.useRef(null),P=t||(p==null?void 0:p.config),h=c.useCallback(async m=>{var b,u,v;if(!P){const A="AI not configured. Provide config or wrap in NiceAIProvider.";return s==null||s(A),{error:A}}g(!0),j(m);const _=performance.now();(b=k.current)==null||b.abort(),k.current=new AbortController;try{const A=G(P),R=Z(se,{description:m,schema:i?JSON.stringify(i,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=hi(l),M={config:x||void 0,rawResponse:(v=(u=l.choices[0])==null?void 0:u.message)==null?void 0:v.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:m,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,i,r,n,s]),d=c.useCallback(async m=>{if(!(w!=null&&w.config))return{error:"No form to refine. Generate a form first."};const _=`
538
+ Modify this existing form based on the following instructions:
539
+
540
+ Current form: ${JSON.stringify(w.config,null,2)}
541
+
542
+ Instructions: ${m}
543
+ `;return h(_)},[w,h]),y=c.useCallback(()=>{j(null),N(null)},[]),C=c.useCallback(()=>{var m;(m=k.current)==null||m.abort(),g(!1)},[]);return c.useEffect(()=>()=>{var m;(m=k.current)==null||m.abort()},[]),{generateForm:h,refineForm:d,loading:o,lastDescription:f,lastResult:w,history:S,clearResults:y,abort:C,isConfigured:!!P}}function hi(a){var t,i,r;try{const n=((i=(t=a.choices[0])==null?void 0:t.message)==null?void 0:i.content)||"",p=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,o=JSON.parse(p);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 gi({config:a,schema:t,context:i,onGenerate:r,placeholder:n='Describe the form you want to create... (e.g., "Contact form with name, email, subject, and message")',showExamples:s=!0,showPreview:p=!0,className:o,style:g,renderForm:f}){const[j,w]=c.useState(""),[N,S]=c.useState(!1),$=c.useRef(null),{generateForm:k,loading:P,lastResult:h,isConfigured:d}=mt({config:a,schema:t,context:i,onFormGenerated:r}),y=["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())},m=u=>{var v;w(u),S(!1),(v=$.current)==null||v.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 ${o||""}`,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:y.map((u,v)=>e.jsx("button",{type:"button",className:"nice-form-builder-ai__dropdown-item",onClick:()=>m(u),children:u},v))})]}),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}),p&&e.jsx("div",{className:"nice-form-builder-ai__preview",children:f?f(h.config):e.jsx(fi,{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:`
544
+ .nice-form-builder-ai {
545
+ font-family: var(--nice-font-family, system-ui, sans-serif);
546
+ }
547
+
548
+ .nice-form-builder-ai--disabled {
549
+ padding: 20px;
550
+ background: var(--nice-disabled-bg, #f5f5f5);
551
+ border-radius: 8px;
552
+ color: var(--nice-text-muted, #666);
553
+ }
554
+
555
+ .nice-form-builder-ai__input-section {
556
+ margin-bottom: 20px;
557
+ }
558
+
559
+ .nice-form-builder-ai__label {
560
+ display: flex;
561
+ align-items: center;
562
+ gap: 8px;
563
+ margin-bottom: 8px;
564
+ font-weight: 600;
565
+ color: var(--nice-text-color, #333);
566
+ }
567
+
568
+ .nice-form-builder-ai__input-wrapper {
569
+ border: 1px solid var(--nice-border-color, #e0e0e0);
570
+ border-radius: 8px;
571
+ overflow: hidden;
572
+ background: var(--nice-input-bg, #fff);
573
+ }
574
+
575
+ .nice-form-builder-ai__input-wrapper:focus-within {
576
+ border-color: var(--nice-primary, #0066cc);
577
+ box-shadow: 0 0 0 3px var(--nice-primary-light, rgba(0, 102, 204, 0.15));
578
+ }
579
+
580
+ .nice-form-builder-ai__textarea {
581
+ width: 100%;
582
+ min-height: 60px;
583
+ padding: 12px;
584
+ border: none;
585
+ background: transparent;
586
+ font-size: 14px;
587
+ resize: none;
588
+ outline: none;
589
+ color: var(--nice-text-color, #333);
590
+ }
591
+
592
+ .nice-form-builder-ai__actions {
593
+ display: flex;
594
+ gap: 8px;
595
+ padding: 8px 12px;
596
+ background: var(--nice-bg-subtle, #f8f9fa);
597
+ border-top: 1px solid var(--nice-border-color, #e0e0e0);
598
+ }
599
+
600
+ .nice-form-builder-ai__btn {
601
+ display: inline-flex;
602
+ align-items: center;
603
+ gap: 6px;
604
+ padding: 8px 16px;
605
+ border: none;
606
+ border-radius: 6px;
607
+ font-size: 14px;
608
+ font-weight: 500;
609
+ cursor: pointer;
610
+ transition: all 0.2s;
611
+ }
612
+
613
+ .nice-form-builder-ai__btn--primary {
614
+ background: var(--nice-primary, #0066cc);
615
+ color: white;
616
+ }
617
+
618
+ .nice-form-builder-ai__btn--primary:hover:not(:disabled) {
619
+ background: var(--nice-primary-dark, #0052a3);
620
+ }
621
+
622
+ .nice-form-builder-ai__btn--secondary {
623
+ background: var(--nice-bg-secondary, #fff);
624
+ border: 1px solid var(--nice-border-color, #e0e0e0);
625
+ color: var(--nice-text-color, #333);
626
+ }
627
+
628
+ .nice-form-builder-ai__btn--success {
629
+ background: var(--nice-success, #2e7d32);
630
+ color: white;
631
+ }
632
+
633
+ .nice-form-builder-ai__btn:disabled {
634
+ opacity: 0.5;
635
+ cursor: not-allowed;
636
+ }
637
+
638
+ .nice-form-builder-ai__examples-wrapper {
639
+ position: relative;
640
+ }
641
+
642
+ .nice-form-builder-ai__dropdown {
643
+ position: absolute;
644
+ bottom: 100%;
645
+ left: 0;
646
+ margin-bottom: 4px;
647
+ min-width: 300px;
648
+ background: white;
649
+ border: 1px solid var(--nice-border-color, #e0e0e0);
650
+ border-radius: 8px;
651
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
652
+ z-index: 100;
653
+ }
654
+
655
+ .nice-form-builder-ai__dropdown-item {
656
+ display: block;
657
+ width: 100%;
658
+ padding: 10px 12px;
659
+ border: none;
660
+ background: transparent;
661
+ text-align: left;
662
+ font-size: 13px;
663
+ color: var(--nice-text-color, #333);
664
+ cursor: pointer;
665
+ transition: background 0.15s;
666
+ }
667
+
668
+ .nice-form-builder-ai__dropdown-item:hover {
669
+ background: var(--nice-hover-bg, #f5f5f5);
670
+ }
671
+
672
+ .nice-form-builder-ai__hint {
673
+ margin-top: 8px;
674
+ font-size: 12px;
675
+ color: var(--nice-text-muted, #666);
676
+ }
677
+
678
+ .nice-form-builder-ai__hint kbd {
679
+ padding: 2px 6px;
680
+ background: var(--nice-bg-subtle, #f0f0f0);
681
+ border-radius: 4px;
682
+ font-family: monospace;
683
+ font-size: 11px;
684
+ }
685
+
686
+ .nice-form-builder-ai__spinner {
687
+ display: inline-block;
688
+ width: 14px;
689
+ height: 14px;
690
+ border: 2px solid currentColor;
691
+ border-top-color: transparent;
692
+ border-radius: 50%;
693
+ animation: nice-spin 0.8s linear infinite;
694
+ }
695
+
696
+ @keyframes nice-spin {
697
+ to { transform: rotate(360deg); }
698
+ }
699
+
700
+ .nice-form-builder-ai__result {
701
+ padding: 20px;
702
+ background: var(--nice-bg-subtle, #f8f9fa);
703
+ border-radius: 8px;
704
+ border: 1px solid var(--nice-border-color, #e0e0e0);
705
+ }
706
+
707
+ .nice-form-builder-ai__result-header {
708
+ display: flex;
709
+ align-items: center;
710
+ gap: 12px;
711
+ margin-bottom: 12px;
712
+ }
713
+
714
+ .nice-form-builder-ai__result-title {
715
+ flex: 1;
716
+ margin: 0;
717
+ font-size: 18px;
718
+ color: var(--nice-text-color, #333);
719
+ }
720
+
721
+ .nice-form-builder-ai__latency {
722
+ font-size: 12px;
723
+ color: var(--nice-text-muted, #666);
724
+ }
725
+
726
+ .nice-form-builder-ai__result-description {
727
+ margin: 0 0 16px;
728
+ color: var(--nice-text-muted, #666);
729
+ }
730
+
731
+ .nice-form-builder-ai__preview {
732
+ padding: 20px;
733
+ background: white;
734
+ border-radius: 8px;
735
+ border: 1px solid var(--nice-border-color, #e0e0e0);
736
+ margin-bottom: 16px;
737
+ }
738
+
739
+ .nice-form-builder-ai__json {
740
+ margin-top: 16px;
741
+ }
742
+
743
+ .nice-form-builder-ai__json summary {
744
+ cursor: pointer;
745
+ color: var(--nice-text-muted, #666);
746
+ font-size: 13px;
747
+ }
748
+
749
+ .nice-form-builder-ai__json pre {
750
+ margin: 8px 0 0;
751
+ padding: 12px;
752
+ background: var(--nice-code-bg, #f5f5f5);
753
+ border-radius: 6px;
754
+ font-size: 12px;
755
+ overflow-x: auto;
756
+ }
757
+
758
+ .nice-form-builder-ai__error {
759
+ padding: 12px;
760
+ background: var(--nice-error-light, #ffebee);
761
+ color: var(--nice-error, #c62828);
762
+ border-radius: 6px;
763
+ }
764
+ `})]}):e.jsx("div",{className:`nice-form-builder-ai nice-form-builder-ai--disabled ${o||""}`,style:g,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function fi({config:a}){var r,n;const t=s=>{var o,g;const p={id:s.id,placeholder:s.placeholder,required:s.required,disabled:!0};switch(s.type){case"textarea":case"richtext":case"markdown":return e.jsx("textarea",{...p,rows:3,className:"nice-form-preview__input nice-form-preview__textarea"});case"select":case"multiselect":return e.jsxs("select",{...p,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(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",...p,className:"nice-form-preview__input"});case"date":return e.jsx("input",{type:"date",...p,className:"nice-form-preview__input"});case"time":return e.jsx("input",{type:"time",...p,className:"nice-form-preview__input"});case"datetime":return e.jsx("input",{type:"datetime-local",...p,className:"nice-form-preview__input"});case"number":case"currency":case"percentage":return e.jsx("input",{type:"number",...p,className:"nice-form-preview__input"});case"email":return e.jsx("input",{type:"email",...p,className:"nice-form-preview__input"});case"phone":return e.jsx("input",{type:"tel",...p,className:"nice-form-preview__input"});case"url":return e.jsx("input",{type:"url",...p,className:"nice-form-preview__input"});case"password":return e.jsx("input",{type:"password",...p,className:"nice-form-preview__input"});case"color":return e.jsx("input",{type:"color",...p,className:"nice-form-preview__input nice-form-preview__color"});case"slider":case"rating":return e.jsx("input",{type:"range",...p,className:"nice-form-preview__input"});default:return e.jsx("input",{type:"text",...p,className:"nice-form-preview__input"})}},i=((r=a.layout)==null?void 0:r.columns)||1;return e.jsxs("form",{className:"nice-form-preview",style:{"--columns":i},children:[(n=a.layout)!=null&&n.sections?a.layout.sections.map((s,p)=>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 g=a.fields.find(f=>f.id===o);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:"*"})]}),t(g)]},g.id):null})})]},p)):e.jsx("div",{className:"nice-form-preview__grid",children:a.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:"*"})]}),t(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:a.submitLabel||"Submit"})}),e.jsx("style",{children:`
765
+ .nice-form-preview {
766
+ --columns: 1;
767
+ }
768
+
769
+ .nice-form-preview__grid {
770
+ display: grid;
771
+ grid-template-columns: repeat(var(--columns), 1fr);
772
+ gap: 16px;
773
+ }
774
+
775
+ .nice-form-preview__section {
776
+ margin-bottom: 24px;
777
+ padding: 16px;
778
+ border: 1px solid var(--nice-border-color, #e0e0e0);
779
+ border-radius: 8px;
780
+ }
781
+
782
+ .nice-form-preview__section legend {
783
+ font-weight: 600;
784
+ padding: 0 8px;
785
+ }
786
+
787
+ .nice-form-preview__section-desc {
788
+ margin: 0 0 12px;
789
+ font-size: 13px;
790
+ color: var(--nice-text-muted, #666);
791
+ }
792
+
793
+ .nice-form-preview__field {
794
+ display: flex;
795
+ flex-direction: column;
796
+ gap: 6px;
797
+ }
798
+
799
+ .nice-form-preview__label {
800
+ font-size: 14px;
801
+ font-weight: 500;
802
+ color: var(--nice-text-color, #333);
803
+ }
804
+
805
+ .nice-form-preview__required {
806
+ color: var(--nice-error, #c62828);
807
+ margin-left: 4px;
808
+ }
809
+
810
+ .nice-form-preview__input {
811
+ padding: 10px 12px;
812
+ border: 1px solid var(--nice-border-color, #e0e0e0);
813
+ border-radius: 6px;
814
+ font-size: 14px;
815
+ background: var(--nice-input-bg, #fff);
816
+ }
817
+
818
+ .nice-form-preview__textarea {
819
+ resize: vertical;
820
+ min-height: 80px;
821
+ }
822
+
823
+ .nice-form-preview__select {
824
+ appearance: none;
825
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23666' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
826
+ background-repeat: no-repeat;
827
+ background-position: right 12px center;
828
+ padding-right: 32px;
829
+ }
830
+
831
+ .nice-form-preview__color {
832
+ width: 60px;
833
+ height: 36px;
834
+ padding: 2px;
835
+ }
836
+
837
+ .nice-form-preview__radio-group {
838
+ display: flex;
839
+ flex-direction: column;
840
+ gap: 8px;
841
+ }
842
+
843
+ .nice-form-preview__radio,
844
+ .nice-form-preview__checkbox {
845
+ display: flex;
846
+ align-items: center;
847
+ gap: 8px;
848
+ font-size: 14px;
849
+ cursor: pointer;
850
+ }
851
+
852
+ .nice-form-preview__submit {
853
+ margin-top: 24px;
854
+ padding-top: 16px;
855
+ border-top: 1px solid var(--nice-border-color, #e0e0e0);
856
+ }
857
+
858
+ .nice-form-preview__submit-btn {
859
+ padding: 12px 24px;
860
+ background: var(--nice-primary, #0066cc);
861
+ color: white;
862
+ border: none;
863
+ border-radius: 6px;
864
+ font-size: 14px;
865
+ font-weight: 500;
866
+ cursor: not-allowed;
867
+ opacity: 0.7;
868
+ }
869
+ `})]})}function pt(a={}){const{config:t,dataFields:i,context:r,onChartGenerated:n,onError:s}=a,p=X(),[o,g]=c.useState(!1),[f,j]=c.useState(null),[w,N]=c.useState(null),[S,$]=c.useState([]),k=c.useRef(null),P=t||(p==null?void 0:p.config),h=c.useMemo(()=>{if(i)return i.map(_=>{var b;return{name:_.name,type:_.type,label:_.label||_.name,...(b=_.sampleValues)!=null&&b.length?{samples:_.sampleValues.slice(0,3)}:{}}})},[i]),d=c.useCallback(async _=>{var u,v,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(oe,{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=xi(x),z={config:M||void 0,rawResponse:(A=(v=x.choices[0])==null?void 0:v.message)==null?void 0:A.content,latencyMs:performance.now()-b,error:M?void 0:"Failed to parse chart configuration",suggestions:bi(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]),y=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]),C=c.useCallback(()=>{j(null),N(null)},[]),m=c.useCallback(()=>{var _;(_=k.current)==null||_.abort(),g(!1)},[]);return c.useEffect(()=>()=>{var _;(_=k.current)==null||_.abort()},[]),{generateChart:d,suggestAlternatives:y,loading:o,lastRequest:f,lastResult:w,history:S,clearResults:C,abort:m,isConfigured:!!P}}function xi(a){var t,i,r;try{const n=((i=(t=a.choices[0])==null?void 0:t.message)==null?void 0:i.content)||"",p=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,o=JSON.parse(p);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 bi(a){var i;if(!a)return[];const t=[];return(a.type==="line"||a.type==="bar")&&(t.push("Add trend line for forecasting"),t.push("Stack series for comparison")),(a.type==="pie"||a.type==="donut")&&(t.push("Convert to bar chart for better comparison"),t.push("Add data labels for percentages")),(i=a.options)!=null&&i.animation||t.push("Enable animations for better UX"),t.slice(0,3)}function yi({config:a,dataFields:t,context:i,onGenerate:r,placeholder:n='Describe the chart you want... (e.g., "Show monthly sales as a line chart")',showTypeSelector:s=!0,showPreview:p=!0,className:o,style:g,renderChart:f}){var v;const[j,w]=c.useState(""),[N,S]=c.useState(null),$=c.useRef(null),{generateChart:k,suggestAlternatives:P,loading:h,lastResult:d,isConfigured:y}=pt({config:a,dataFields:t,context:i,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"}],m=async()=>{if(!j.trim()||h)return;const A=N?`Create a ${N} chart: ${j}`:j;await k(A)},_=A=>{A.key==="Enter"&&(A.preventDefault(),m())},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 y?e.jsxs("div",{className:`nice-chart-ai ${o||""}`,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:m,className:"nice-chart-ai__submit",disabled:!j.trim(),children:"Generate"})]}),t&&t.length>0&&e.jsxs("div",{className:"nice-chart-ai__fields",children:[e.jsx("span",{className:"nice-chart-ai__fields-label",children:"Available fields:"}),t.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:[(v=C.find(A=>A.type===d.config.type))==null?void 0:v.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))]}),p&&e.jsx("div",{className:"nice-chart-ai__preview",children:f?f(d.config):e.jsx(vi,{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
+ .nice-chart-ai {
871
+ font-family: var(--nice-font-family, system-ui, sans-serif);
872
+ }
873
+
874
+ .nice-chart-ai--disabled {
875
+ padding: 20px;
876
+ background: var(--nice-disabled-bg, #f5f5f5);
877
+ border-radius: 8px;
878
+ color: var(--nice-text-muted, #666);
879
+ }
880
+
881
+ .nice-chart-ai__types {
882
+ display: flex;
883
+ flex-wrap: wrap;
884
+ gap: 8px;
885
+ margin-bottom: 12px;
886
+ }
887
+
888
+ .nice-chart-ai__type {
889
+ display: flex;
890
+ flex-direction: column;
891
+ align-items: center;
892
+ gap: 4px;
893
+ padding: 8px 12px;
894
+ border: 1px solid var(--nice-border-color, #e0e0e0);
895
+ border-radius: 8px;
896
+ background: var(--nice-bg-secondary, #fff);
897
+ cursor: pointer;
898
+ transition: all 0.2s;
899
+ }
900
+
901
+ .nice-chart-ai__type:hover {
902
+ border-color: var(--nice-primary, #0066cc);
903
+ }
904
+
905
+ .nice-chart-ai__type--selected {
906
+ border-color: var(--nice-primary, #0066cc);
907
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.1));
908
+ }
909
+
910
+ .nice-chart-ai__type-icon {
911
+ font-size: 20px;
912
+ }
913
+
914
+ .nice-chart-ai__type-label {
915
+ font-size: 11px;
916
+ color: var(--nice-text-muted, #666);
917
+ }
918
+
919
+ .nice-chart-ai__input-wrapper {
920
+ display: flex;
921
+ align-items: center;
922
+ gap: 8px;
923
+ padding: 10px 14px;
924
+ border: 1px solid var(--nice-border-color, #e0e0e0);
925
+ border-radius: 8px;
926
+ background: var(--nice-input-bg, #fff);
927
+ }
928
+
929
+ .nice-chart-ai__input-wrapper:focus-within {
930
+ border-color: var(--nice-primary, #0066cc);
931
+ box-shadow: 0 0 0 3px var(--nice-primary-light, rgba(0, 102, 204, 0.15));
932
+ }
933
+
934
+ .nice-chart-ai__icon {
935
+ font-size: 18px;
936
+ }
937
+
938
+ .nice-chart-ai__input {
939
+ flex: 1;
940
+ border: none;
941
+ background: transparent;
942
+ font-size: 14px;
943
+ outline: none;
944
+ }
945
+
946
+ .nice-chart-ai__submit {
947
+ padding: 8px 16px;
948
+ background: var(--nice-primary, #0066cc);
949
+ color: white;
950
+ border: none;
951
+ border-radius: 6px;
952
+ font-weight: 500;
953
+ cursor: pointer;
954
+ transition: background 0.2s;
955
+ }
956
+
957
+ .nice-chart-ai__submit:hover:not(:disabled) {
958
+ background: var(--nice-primary-dark, #0052a3);
959
+ }
960
+
961
+ .nice-chart-ai__submit:disabled {
962
+ opacity: 0.5;
963
+ cursor: not-allowed;
964
+ }
965
+
966
+ .nice-chart-ai__spinner {
967
+ width: 20px;
968
+ height: 20px;
969
+ border: 2px solid var(--nice-border-color, #e0e0e0);
970
+ border-top-color: var(--nice-primary, #0066cc);
971
+ border-radius: 50%;
972
+ animation: nice-spin 0.8s linear infinite;
973
+ }
974
+
975
+ @keyframes nice-spin {
976
+ to { transform: rotate(360deg); }
977
+ }
978
+
979
+ .nice-chart-ai__fields {
980
+ display: flex;
981
+ flex-wrap: wrap;
982
+ gap: 6px;
983
+ margin-top: 10px;
984
+ align-items: center;
985
+ }
986
+
987
+ .nice-chart-ai__fields-label {
988
+ font-size: 12px;
989
+ color: var(--nice-text-muted, #666);
990
+ }
991
+
992
+ .nice-chart-ai__field-badge {
993
+ padding: 4px 8px;
994
+ background: var(--nice-bg-subtle, #f0f0f0);
995
+ border-radius: 4px;
996
+ font-size: 12px;
997
+ color: var(--nice-text-color, #333);
998
+ }
999
+
1000
+ .nice-chart-ai__result {
1001
+ margin-top: 20px;
1002
+ padding: 16px;
1003
+ background: var(--nice-bg-subtle, #f8f9fa);
1004
+ border-radius: 8px;
1005
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1006
+ }
1007
+
1008
+ .nice-chart-ai__result-header {
1009
+ display: flex;
1010
+ align-items: center;
1011
+ gap: 12px;
1012
+ margin-bottom: 12px;
1013
+ }
1014
+
1015
+ .nice-chart-ai__result-info {
1016
+ flex: 1;
1017
+ display: flex;
1018
+ align-items: center;
1019
+ gap: 8px;
1020
+ }
1021
+
1022
+ .nice-chart-ai__chart-type {
1023
+ display: flex;
1024
+ align-items: center;
1025
+ gap: 6px;
1026
+ padding: 4px 10px;
1027
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.1));
1028
+ border-radius: 6px;
1029
+ font-weight: 500;
1030
+ color: var(--nice-primary, #0066cc);
1031
+ }
1032
+
1033
+ .nice-chart-ai__chart-title {
1034
+ color: var(--nice-text-muted, #666);
1035
+ }
1036
+
1037
+ .nice-chart-ai__latency {
1038
+ font-size: 12px;
1039
+ color: var(--nice-text-muted, #999);
1040
+ }
1041
+
1042
+ .nice-chart-ai__use-btn {
1043
+ padding: 8px 16px;
1044
+ background: var(--nice-success, #2e7d32);
1045
+ color: white;
1046
+ border: none;
1047
+ border-radius: 6px;
1048
+ font-weight: 500;
1049
+ cursor: pointer;
1050
+ }
1051
+
1052
+ .nice-chart-ai__alternatives {
1053
+ display: flex;
1054
+ align-items: center;
1055
+ gap: 8px;
1056
+ margin-bottom: 16px;
1057
+ font-size: 13px;
1058
+ color: var(--nice-text-muted, #666);
1059
+ }
1060
+
1061
+ .nice-chart-ai__alternative {
1062
+ display: flex;
1063
+ align-items: center;
1064
+ justify-content: center;
1065
+ width: 32px;
1066
+ height: 32px;
1067
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1068
+ border-radius: 6px;
1069
+ background: white;
1070
+ font-size: 16px;
1071
+ cursor: pointer;
1072
+ transition: all 0.2s;
1073
+ }
1074
+
1075
+ .nice-chart-ai__alternative:hover {
1076
+ border-color: var(--nice-primary, #0066cc);
1077
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.1));
1078
+ }
1079
+
1080
+ .nice-chart-ai__preview {
1081
+ padding: 20px;
1082
+ background: white;
1083
+ border-radius: 8px;
1084
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1085
+ min-height: 200px;
1086
+ }
1087
+
1088
+ .nice-chart-ai__json {
1089
+ margin-top: 12px;
1090
+ }
1091
+
1092
+ .nice-chart-ai__json summary {
1093
+ cursor: pointer;
1094
+ font-size: 13px;
1095
+ color: var(--nice-text-muted, #666);
1096
+ }
1097
+
1098
+ .nice-chart-ai__json pre {
1099
+ margin: 8px 0 0;
1100
+ padding: 12px;
1101
+ background: var(--nice-code-bg, #f5f5f5);
1102
+ border-radius: 6px;
1103
+ font-size: 12px;
1104
+ overflow-x: auto;
1105
+ }
1106
+
1107
+ .nice-chart-ai__error {
1108
+ padding: 12px;
1109
+ background: var(--nice-error-light, #ffebee);
1110
+ color: var(--nice-error, #c62828);
1111
+ border-radius: 6px;
1112
+ }
1113
+ `})]}):e.jsx("div",{className:`nice-chart-ai nice-chart-ai--disabled ${o||""}`,style:g,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function vi({config:a}){var i;const t=()=>{switch(a.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:"#4CAF50",rx:"2"}),e.jsx("rect",{x:"55",y:"40",width:"25",height:"50",fill:"#2196F3",rx:"2"}),e.jsx("rect",{x:"90",y:"20",width:"25",height:"70",fill:"#FF9800",rx:"2"}),e.jsx("rect",{x:"125",y:"50",width:"25",height:"40",fill:"#9C27B0",rx:"2"}),e.jsx("rect",{x:"160",y:"30",width:"25",height:"60",fill:"#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:"#2196F3",strokeWidth:"3",strokeLinecap:"round"}),a.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:"#2196F3"}),e.jsx("circle",{cx:"80",cy:"50",r:"4",fill:"#2196F3"}),e.jsx("circle",{cx:"140",cy:"40",r:"4",fill:"#2196F3"}),e.jsx("circle",{cx:"180",cy:"60",r:"4",fill:"#2196F3"})]});case"pie":case"donut":const r=a.type==="donut"?35:40,n=a.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:"#4CAF50"}),e.jsx("path",{d:"M 50 50 L 50 10 A 40 40 0 0 1 90 50 Z",fill:"#2196F3"}),e.jsx("path",{d:"M 50 50 L 90 50 A 40 40 0 0 1 70 85 Z",fill:"#FF9800"}),e.jsx("path",{d:"M 50 50 L 70 85 A 40 40 0 0 1 30 85 Z",fill:"#9C27B0"}),a.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:"#2196F3"}),e.jsx("circle",{cx:"50",cy:"40",r:"7",fill:"#4CAF50"}),e.jsx("circle",{cx:"80",cy:"60",r:"4",fill:"#FF9800"}),e.jsx("circle",{cx:"110",cy:"30",r:"6",fill:"#2196F3"}),e.jsx("circle",{cx:"140",cy:"50",r:"5",fill:"#9C27B0"}),e.jsx("circle",{cx:"170",cy:"45",r:"8",fill:"#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:"#e0e0e0",strokeWidth:"8",strokeLinecap:"round"}),e.jsx("path",{d:"M 10 50 A 40 40 0 0 1 60 15",fill:"none",stroke:"#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:[a.type.charAt(0).toUpperCase()+a.type.slice(1)," Chart"]})]})}};return e.jsxs("div",{className:"nice-chart-preview",children:[a.title&&e.jsx("div",{className:"nice-chart-preview__title",children:a.title}),a.subtitle&&e.jsx("div",{className:"nice-chart-preview__subtitle",children:a.subtitle}),e.jsx("div",{className:"nice-chart-preview__chart",children:t()}),((i=a.options)==null?void 0:i.legend)&&e.jsxs("div",{className:"nice-chart-preview__legend",children:[e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"#4CAF50"}}),"Series 1"]}),e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"#2196F3"}}),"Series 2"]}),e.jsxs("span",{className:"nice-chart-preview__legend-item",children:[e.jsx("span",{style:{background:"#FF9800"}}),"Series 3"]})]}),e.jsx("style",{children:`
1114
+ .nice-chart-preview {
1115
+ text-align: center;
1116
+ }
1117
+
1118
+ .nice-chart-preview__title {
1119
+ font-size: 16px;
1120
+ font-weight: 600;
1121
+ margin-bottom: 4px;
1122
+ }
1123
+
1124
+ .nice-chart-preview__subtitle {
1125
+ font-size: 13px;
1126
+ color: var(--nice-text-muted, #666);
1127
+ margin-bottom: 16px;
1128
+ }
1129
+
1130
+ .nice-chart-preview__chart {
1131
+ display: flex;
1132
+ justify-content: center;
1133
+ align-items: center;
1134
+ min-height: 120px;
1135
+ }
1136
+
1137
+ .nice-chart-preview__svg {
1138
+ max-width: 200px;
1139
+ max-height: 120px;
1140
+ }
1141
+
1142
+ .nice-chart-preview__placeholder {
1143
+ display: flex;
1144
+ flex-direction: column;
1145
+ align-items: center;
1146
+ gap: 8px;
1147
+ color: var(--nice-text-muted, #666);
1148
+ }
1149
+
1150
+ .nice-chart-preview__icon {
1151
+ font-size: 32px;
1152
+ }
1153
+
1154
+ .nice-chart-preview__legend {
1155
+ display: flex;
1156
+ justify-content: center;
1157
+ gap: 16px;
1158
+ margin-top: 16px;
1159
+ font-size: 12px;
1160
+ }
1161
+
1162
+ .nice-chart-preview__legend-item {
1163
+ display: flex;
1164
+ align-items: center;
1165
+ gap: 6px;
1166
+ }
1167
+
1168
+ .nice-chart-preview__legend-item span {
1169
+ display: inline-block;
1170
+ width: 12px;
1171
+ height: 12px;
1172
+ border-radius: 2px;
1173
+ }
1174
+ `})]})}function ht(a={}){const{config:t,language:i="typescript",context:r,maxSuggestions:n=3,debounceMs:s=300,onSuggestion:p,onError:o}=a,g=X(),[f,j]=c.useState(!1),[w,N]=c.useState([]),[S,$]=c.useState(-1),k=c.useRef(null),P=c.useRef(null),h=t||(g==null?void 0:g.config),d=c.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]||"",B=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(ce,{language:i,code_context:W,prefix:B,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=_i(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),p==null||p(T),L}catch(H){const Y=H instanceof Error?H.message:"Completion failed";return o==null||o(Y),{suggestions:[],error:Y,latencyMs:performance.now()-M}}finally{j(!1)}},[h,i,r,n,p,o]),y=c.useCallback((l,x)=>{P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{d(l,x)},s)},[d,s]),C=c.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 ${i} 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 wi(M)}catch{return null}finally{j(!1)}},[h,i]),m=c.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 ${i} code and suggest improvements. Return JSON array with: [{ "title": string, "description": string, "before": string, "after": string, "type": "extract-function"|"rename"|"simplify"|"optimize"|"security"|"style" }]`},{role:"user",content:l}],temperature:.4,maxTokens:2048});return ji(M)}catch{return[]}finally{j(!1)}},[h,i]),_=c.useCallback(async(l,x)=>{var M,z;if(!h)return null;j(!0);try{const D=G(h),J=x||ki(i);return((z=(M=(await D.chat({messages:[{role:"system",content:`You are a testing expert. Generate comprehensive unit tests for the following ${i} 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,i]),b=c.useCallback(async(l,x)=>{var M,z;if(!h)return null;j(!0);try{const D=G(h),J=x||Ni(i);return((z=(M=(await D.chat({messages:[{role:"system",content:`Generate ${J} documentation for the following ${i} 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,i]),u=c.useCallback((l=S)=>{const x=w[l];return N([]),$(-1),x},[w,S]),v=c.useCallback(()=>{N([]),$(-1)},[]),A=c.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=c.useCallback(()=>{var l;(l=k.current)==null||l.abort(),P.current&&clearTimeout(P.current),j(!1)},[]);return c.useEffect(()=>()=>{var l;(l=k.current)==null||l.abort(),P.current&&clearTimeout(P.current)},[]),{getCompletions:d,getCompletionsDebounced:y,suggestions:w,activeSuggestion:S,acceptSuggestion:u,dismissSuggestions:v,navigateSuggestions:A,explainCode:C,suggestRefactoring:m,generateTests:_,generateDocs:b,loading:f,abort:R,isConfigured:!!h}}function _i(a,t,i){var r,n;try{return(((n=(r=a.choices[0])==null?void 0:r.message)==null?void 0:n.content)||"").split(`
1178
+ `).filter(o=>o.trim()).slice(0,i).map((o,g)=>({id:`suggestion-${Date.now()}-${g}`,text:o.trim(),type:"inline",preview:o.trim().slice(0,50),confidence:.8-g*.1,insertPosition:t}))}catch{return[]}}function wi(a){var t,i;try{const r=((i=(t=a.choices[0])==null?void 0:t.message)==null?void 0:i.content)||"",n=r.match(/\{[\s\S]*\}/);return n?JSON.parse(n[0]):{summary:r}}catch{return null}}function ji(a){var t,i;try{const n=(((i=(t=a.choices[0])==null?void 0:t.message)==null?void 0:i.content)||"").match(/\[[\s\S]*\]/);if(n)return JSON.parse(n[0])}catch{}return[]}function ki(a){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"}[a]||"unit test"}function Ni(a){return{javascript:"jsdoc",typescript:"tsdoc",python:"docstring",java:"javadoc",kotlin:"javadoc"}[a]||"jsdoc"}function Ci({code:a="",language:t="typescript",config:i,onChange:r,onAcceptSuggestion:n,showToolbar:s=!0,enableInlineSuggestions:p=!0,placeholder:o="Start typing code...",className:g,style:f,renderEditor:j}){const[w,N]=c.useState(a),[S,$]=c.useState(null),[k,P]=c.useState(null),[h,d]=c.useState([]),[y,C]=c.useState(null),[m,_]=c.useState(null),b=c.useRef(null),{getCompletionsDebounced:u,suggestions:v,activeSuggestion:A,acceptSuggestion:R,dismissSuggestions:l,navigateSuggestions:x,explainCode:M,suggestRefactoring:z,generateTests:D,generateDocs:J,loading:H,isConfigured:Y}=ht({config:i,language:t}),I=O=>{if(N(O),r==null||r(O),p&&b.current){const F=Si(b.current);u(O,F)}},B=O=>{if(v.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 F=R(A);F&&(q(F),n==null||n(F))}}else O.key==="Escape"&&l()},q=O=>{if(!b.current)return;const F=b.current,ee=F.selectionStart,Me=w.slice(0,ee)+O.text+w.slice(ee);N(Me),r==null||r(Me);const Pe=ee+O.text.length;setTimeout(()=>{F.focus(),F.setSelectionRange(Pe,Pe)},0)},W=async()=>{const O=S||w;if(!O.trim())return;_("explain");const F=await M(O);P(F)},U=async()=>{const O=S||w;if(!O.trim())return;_("refactor");const F=await z(O);d(F)},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 F=w.replace(O.before,O.after);N(F),r==null||r(F),_(null)},L=()=>{y&&navigator.clipboard.writeText(y)},E=()=>{if(b.current){const O=b.current.selectionStart,F=b.current.selectionEnd;$(O!==F?w.slice(O,F):null)}};return Y?j?e.jsx("div",{className:`nice-code-editor-ai ${g||""}`,style:f,children:j({code:w,onChange:I,suggestions:v,onAccept:O=>{const F=R(O);F&&(n==null||n(F))}})}):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:t}),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:B,onSelect:E,placeholder:o,className:"nice-code-editor-ai__textarea",spellCheck:!1}),v.length>0&&e.jsxs("div",{className:"nice-code-editor-ai__suggestions",children:[v.map((O,F)=>e.jsxs("div",{className:`nice-code-editor-ai__suggestion ${F===A?"nice-code-editor-ai__suggestion--active":""}`,onClick:()=>{const ee=R(F);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"})]})]}),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:()=>_(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,F)=>e.jsx("li",{children:O},F))})]}),m==="refactor"&&h.length>0&&e.jsx("div",{className:"nice-code-editor-ai__refactorings",children:h.map((O,F)=>e.jsxs("div",{className:"nice-code-editor-ai__refactoring",children:[e.jsxs("div",{className:"nice-code-editor-ai__refactoring-header",children:[e.jsx("span",{className:"nice-code-editor-ai__refactoring-title",children: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"})]},F))}),(m==="tests"||m==="docs")&&y&&e.jsxs("div",{className:"nice-code-editor-ai__generated",children:[e.jsx("pre",{children:y}),e.jsx("button",{type:"button",onClick:L,children:"📋 Copy"})]})]})]}),e.jsx("style",{children:`
1179
+ .nice-code-editor-ai {
1180
+ font-family: var(--nice-font-family, system-ui, sans-serif);
1181
+ display: flex;
1182
+ flex-direction: column;
1183
+ gap: 8px;
1184
+ }
1185
+
1186
+ .nice-code-editor-ai--disabled {
1187
+ opacity: 0.7;
1188
+ }
1189
+
1190
+ .nice-code-editor-ai__toolbar {
1191
+ display: flex;
1192
+ align-items: center;
1193
+ gap: 12px;
1194
+ padding: 8px 12px;
1195
+ background: var(--nice-bg-secondary, #f5f5f5);
1196
+ border-radius: 8px;
1197
+ }
1198
+
1199
+ .nice-code-editor-ai__lang-badge {
1200
+ padding: 4px 10px;
1201
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.1));
1202
+ border-radius: 4px;
1203
+ font-size: 12px;
1204
+ font-weight: 500;
1205
+ text-transform: uppercase;
1206
+ color: var(--nice-primary, #0066cc);
1207
+ }
1208
+
1209
+ .nice-code-editor-ai__actions {
1210
+ display: flex;
1211
+ gap: 8px;
1212
+ flex: 1;
1213
+ }
1214
+
1215
+ .nice-code-editor-ai__actions button {
1216
+ padding: 6px 12px;
1217
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1218
+ border-radius: 6px;
1219
+ background: white;
1220
+ font-size: 13px;
1221
+ cursor: pointer;
1222
+ transition: all 0.2s;
1223
+ }
1224
+
1225
+ .nice-code-editor-ai__actions button:hover:not(:disabled) {
1226
+ border-color: var(--nice-primary, #0066cc);
1227
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.05));
1228
+ }
1229
+
1230
+ .nice-code-editor-ai__actions button:disabled {
1231
+ opacity: 0.5;
1232
+ cursor: not-allowed;
1233
+ }
1234
+
1235
+ .nice-code-editor-ai__loading {
1236
+ font-size: 12px;
1237
+ color: var(--nice-text-muted, #666);
1238
+ animation: nice-pulse 1s infinite;
1239
+ }
1240
+
1241
+ @keyframes nice-pulse {
1242
+ 0%, 100% { opacity: 0.5; }
1243
+ 50% { opacity: 1; }
1244
+ }
1245
+
1246
+ .nice-code-editor-ai__editor-wrapper {
1247
+ position: relative;
1248
+ }
1249
+
1250
+ .nice-code-editor-ai__textarea {
1251
+ width: 100%;
1252
+ min-height: 300px;
1253
+ padding: 16px;
1254
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1255
+ border-radius: 8px;
1256
+ font-family: 'Fira Code', 'JetBrains Mono', monospace;
1257
+ font-size: 14px;
1258
+ line-height: 1.5;
1259
+ resize: vertical;
1260
+ background: var(--nice-code-bg, #1e1e1e);
1261
+ color: var(--nice-code-color, #d4d4d4);
1262
+ }
1263
+
1264
+ .nice-code-editor-ai__textarea:focus {
1265
+ outline: none;
1266
+ border-color: var(--nice-primary, #0066cc);
1267
+ }
1268
+
1269
+ .nice-code-editor-ai__suggestions {
1270
+ position: absolute;
1271
+ top: 100%;
1272
+ left: 16px;
1273
+ right: 16px;
1274
+ background: white;
1275
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1276
+ border-radius: 8px;
1277
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
1278
+ z-index: 100;
1279
+ margin-top: 4px;
1280
+ overflow: hidden;
1281
+ }
1282
+
1283
+ .nice-code-editor-ai__suggestion {
1284
+ display: flex;
1285
+ align-items: center;
1286
+ justify-content: space-between;
1287
+ padding: 10px 12px;
1288
+ cursor: pointer;
1289
+ border-bottom: 1px solid var(--nice-border-light, #f0f0f0);
1290
+ }
1291
+
1292
+ .nice-code-editor-ai__suggestion:last-of-type {
1293
+ border-bottom: none;
1294
+ }
1295
+
1296
+ .nice-code-editor-ai__suggestion:hover {
1297
+ background: var(--nice-bg-hover, #f5f5f5);
1298
+ }
1299
+
1300
+ .nice-code-editor-ai__suggestion--active {
1301
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.1));
1302
+ }
1303
+
1304
+ .nice-code-editor-ai__suggestion-text {
1305
+ font-family: 'Fira Code', monospace;
1306
+ font-size: 13px;
1307
+ color: var(--nice-text-color, #333);
1308
+ }
1309
+
1310
+ .nice-code-editor-ai__suggestion-confidence {
1311
+ font-size: 11px;
1312
+ color: var(--nice-text-muted, #999);
1313
+ }
1314
+
1315
+ .nice-code-editor-ai__suggestions-hint {
1316
+ padding: 8px 12px;
1317
+ background: var(--nice-bg-subtle, #f8f9fa);
1318
+ font-size: 11px;
1319
+ color: var(--nice-text-muted, #666);
1320
+ text-align: center;
1321
+ }
1322
+
1323
+ .nice-code-editor-ai__panel {
1324
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1325
+ border-radius: 8px;
1326
+ overflow: hidden;
1327
+ }
1328
+
1329
+ .nice-code-editor-ai__panel-header {
1330
+ display: flex;
1331
+ justify-content: space-between;
1332
+ align-items: center;
1333
+ padding: 12px 16px;
1334
+ background: var(--nice-bg-secondary, #f5f5f5);
1335
+ font-weight: 500;
1336
+ }
1337
+
1338
+ .nice-code-editor-ai__panel-header button {
1339
+ background: none;
1340
+ border: none;
1341
+ font-size: 16px;
1342
+ cursor: pointer;
1343
+ opacity: 0.6;
1344
+ }
1345
+
1346
+ .nice-code-editor-ai__panel-header button:hover {
1347
+ opacity: 1;
1348
+ }
1349
+
1350
+ .nice-code-editor-ai__panel-content {
1351
+ padding: 16px;
1352
+ max-height: 400px;
1353
+ overflow-y: auto;
1354
+ }
1355
+
1356
+ .nice-code-editor-ai__explanation-summary {
1357
+ font-size: 15px;
1358
+ line-height: 1.6;
1359
+ margin-bottom: 12px;
1360
+ }
1361
+
1362
+ .nice-code-editor-ai__explanation-details {
1363
+ font-size: 14px;
1364
+ color: var(--nice-text-muted, #666);
1365
+ margin-bottom: 12px;
1366
+ }
1367
+
1368
+ .nice-code-editor-ai__complexity {
1369
+ display: inline-block;
1370
+ padding: 4px 10px;
1371
+ border-radius: 4px;
1372
+ font-size: 12px;
1373
+ font-weight: 500;
1374
+ }
1375
+
1376
+ .nice-code-editor-ai__complexity--low {
1377
+ background: var(--nice-success-light, #e8f5e9);
1378
+ color: var(--nice-success, #2e7d32);
1379
+ }
1380
+
1381
+ .nice-code-editor-ai__complexity--medium {
1382
+ background: var(--nice-warning-light, #fff3e0);
1383
+ color: var(--nice-warning, #f57c00);
1384
+ }
1385
+
1386
+ .nice-code-editor-ai__complexity--high {
1387
+ background: var(--nice-error-light, #ffebee);
1388
+ color: var(--nice-error, #c62828);
1389
+ }
1390
+
1391
+ .nice-code-editor-ai__explanation-suggestions {
1392
+ margin-top: 12px;
1393
+ padding-left: 20px;
1394
+ }
1395
+
1396
+ .nice-code-editor-ai__refactoring {
1397
+ padding: 16px;
1398
+ background: var(--nice-bg-subtle, #f8f9fa);
1399
+ border-radius: 8px;
1400
+ margin-bottom: 12px;
1401
+ }
1402
+
1403
+ .nice-code-editor-ai__refactoring-header {
1404
+ display: flex;
1405
+ justify-content: space-between;
1406
+ align-items: center;
1407
+ margin-bottom: 8px;
1408
+ }
1409
+
1410
+ .nice-code-editor-ai__refactoring-title {
1411
+ font-weight: 600;
1412
+ }
1413
+
1414
+ .nice-code-editor-ai__refactoring-type {
1415
+ padding: 2px 8px;
1416
+ border-radius: 4px;
1417
+ font-size: 11px;
1418
+ background: var(--nice-bg-secondary, #e0e0e0);
1419
+ }
1420
+
1421
+ .nice-code-editor-ai__refactoring-desc {
1422
+ font-size: 14px;
1423
+ color: var(--nice-text-muted, #666);
1424
+ margin-bottom: 12px;
1425
+ }
1426
+
1427
+ .nice-code-editor-ai__refactoring-diff {
1428
+ display: grid;
1429
+ grid-template-columns: 1fr 1fr;
1430
+ gap: 12px;
1431
+ margin-bottom: 12px;
1432
+ }
1433
+
1434
+ .nice-code-editor-ai__refactoring-before,
1435
+ .nice-code-editor-ai__refactoring-after {
1436
+ font-size: 12px;
1437
+ }
1438
+
1439
+ .nice-code-editor-ai__refactoring-before span,
1440
+ .nice-code-editor-ai__refactoring-after span {
1441
+ display: block;
1442
+ margin-bottom: 4px;
1443
+ color: var(--nice-text-muted, #666);
1444
+ }
1445
+
1446
+ .nice-code-editor-ai__refactoring-before pre,
1447
+ .nice-code-editor-ai__refactoring-after pre {
1448
+ padding: 8px;
1449
+ background: var(--nice-code-bg, #1e1e1e);
1450
+ color: var(--nice-code-color, #d4d4d4);
1451
+ border-radius: 4px;
1452
+ font-size: 12px;
1453
+ overflow-x: auto;
1454
+ }
1455
+
1456
+ .nice-code-editor-ai__refactoring-apply {
1457
+ padding: 6px 16px;
1458
+ background: var(--nice-primary, #0066cc);
1459
+ color: white;
1460
+ border: none;
1461
+ border-radius: 6px;
1462
+ font-weight: 500;
1463
+ cursor: pointer;
1464
+ }
1465
+
1466
+ .nice-code-editor-ai__generated pre {
1467
+ padding: 16px;
1468
+ background: var(--nice-code-bg, #1e1e1e);
1469
+ color: var(--nice-code-color, #d4d4d4);
1470
+ border-radius: 8px;
1471
+ font-family: 'Fira Code', monospace;
1472
+ font-size: 13px;
1473
+ overflow-x: auto;
1474
+ margin-bottom: 12px;
1475
+ }
1476
+
1477
+ .nice-code-editor-ai__generated button {
1478
+ padding: 8px 16px;
1479
+ background: var(--nice-bg-secondary, #f5f5f5);
1480
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1481
+ border-radius: 6px;
1482
+ cursor: pointer;
1483
+ }
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:o,className:"nice-code-editor-ai__textarea"})]})}function Si(a){const i=a.value.substring(0,a.selectionStart).split(`
1485
+ `);return{line:i.length-1,column:i[i.length-1].length}}function gt(a={}){const{config:t,context:i,existingRoles:r,existingVariables:n,onWorkflowGenerated:s,onError:p}=a,o=X(),[g,f]=c.useState(!1),[j,w]=c.useState(null),[N,S]=c.useState([]),$=c.useRef(null),k=t||(o==null?void 0:o.config),P=c.useCallback(async _=>{var u,v,A;if(!k){const R="AI not configured";return p==null||p(R),{error:R}}f(!0);const b=performance.now();(u=$.current)==null||u.abort(),$.current=new AbortController;try{const R=G(k),l=[i,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=(v=M.choices[0])==null?void 0:v.message)==null?void 0:A.content,latencyMs:performance.now()-b,error:z?void 0:"Failed to generate workflow",suggestions:Ai(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),p==null||p(l),x}finally{f(!1)}},[k,i,r,n,s,p]),h=c.useCallback(async _=>{if(!k)return{error:"AI not configured"};f(!0);const b=performance.now();try{const v=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(v)||void 0,latencyMs:performance.now()-b}}catch(u){return{error:u instanceof Error?u.message:"Optimization failed"}}finally{f(!1)}},[k]),d=c.useCallback(async(_,b)=>{var u,v;if(!k)return[];f(!0);try{const A=G(k),R=_.nodes.find(z=>z.id===b),M=(((v=(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:v.content)||"").match(/\[[\s\S]*\]/);if(M)return JSON.parse(M[0])}catch{}finally{f(!1)}return[]},[k]),y=c.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=c.useCallback(()=>{w(null)},[]),m=c.useCallback(()=>{var _;(_=$.current)==null||_.abort(),f(!1)},[]);return c.useEffect(()=>()=>{var _;(_=$.current)==null||_.abort()},[]),{generateWorkflow:P,optimizeWorkflow:h,suggestNextStep:d,validateWorkflow:y,loading:g,lastResult:j,history:N,clearResults:C,abort:m,isConfigured:!!k}}function Oe(a){var t,i,r;try{const n=((i=(t=a.choices[0])==null?void 0:t.message)==null?void 0:i.content)||"",p=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,o=JSON.parse(p);if(o.nodes&&Array.isArray(o.nodes)){const g=o.nodes.map((f,j)=>({...f,id:f.id||`node_${j}`,position:f.position||Ti(j,o.nodes.length)}));return{id:o.id||`workflow_${Date.now()}`,name:o.name||"Generated Workflow",description:o.description,version:o.version||"1.0",nodes:g,edges:o.edges||[],lanes:o.lanes,variables:o.variables,metadata:o.metadata}}}catch{}return null}function Ti(a,t){const s=Math.floor(a/5);return{x:100+a%5*200,y:100+s*100}}function Ai(a){if(!a)return[];const t=[];return a.nodes.some(s=>s.type==="event-error")||t.push("Add error boundary events for critical tasks"),!a.nodes.some(s=>s.type==="gateway-parallel")&&a.nodes.length>5&&t.push("Consider parallel gateways for independent tasks"),(!a.lanes||a.lanes.length===0)&&t.push("Add swimlanes to clarify responsibilities"),a.nodes.some(s=>s.type==="event-timer")||t.push("Add timer events for SLA monitoring"),t.slice(0,3)}const Ri=["Employee onboarding process with HR approval","Purchase order approval with budget check","Customer support ticket escalation workflow","Document review and approval process","Leave request with manager and HR approval"];function Mi({config:a,context:t,roles:i,onGenerate:r,placeholder:n='Describe the workflow process... (e.g., "Leave request with manager approval")',showExamples:s=!0,showPreview:p=!0,className:o,style:g,renderWorkflow:f}){const[j,w]=c.useState(""),[N,S]=c.useState([]),$=c.useRef(null),{generateWorkflow:k,validateWorkflow:P,loading:h,lastResult:d,isConfigured:y}=gt({config:a,context:t,existingRoles:i,onWorkflowGenerated:r}),C=async()=>{!j.trim()||h||await k(j)},m=u=>{var v;w(u),(v=$.current)==null||v.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=$i(d.workflow),v=new Blob([u],{type:"application/xml"}),A=URL.createObjectURL(v),R=document.createElement("a");R.href=A,R.download=`${d.workflow.name.replace(/\s+/g,"_")}.bpmn`,R.click(),URL.revokeObjectURL(A)};return y?e.jsxs("div",{className:`nice-workflow-ai ${o||""}`,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:"}),Ri.slice(0,3).map((u,v)=>e.jsx("button",{type:"button",className:"nice-workflow-ai__example",onClick:()=>m(u),children:u},v))]}),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,v)=>e.jsx("li",{className:`nice-workflow-ai__issue nice-workflow-ai__issue--${u.startsWith("[error]")?"error":u.startsWith("[warning]")?"warning":"info"}`,children:u},v))})]}),p&&e.jsx("div",{className:"nice-workflow-ai__preview",children:f?f(d.workflow):e.jsx(Pi,{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,v)=>e.jsx("li",{children:u},v))})]}),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
+ .nice-workflow-ai {
1490
+ font-family: var(--nice-font-family, system-ui, sans-serif);
1491
+ }
1492
+
1493
+ .nice-workflow-ai--disabled {
1494
+ padding: 20px;
1495
+ background: var(--nice-disabled-bg, #f5f5f5);
1496
+ border-radius: 8px;
1497
+ color: var(--nice-text-muted, #666);
1498
+ }
1499
+
1500
+ .nice-workflow-ai__input-section {
1501
+ display: flex;
1502
+ gap: 12px;
1503
+ margin-bottom: 12px;
1504
+ }
1505
+
1506
+ .nice-workflow-ai__input {
1507
+ flex: 1;
1508
+ padding: 12px;
1509
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1510
+ border-radius: 8px;
1511
+ font-size: 14px;
1512
+ resize: vertical;
1513
+ min-height: 80px;
1514
+ }
1515
+
1516
+ .nice-workflow-ai__input:focus {
1517
+ outline: none;
1518
+ border-color: var(--nice-primary, #0066cc);
1519
+ box-shadow: 0 0 0 3px var(--nice-primary-light, rgba(0, 102, 204, 0.15));
1520
+ }
1521
+
1522
+ .nice-workflow-ai__submit {
1523
+ display: flex;
1524
+ align-items: center;
1525
+ justify-content: center;
1526
+ padding: 12px 24px;
1527
+ background: var(--nice-primary, #0066cc);
1528
+ color: white;
1529
+ border: none;
1530
+ border-radius: 8px;
1531
+ font-weight: 500;
1532
+ cursor: pointer;
1533
+ white-space: nowrap;
1534
+ transition: background 0.2s;
1535
+ }
1536
+
1537
+ .nice-workflow-ai__submit:hover:not(:disabled) {
1538
+ background: var(--nice-primary-dark, #0052a3);
1539
+ }
1540
+
1541
+ .nice-workflow-ai__submit:disabled {
1542
+ opacity: 0.5;
1543
+ cursor: not-allowed;
1544
+ }
1545
+
1546
+ .nice-workflow-ai__spinner {
1547
+ width: 20px;
1548
+ height: 20px;
1549
+ border: 2px solid rgba(255, 255, 255, 0.3);
1550
+ border-top-color: white;
1551
+ border-radius: 50%;
1552
+ animation: nice-spin 0.8s linear infinite;
1553
+ }
1554
+
1555
+ @keyframes nice-spin {
1556
+ to { transform: rotate(360deg); }
1557
+ }
1558
+
1559
+ .nice-workflow-ai__examples {
1560
+ display: flex;
1561
+ flex-wrap: wrap;
1562
+ gap: 8px;
1563
+ align-items: center;
1564
+ margin-bottom: 16px;
1565
+ }
1566
+
1567
+ .nice-workflow-ai__examples-label {
1568
+ font-size: 13px;
1569
+ color: var(--nice-text-muted, #666);
1570
+ }
1571
+
1572
+ .nice-workflow-ai__example {
1573
+ padding: 6px 12px;
1574
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1575
+ border-radius: 16px;
1576
+ background: white;
1577
+ font-size: 12px;
1578
+ cursor: pointer;
1579
+ transition: all 0.2s;
1580
+ }
1581
+
1582
+ .nice-workflow-ai__example:hover {
1583
+ border-color: var(--nice-primary, #0066cc);
1584
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.05));
1585
+ }
1586
+
1587
+ .nice-workflow-ai__result {
1588
+ padding: 20px;
1589
+ background: var(--nice-bg-subtle, #f8f9fa);
1590
+ border-radius: 8px;
1591
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1592
+ }
1593
+
1594
+ .nice-workflow-ai__result-header {
1595
+ display: flex;
1596
+ justify-content: space-between;
1597
+ align-items: flex-start;
1598
+ margin-bottom: 16px;
1599
+ }
1600
+
1601
+ .nice-workflow-ai__workflow-info {
1602
+ display: flex;
1603
+ flex-direction: column;
1604
+ gap: 4px;
1605
+ }
1606
+
1607
+ .nice-workflow-ai__workflow-name {
1608
+ font-size: 18px;
1609
+ font-weight: 600;
1610
+ }
1611
+
1612
+ .nice-workflow-ai__workflow-desc {
1613
+ font-size: 14px;
1614
+ color: var(--nice-text-muted, #666);
1615
+ }
1616
+
1617
+ .nice-workflow-ai__result-meta {
1618
+ display: flex;
1619
+ gap: 12px;
1620
+ font-size: 12px;
1621
+ color: var(--nice-text-muted, #666);
1622
+ }
1623
+
1624
+ .nice-workflow-ai__stat {
1625
+ padding: 4px 8px;
1626
+ background: var(--nice-bg-secondary, #e0e0e0);
1627
+ border-radius: 4px;
1628
+ }
1629
+
1630
+ .nice-workflow-ai__latency {
1631
+ color: var(--nice-text-muted, #999);
1632
+ }
1633
+
1634
+ .nice-workflow-ai__actions {
1635
+ display: flex;
1636
+ gap: 8px;
1637
+ margin-bottom: 16px;
1638
+ }
1639
+
1640
+ .nice-workflow-ai__actions button {
1641
+ padding: 8px 16px;
1642
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1643
+ border-radius: 6px;
1644
+ background: white;
1645
+ font-size: 13px;
1646
+ cursor: pointer;
1647
+ transition: all 0.2s;
1648
+ }
1649
+
1650
+ .nice-workflow-ai__actions button:hover {
1651
+ border-color: var(--nice-primary, #0066cc);
1652
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.05));
1653
+ }
1654
+
1655
+ .nice-workflow-ai__actions button:first-child {
1656
+ background: var(--nice-success, #2e7d32);
1657
+ color: white;
1658
+ border: none;
1659
+ }
1660
+
1661
+ .nice-workflow-ai__validation {
1662
+ margin-bottom: 16px;
1663
+ padding: 12px;
1664
+ background: var(--nice-warning-light, #fff3e0);
1665
+ border-radius: 6px;
1666
+ }
1667
+
1668
+ .nice-workflow-ai__validation-title {
1669
+ font-weight: 500;
1670
+ margin-bottom: 8px;
1671
+ }
1672
+
1673
+ .nice-workflow-ai__validation ul {
1674
+ margin: 0;
1675
+ padding-left: 20px;
1676
+ }
1677
+
1678
+ .nice-workflow-ai__issue {
1679
+ margin-bottom: 4px;
1680
+ font-size: 13px;
1681
+ }
1682
+
1683
+ .nice-workflow-ai__issue--error {
1684
+ color: var(--nice-error, #c62828);
1685
+ }
1686
+
1687
+ .nice-workflow-ai__issue--warning {
1688
+ color: var(--nice-warning, #f57c00);
1689
+ }
1690
+
1691
+ .nice-workflow-ai__issue--info {
1692
+ color: var(--nice-info, #0288d1);
1693
+ }
1694
+
1695
+ .nice-workflow-ai__preview {
1696
+ padding: 20px;
1697
+ background: white;
1698
+ border-radius: 8px;
1699
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1700
+ margin-bottom: 16px;
1701
+ overflow-x: auto;
1702
+ }
1703
+
1704
+ .nice-workflow-ai__suggestions {
1705
+ margin-bottom: 16px;
1706
+ padding: 12px;
1707
+ background: var(--nice-info-light, #e3f2fd);
1708
+ border-radius: 6px;
1709
+ }
1710
+
1711
+ .nice-workflow-ai__suggestions-title {
1712
+ font-weight: 500;
1713
+ margin-bottom: 8px;
1714
+ display: block;
1715
+ }
1716
+
1717
+ .nice-workflow-ai__suggestions ul {
1718
+ margin: 0;
1719
+ padding-left: 20px;
1720
+ font-size: 13px;
1721
+ }
1722
+
1723
+ .nice-workflow-ai__json {
1724
+ margin-top: 12px;
1725
+ }
1726
+
1727
+ .nice-workflow-ai__json summary {
1728
+ cursor: pointer;
1729
+ font-size: 13px;
1730
+ color: var(--nice-text-muted, #666);
1731
+ }
1732
+
1733
+ .nice-workflow-ai__json pre {
1734
+ margin: 8px 0 0;
1735
+ padding: 12px;
1736
+ background: var(--nice-code-bg, #1e1e1e);
1737
+ color: var(--nice-code-color, #d4d4d4);
1738
+ border-radius: 6px;
1739
+ font-size: 12px;
1740
+ overflow-x: auto;
1741
+ }
1742
+
1743
+ .nice-workflow-ai__error {
1744
+ padding: 12px;
1745
+ background: var(--nice-error-light, #ffebee);
1746
+ color: var(--nice-error, #c62828);
1747
+ border-radius: 6px;
1748
+ }
1749
+ `})]}):e.jsx("div",{className:`nice-workflow-ai nice-workflow-ai--disabled ${o||""}`,style:g,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function Pi({workflow:a}){const t=r=>({start:"▶️",end:"⏹️",task:"📋",userTask:"👤",serviceTask:"⚙️",scriptTask:"📜","gateway-exclusive":"◇","gateway-parallel":"✚","gateway-inclusive":"○","event-timer":"⏰","event-message":"✉️","event-error":"⚠️"})[r]||"📋",i=r=>r==="start"?"#4CAF50":r==="end"?"#f44336":r.startsWith("gateway")?"#FF9800":r.startsWith("event")?"#9C27B0":"#2196F3";return e.jsxs("div",{className:"workflow-preview",children:[e.jsxs("div",{className:"workflow-preview__diagram",children:[a.nodes.map(r=>{var n,s;return e.jsxs("div",{className:`workflow-preview__node workflow-preview__node--${r.type.split("-")[0]}`,style:{left:(n=r.position)==null?void 0:n.x,top:(s=r.position)==null?void 0:s.y,borderColor:i(r.type)},children:[e.jsx("span",{className:"workflow-preview__node-icon",children:t(r.type)}),e.jsx("span",{className:"workflow-preview__node-label",children:r.label})]},r.id)}),e.jsxs("svg",{className:"workflow-preview__connections",children:[a.edges.map(r=>{const n=a.nodes.find(j=>j.id===r.source),s=a.nodes.find(j=>j.id===r.target);if(!(n!=null&&n.position)||!(s!=null&&s.position))return null;const p=n.position.x+60,o=n.position.y+20,g=s.position.x,f=s.position.y+20;return e.jsxs("g",{children:[e.jsx("line",{x1:p,y1:o,x2:g,y2:f,stroke:"#666",strokeWidth:"2",markerEnd:"url(#arrowhead)"}),r.label&&e.jsx("text",{x:(p+g)/2,y:(o+f)/2-5,fontSize:"10",fill:"#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:"#666"})})})]})]}),a.lanes&&a.lanes.length>0&&e.jsxs("div",{className:"workflow-preview__lanes",children:[e.jsx("span",{className:"workflow-preview__lanes-title",children:"Swimlanes:"}),a.lanes.map(r=>e.jsx("span",{className:"workflow-preview__lane",children:r.name},r.id))]}),e.jsx("style",{children:`
1750
+ .workflow-preview {
1751
+ min-height: 200px;
1752
+ }
1753
+
1754
+ .workflow-preview__diagram {
1755
+ position: relative;
1756
+ min-height: 300px;
1757
+ padding: 20px;
1758
+ }
1759
+
1760
+ .workflow-preview__node {
1761
+ position: absolute;
1762
+ display: flex;
1763
+ align-items: center;
1764
+ gap: 8px;
1765
+ padding: 10px 16px;
1766
+ background: white;
1767
+ border: 2px solid;
1768
+ border-radius: 8px;
1769
+ font-size: 13px;
1770
+ white-space: nowrap;
1771
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
1772
+ }
1773
+
1774
+ .workflow-preview__node--start,
1775
+ .workflow-preview__node--end {
1776
+ border-radius: 50%;
1777
+ width: 40px;
1778
+ height: 40px;
1779
+ padding: 0;
1780
+ justify-content: center;
1781
+ }
1782
+
1783
+ .workflow-preview__node--start .workflow-preview__node-label,
1784
+ .workflow-preview__node--end .workflow-preview__node-label {
1785
+ display: none;
1786
+ }
1787
+
1788
+ .workflow-preview__node--gateway {
1789
+ transform: rotate(45deg);
1790
+ width: 40px;
1791
+ height: 40px;
1792
+ padding: 0;
1793
+ justify-content: center;
1794
+ }
1795
+
1796
+ .workflow-preview__node--gateway .workflow-preview__node-icon,
1797
+ .workflow-preview__node--gateway .workflow-preview__node-label {
1798
+ transform: rotate(-45deg);
1799
+ }
1800
+
1801
+ .workflow-preview__node-icon {
1802
+ font-size: 16px;
1803
+ }
1804
+
1805
+ .workflow-preview__node-label {
1806
+ font-weight: 500;
1807
+ }
1808
+
1809
+ .workflow-preview__connections {
1810
+ position: absolute;
1811
+ top: 0;
1812
+ left: 0;
1813
+ width: 100%;
1814
+ height: 100%;
1815
+ pointer-events: none;
1816
+ }
1817
+
1818
+ .workflow-preview__lanes {
1819
+ display: flex;
1820
+ gap: 8px;
1821
+ align-items: center;
1822
+ margin-top: 16px;
1823
+ padding-top: 16px;
1824
+ border-top: 1px solid var(--nice-border-color, #e0e0e0);
1825
+ }
1826
+
1827
+ .workflow-preview__lanes-title {
1828
+ font-size: 12px;
1829
+ color: var(--nice-text-muted, #666);
1830
+ }
1831
+
1832
+ .workflow-preview__lane {
1833
+ padding: 4px 12px;
1834
+ background: var(--nice-bg-subtle, #f0f0f0);
1835
+ border-radius: 4px;
1836
+ font-size: 12px;
1837
+ }
1838
+ `})]})}function $i(a){const t={start:"bpmn:startEvent",end:"bpmn:endEvent",task:"bpmn:task",userTask:"bpmn:userTask",serviceTask:"bpmn:serviceTask",scriptTask:"bpmn:scriptTask","gateway-exclusive":"bpmn:exclusiveGateway","gateway-parallel":"bpmn:parallelGateway","gateway-inclusive":"bpmn:inclusiveGateway"},i=a.nodes.map(n=>` <${t[n.type]||"bpmn:task"} id="${n.id}" name="${ge(n.label)}" />`).join(`
1839
+ `),r=a.edges.map(n=>` <bpmn:sequenceFlow id="${n.id}" sourceRef="${n.source}" targetRef="${n.target}"${n.label?` name="${ge(n.label)}"`:""} />`).join(`
1840
+ `);return`<?xml version="1.0" encoding="UTF-8"?>
1841
+ <bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL"
1842
+ xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI"
1843
+ id="${a.id}"
1844
+ targetNamespace="http://nice2dev.com/bpmn">
1845
+ <bpmn:process id="Process_${a.id}" name="${ge(a.name)}" isExecutable="true">
1846
+ ${i}
1847
+ ${r}
1848
+ </bpmn:process>
1849
+ </bpmn:definitions>`}function ge(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function ft(a={}){const{config:t,dataSources:i,context:r,onReportGenerated:n,onError:s}=a,p=X(),[o,g]=c.useState(!1),[f,j]=c.useState(null),[w,N]=c.useState([]),S=c.useRef(null),$=t||(p==null?void 0:p.config),k=c.useCallback(async m=>{var b,u,v;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=i?i.map(D=>`- ${D.name} (${D.id}): ${D.fields.join(", ")}`).join(`
1850
+ `):void 0,l=Z(de,{description:m,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=Ii(x),z={layout:M||void 0,rawResponse:(v=(u=x.choices[0])==null?void 0:u.message)==null?void 0:v.content,latencyMs:performance.now()-_,error:M?void 0:"Failed to generate report layout",suggestions:zi(M)};return M&&(n==null||n(M)),j(z),N(D=>[...D.slice(-9),{request:m,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)}},[$,i,r,n,s]),P=c.useCallback(async m=>{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: ${m.name}
1851
+ Existing sections: ${m.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=c.useCallback(async m=>{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(m,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=c.useCallback(async(m,_)=>{var b,u,v;if(!$)return"bar";try{const A=G($),R=m.slice(0,5),x=(v=(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:v.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"}},[$]),y=c.useCallback(()=>{j(null)},[]),C=c.useCallback(()=>{var m;(m=S.current)==null||m.abort(),g(!1)},[]);return c.useEffect(()=>()=>{var m;(m=S.current)==null||m.abort()},[]),{generateReport:k,suggestSections:P,generateSummary:h,suggestChartType:d,loading:o,lastResult:f,history:w,clearResults:y,abort:C,isConfigured:!!$}}function Ii(a){var t,i,r;try{const n=((i=(t=a.choices[0])==null?void 0:t.message)==null?void 0:i.content)||"",p=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,o=JSON.parse(p);if(o.sections&&Array.isArray(o.sections)){const g=o.sections.map((f,j)=>({...f,id:f.id||`section_${j}`,order:f.order??j,config:f.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:g,dataSources:o.dataSources,parameters:o.parameters,styles:o.styles}}}catch{}return null}function zi(a){if(!a)return[];const t=[],i=new Set(a.sections.map(r=>r.type));return i.has("summary")||t.push("Add an executive summary for quick insights"),i.has("kpi")||t.push("Include KPI cards for key metrics"),i.has("chart")||t.push("Add visualizations to make data more accessible"),i.has("footer")||t.push("Add a footer with page numbers and date"),a.sections.length>5&&!i.has("toc")&&t.push("Consider adding a table of contents"),t.slice(0,3)}const Li=[{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 Oi({config:a,dataSources:t,context:i,onGenerate:r,placeholder:n='Describe the report you need... (e.g., "Monthly sales report with KPIs and charts")',showTemplates:s=!0,showPreview:p=!0,className:o,style:g,renderReport:f}){const[j,w]=c.useState(""),N=c.useRef(null),{generateReport:S,loading:$,lastResult:k,isConfigured:P}=ft({config:a,dataSources:t,context:i,onReportGenerated:r}),h=async()=>{!j.trim()||$||await S(j)},d=C=>{var m;w(C.prompt),(m=N.current)==null||m.focus()},y=()=>{if(!(k!=null&&k.layout))return;const C=JSON.stringify(k.layout,null,2),m=new Blob([C],{type:"application/json"}),_=URL.createObjectURL(m),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 ${o||""}`,style:g,children:[s&&e.jsx("div",{className:"nice-report-ai__templates",children:Li.map((C,m)=>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})]},m))}),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"})]}),t&&t.length>0&&e.jsxs("div",{className:"nice-report-ai__datasources",children:[e.jsx("span",{className:"nice-report-ai__datasources-label",children:"Available data:"}),t.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:y,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,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:xt(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))})]}),p&&e.jsx("div",{className:"nice-report-ai__preview",children:f?f(k.layout):e.jsx(Ei,{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,m)=>e.jsx("li",{children:C},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
+ .nice-report-ai {
1854
+ font-family: var(--nice-font-family, system-ui, sans-serif);
1855
+ }
1856
+
1857
+ .nice-report-ai--disabled {
1858
+ padding: 20px;
1859
+ background: var(--nice-disabled-bg, #f5f5f5);
1860
+ border-radius: 8px;
1861
+ color: var(--nice-text-muted, #666);
1862
+ }
1863
+
1864
+ .nice-report-ai__templates {
1865
+ display: flex;
1866
+ flex-wrap: wrap;
1867
+ gap: 8px;
1868
+ margin-bottom: 16px;
1869
+ }
1870
+
1871
+ .nice-report-ai__template {
1872
+ display: flex;
1873
+ flex-direction: column;
1874
+ align-items: center;
1875
+ gap: 4px;
1876
+ padding: 12px 16px;
1877
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1878
+ border-radius: 8px;
1879
+ background: white;
1880
+ cursor: pointer;
1881
+ transition: all 0.2s;
1882
+ min-width: 100px;
1883
+ }
1884
+
1885
+ .nice-report-ai__template:hover {
1886
+ border-color: var(--nice-primary, #0066cc);
1887
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.05));
1888
+ }
1889
+
1890
+ .nice-report-ai__template-icon {
1891
+ font-size: 24px;
1892
+ }
1893
+
1894
+ .nice-report-ai__template-name {
1895
+ font-size: 12px;
1896
+ color: var(--nice-text-muted, #666);
1897
+ text-align: center;
1898
+ }
1899
+
1900
+ .nice-report-ai__input-section {
1901
+ display: flex;
1902
+ gap: 12px;
1903
+ margin-bottom: 12px;
1904
+ }
1905
+
1906
+ .nice-report-ai__input {
1907
+ flex: 1;
1908
+ padding: 12px;
1909
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1910
+ border-radius: 8px;
1911
+ font-size: 14px;
1912
+ resize: vertical;
1913
+ min-height: 80px;
1914
+ }
1915
+
1916
+ .nice-report-ai__input:focus {
1917
+ outline: none;
1918
+ border-color: var(--nice-primary, #0066cc);
1919
+ box-shadow: 0 0 0 3px var(--nice-primary-light, rgba(0, 102, 204, 0.15));
1920
+ }
1921
+
1922
+ .nice-report-ai__submit {
1923
+ display: flex;
1924
+ align-items: center;
1925
+ justify-content: center;
1926
+ padding: 12px 24px;
1927
+ background: var(--nice-primary, #0066cc);
1928
+ color: white;
1929
+ border: none;
1930
+ border-radius: 8px;
1931
+ font-weight: 500;
1932
+ cursor: pointer;
1933
+ white-space: nowrap;
1934
+ transition: background 0.2s;
1935
+ }
1936
+
1937
+ .nice-report-ai__submit:hover:not(:disabled) {
1938
+ background: var(--nice-primary-dark, #0052a3);
1939
+ }
1940
+
1941
+ .nice-report-ai__submit:disabled {
1942
+ opacity: 0.5;
1943
+ cursor: not-allowed;
1944
+ }
1945
+
1946
+ .nice-report-ai__spinner {
1947
+ width: 20px;
1948
+ height: 20px;
1949
+ border: 2px solid rgba(255, 255, 255, 0.3);
1950
+ border-top-color: white;
1951
+ border-radius: 50%;
1952
+ animation: nice-spin 0.8s linear infinite;
1953
+ }
1954
+
1955
+ @keyframes nice-spin {
1956
+ to { transform: rotate(360deg); }
1957
+ }
1958
+
1959
+ .nice-report-ai__datasources {
1960
+ display: flex;
1961
+ flex-wrap: wrap;
1962
+ gap: 8px;
1963
+ align-items: center;
1964
+ margin-bottom: 16px;
1965
+ }
1966
+
1967
+ .nice-report-ai__datasources-label {
1968
+ font-size: 13px;
1969
+ color: var(--nice-text-muted, #666);
1970
+ }
1971
+
1972
+ .nice-report-ai__datasource {
1973
+ padding: 4px 12px;
1974
+ background: var(--nice-bg-subtle, #f0f0f0);
1975
+ border-radius: 4px;
1976
+ font-size: 12px;
1977
+ }
1978
+
1979
+ .nice-report-ai__result {
1980
+ padding: 20px;
1981
+ background: var(--nice-bg-subtle, #f8f9fa);
1982
+ border-radius: 8px;
1983
+ border: 1px solid var(--nice-border-color, #e0e0e0);
1984
+ }
1985
+
1986
+ .nice-report-ai__result-header {
1987
+ display: flex;
1988
+ justify-content: space-between;
1989
+ align-items: flex-start;
1990
+ margin-bottom: 16px;
1991
+ }
1992
+
1993
+ .nice-report-ai__report-info {
1994
+ display: flex;
1995
+ flex-direction: column;
1996
+ gap: 4px;
1997
+ }
1998
+
1999
+ .nice-report-ai__report-name {
2000
+ font-size: 18px;
2001
+ font-weight: 600;
2002
+ }
2003
+
2004
+ .nice-report-ai__report-desc {
2005
+ font-size: 14px;
2006
+ color: var(--nice-text-muted, #666);
2007
+ }
2008
+
2009
+ .nice-report-ai__result-meta {
2010
+ display: flex;
2011
+ gap: 12px;
2012
+ font-size: 12px;
2013
+ color: var(--nice-text-muted, #666);
2014
+ }
2015
+
2016
+ .nice-report-ai__stat {
2017
+ padding: 4px 8px;
2018
+ background: var(--nice-bg-secondary, #e0e0e0);
2019
+ border-radius: 4px;
2020
+ }
2021
+
2022
+ .nice-report-ai__latency {
2023
+ color: var(--nice-text-muted, #999);
2024
+ }
2025
+
2026
+ .nice-report-ai__actions {
2027
+ display: flex;
2028
+ gap: 8px;
2029
+ margin-bottom: 16px;
2030
+ }
2031
+
2032
+ .nice-report-ai__actions button {
2033
+ padding: 8px 16px;
2034
+ border: 1px solid var(--nice-border-color, #e0e0e0);
2035
+ border-radius: 6px;
2036
+ background: white;
2037
+ font-size: 13px;
2038
+ cursor: pointer;
2039
+ transition: all 0.2s;
2040
+ }
2041
+
2042
+ .nice-report-ai__actions button:hover {
2043
+ border-color: var(--nice-primary, #0066cc);
2044
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.05));
2045
+ }
2046
+
2047
+ .nice-report-ai__actions button:first-child {
2048
+ background: var(--nice-success, #2e7d32);
2049
+ color: white;
2050
+ border: none;
2051
+ }
2052
+
2053
+ .nice-report-ai__sections {
2054
+ margin-bottom: 16px;
2055
+ }
2056
+
2057
+ .nice-report-ai__sections-title {
2058
+ font-weight: 500;
2059
+ margin-bottom: 8px;
2060
+ }
2061
+
2062
+ .nice-report-ai__sections-list {
2063
+ display: flex;
2064
+ flex-direction: column;
2065
+ gap: 4px;
2066
+ }
2067
+
2068
+ .nice-report-ai__section {
2069
+ display: flex;
2070
+ align-items: center;
2071
+ gap: 8px;
2072
+ padding: 8px 12px;
2073
+ background: white;
2074
+ border-radius: 6px;
2075
+ border: 1px solid var(--nice-border-light, #f0f0f0);
2076
+ }
2077
+
2078
+ .nice-report-ai__section-number {
2079
+ width: 24px;
2080
+ height: 24px;
2081
+ display: flex;
2082
+ align-items: center;
2083
+ justify-content: center;
2084
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.1));
2085
+ border-radius: 50%;
2086
+ font-size: 12px;
2087
+ font-weight: 600;
2088
+ color: var(--nice-primary, #0066cc);
2089
+ }
2090
+
2091
+ .nice-report-ai__section-icon {
2092
+ font-size: 16px;
2093
+ }
2094
+
2095
+ .nice-report-ai__section-type {
2096
+ font-size: 13px;
2097
+ font-weight: 500;
2098
+ text-transform: capitalize;
2099
+ }
2100
+
2101
+ .nice-report-ai__section-title {
2102
+ font-size: 13px;
2103
+ color: var(--nice-text-muted, #666);
2104
+ }
2105
+
2106
+ .nice-report-ai__preview {
2107
+ padding: 20px;
2108
+ background: white;
2109
+ border-radius: 8px;
2110
+ border: 1px solid var(--nice-border-color, #e0e0e0);
2111
+ margin-bottom: 16px;
2112
+ overflow-x: auto;
2113
+ }
2114
+
2115
+ .nice-report-ai__suggestions {
2116
+ margin-bottom: 16px;
2117
+ padding: 12px;
2118
+ background: var(--nice-info-light, #e3f2fd);
2119
+ border-radius: 6px;
2120
+ }
2121
+
2122
+ .nice-report-ai__suggestions-title {
2123
+ font-weight: 500;
2124
+ margin-bottom: 8px;
2125
+ display: block;
2126
+ }
2127
+
2128
+ .nice-report-ai__suggestions ul {
2129
+ margin: 0;
2130
+ padding-left: 20px;
2131
+ font-size: 13px;
2132
+ }
2133
+
2134
+ .nice-report-ai__json {
2135
+ margin-top: 12px;
2136
+ }
2137
+
2138
+ .nice-report-ai__json summary {
2139
+ cursor: pointer;
2140
+ font-size: 13px;
2141
+ color: var(--nice-text-muted, #666);
2142
+ }
2143
+
2144
+ .nice-report-ai__json pre {
2145
+ margin: 8px 0 0;
2146
+ padding: 12px;
2147
+ background: var(--nice-code-bg, #1e1e1e);
2148
+ color: var(--nice-code-color, #d4d4d4);
2149
+ border-radius: 6px;
2150
+ font-size: 12px;
2151
+ overflow-x: auto;
2152
+ }
2153
+
2154
+ .nice-report-ai__error {
2155
+ padding: 12px;
2156
+ background: var(--nice-error-light, #ffebee);
2157
+ color: var(--nice-error, #c62828);
2158
+ border-radius: 6px;
2159
+ }
2160
+ `})]}):e.jsx("div",{className:`nice-report-ai nice-report-ai--disabled ${o||""}`,style:g,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function xt(a){return{header:"📑",summary:"📝",kpi:"📈",table:"📋",chart:"📊",text:"📄",image:"🖼️",divider:"➖",spacer:"⬜",pageBreak:"📃",footer:"📜",toc:"📚",customBlock:"🧩"}[a]||"📄"}function Ei({layout:a}){return e.jsxs("div",{className:"report-preview",style:{aspectRatio:a.orientation==="landscape"?"1.414":"0.707",maxWidth:a.orientation==="landscape"?"100%":"60%"},children:[e.jsx("div",{className:"report-preview__paper",children:a.sections.map(t=>e.jsxs("div",{className:`report-preview__section report-preview__section--${t.type}`,children:[e.jsx("span",{className:"report-preview__section-icon",children:xt(t.type)}),e.jsx("span",{className:"report-preview__section-label",children:t.title||t.type})]},t.id))}),e.jsx("style",{children:`
2161
+ .report-preview {
2162
+ display: flex;
2163
+ justify-content: center;
2164
+ padding: 20px;
2165
+ background: var(--nice-bg-subtle, #f0f0f0);
2166
+ border-radius: 8px;
2167
+ }
2168
+
2169
+ .report-preview__paper {
2170
+ width: 100%;
2171
+ max-width: 300px;
2172
+ padding: 20px;
2173
+ background: white;
2174
+ border: 1px solid var(--nice-border-color, #e0e0e0);
2175
+ border-radius: 4px;
2176
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
2177
+ display: flex;
2178
+ flex-direction: column;
2179
+ gap: 8px;
2180
+ }
2181
+
2182
+ .report-preview__section {
2183
+ display: flex;
2184
+ align-items: center;
2185
+ gap: 8px;
2186
+ padding: 8px 12px;
2187
+ border-radius: 4px;
2188
+ font-size: 12px;
2189
+ }
2190
+
2191
+ .report-preview__section--header {
2192
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.1));
2193
+ font-weight: 600;
2194
+ }
2195
+
2196
+ .report-preview__section--summary {
2197
+ background: var(--nice-bg-subtle, #f5f5f5);
2198
+ }
2199
+
2200
+ .report-preview__section--kpi {
2201
+ background: var(--nice-success-light, #e8f5e9);
2202
+ }
2203
+
2204
+ .report-preview__section--table {
2205
+ background: var(--nice-info-light, #e3f2fd);
2206
+ min-height: 40px;
2207
+ }
2208
+
2209
+ .report-preview__section--chart {
2210
+ background: var(--nice-warning-light, #fff3e0);
2211
+ min-height: 50px;
2212
+ }
2213
+
2214
+ .report-preview__section--text {
2215
+ background: var(--nice-bg-subtle, #f5f5f5);
2216
+ }
2217
+
2218
+ .report-preview__section--divider {
2219
+ background: transparent;
2220
+ border-top: 1px solid var(--nice-border-color, #e0e0e0);
2221
+ padding: 0;
2222
+ }
2223
+
2224
+ .report-preview__section--footer {
2225
+ background: var(--nice-bg-secondary, #e0e0e0);
2226
+ margin-top: auto;
2227
+ }
2228
+
2229
+ .report-preview__section-icon {
2230
+ font-size: 14px;
2231
+ }
2232
+
2233
+ .report-preview__section-label {
2234
+ flex: 1;
2235
+ overflow: hidden;
2236
+ text-overflow: ellipsis;
2237
+ white-space: nowrap;
2238
+ }
2239
+ `})]})}function bt(a={}){const{config:t,generateDarkMode:i=!0,onThemeGenerated:r,onError:n}=a,s=X(),[p,o]=c.useState(!1),[g,f]=c.useState(null),j=c.useRef(null),w=t||(s==null?void 0:s.config),N=c.useCallback(async d=>{var C,m,_,b;if(!w){const u="AI not configured";return n==null||n(u),{error:u}}o(!0);const y=performance.now();(C=j.current)==null||C.abort(),j.current=new AbortController;try{const u=G(w);let v="";switch(d.type){case"description":v=d.value;break;case"brand":v=`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":v=`Create a theme based on primary color ${d.value.primary}${d.value.secondary?` and secondary color ${d.value.secondary}`:""}`;break;case"image":v="Extract colors and create a theme from the provided image palette";break}const A=Z(ue,{description:v,generate_dark_mode:i?"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()-y,error:l.light?void 0:"Failed to generate theme",suggestions:Di(l.light)};return l.light&&(r==null||r(l.light,l.dark??void 0)),f(x),x}catch(u){const v=u instanceof Error?u.message:"Theme generation failed",A={error:v,latencyMs:performance.now()-y};return f(A),n==null||n(v),A}finally{o(!1)}},[w,i,r,n]),S=c.useCallback(async(d,y)=>{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
+ ${JSON.stringify(d,null,2)}
2241
+
2242
+ Adjustments: ${y}`}],temperature:.4,maxTokens:2048});return Ee(m).light||null}catch{return null}finally{o(!1)}},[w]),$=c.useCallback(d=>{const y=[];return y.push(" /* Colors */"),Object.entries(d.colors).forEach(([C,m])=>{y.push(` --nice-${xe(C)}: ${m};`)}),y.push(`
2243
+ /* Typography */`),Object.entries(d.typography).forEach(([C,m])=>{y.push(` --nice-${xe(C)}: ${m};`)}),y.push(`
2244
+ /* Spacing */`),Object.entries(d.spacing).forEach(([C,m])=>{y.push(` --nice-spacing-${C}: ${m};`)}),y.push(`
2245
+ /* Border Radius */`),Object.entries(d.borderRadius).forEach(([C,m])=>{y.push(` --nice-radius-${C}: ${m};`)}),y.push(`
2246
+ /* Shadows */`),Object.entries(d.shadows).forEach(([C,m])=>{y.push(` --nice-shadow-${C}: ${m};`)}),y.push(`
2247
+ /* Animations */`),Object.entries(d.animations).forEach(([C,m])=>{y.push(` --nice-${xe(C)}: ${m};`)}),`:root {
2248
+ ${y.join(`
2249
+ `)}
2250
+ }`},[]),k=c.useCallback(d=>{const y={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(y,null,2)}`},[]),P=c.useCallback(()=>{f(null)},[]),h=c.useCallback(()=>{var d;(d=j.current)==null||d.abort(),o(!1)},[]);return c.useEffect(()=>()=>{var d;(d=j.current)==null||d.abort()},[]),{generateTheme:N,adjustTheme:S,toCSSVariables:$,toTailwindConfig:k,loading:p,lastResult:g,clearResults:P,abort:h,isConfigured:!!w}}function Ee(a){var t,i,r;try{const n=((i=(t=a.choices[0])==null?void 0:t.message)==null?void 0:i.content)||"",p=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,o=JSON.parse(p);if(o.light||o.theme)return{light:fe(o.light||o.theme),dark:o.dark?fe(o.dark):null};if(o.colors)return{light:fe(o),dark:null}}catch{}return{light:null,dark:null}}function fe(a){return{id:a.id||`theme_${Date.now()}`,name:a.name||"Generated Theme",description:a.description,mode:a.mode||"light",colors:{primary:"#0066cc",primaryLight:"#4d94db",primaryDark:"#004499",secondary:"#6c757d",secondaryLight:"#9ca3af",secondaryDark:"#4b5563",accent:"#ff6b35",background:"#ffffff",surface:"#f8f9fa",text:"#212529",textMuted:"#6c757d",textInverse:"#ffffff",border:"#dee2e6",success:"#28a745",warning:"#ffc107",error:"#dc3545",info:"#17a2b8",...a.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",...a.typography},spacing:{xs:"4px",sm:"8px",md:"16px",lg:"24px",xl:"32px","2xl":"48px","3xl":"64px","4xl":"80px",...a.spacing},borderRadius:{none:"0",sm:"4px",md:"8px",lg:"12px",xl:"16px",full:"9999px",...a.borderRadius},shadows:{none:"none",sm:"0 1px 2px rgba(0,0,0,0.05)",md:"0 4px 6px rgba(0,0,0,0.1)",lg:"0 10px 15px rgba(0,0,0,0.1)",xl:"0 20px 25px rgba(0,0,0,0.1)",...a.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)",...a.animations},components:a.components,cssVariables:a.cssVariables}}function Di(a){if(!a)return[];const t=[];return t.push("Verify WCAG contrast ratios for text on background"),t.push("Test the theme in both light and dark environments"),t.push("Ensure button and input styles are consistent"),t.slice(0,3)}function xe(a){return a.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}const Fi=[{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 Bi({config:a,generateDarkMode:t=!0,onGenerate:i,showPresets:r=!0,showPreview:n=!0,className:s,style:p}){const[o,g]=c.useState("description"),[f,j]=c.useState(""),[w,N]=c.useState(""),[S,$]=c.useState(""),[k,P]=c.useState("#0066cc"),[h,d]=c.useState("light"),{generateTheme:y,toCSSVariables:C,toTailwindConfig:m,loading:_,lastResult:b,isConfigured:u}=bt({config:a,generateDarkMode:t,onThemeGenerated:i}),v=async()=>{if(_)return;let M;switch(o){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 y(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=m(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:p,children:[r&&e.jsx("div",{className:"nice-theme-ai__presets",children:Fi.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 ${o==="description"?"nice-theme-ai__tab--active":""}`,onClick:()=>g("description"),children:"📝 Description"}),e.jsx("button",{type:"button",className:`nice-theme-ai__tab ${o==="brand"?"nice-theme-ai__tab--active":""}`,onClick:()=>g("brand"),children:"🏷️ Brand"}),e.jsx("button",{type:"button",className:`nice-theme-ai__tab ${o==="colors"?"nice-theme-ai__tab--active":""}`,onClick:()=>g("colors"),children:"🎨 Colors"})]}),e.jsxs("div",{className:"nice-theme-ai__input-section",children:[o==="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:_}),o==="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:_})]}),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: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:v,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(Ji,{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:`
2252
+ .nice-theme-ai {
2253
+ font-family: var(--nice-font-family, system-ui, sans-serif);
2254
+ }
2255
+
2256
+ .nice-theme-ai--disabled {
2257
+ padding: 20px;
2258
+ background: var(--nice-disabled-bg, #f5f5f5);
2259
+ border-radius: 8px;
2260
+ color: var(--nice-text-muted, #666);
2261
+ }
2262
+
2263
+ .nice-theme-ai__presets {
2264
+ display: flex;
2265
+ flex-wrap: wrap;
2266
+ gap: 8px;
2267
+ margin-bottom: 16px;
2268
+ }
2269
+
2270
+ .nice-theme-ai__preset {
2271
+ display: flex;
2272
+ flex-direction: column;
2273
+ align-items: center;
2274
+ gap: 4px;
2275
+ padding: 12px 16px;
2276
+ border: 1px solid var(--nice-border-color, #e0e0e0);
2277
+ border-radius: 8px;
2278
+ background: white;
2279
+ cursor: pointer;
2280
+ transition: all 0.2s;
2281
+ min-width: 80px;
2282
+ }
2283
+
2284
+ .nice-theme-ai__preset:hover {
2285
+ border-color: var(--nice-primary, #0066cc);
2286
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.05));
2287
+ }
2288
+
2289
+ .nice-theme-ai__preset-icon {
2290
+ font-size: 24px;
2291
+ }
2292
+
2293
+ .nice-theme-ai__preset-name {
2294
+ font-size: 11px;
2295
+ color: var(--nice-text-muted, #666);
2296
+ }
2297
+
2298
+ .nice-theme-ai__tabs {
2299
+ display: flex;
2300
+ gap: 4px;
2301
+ margin-bottom: 12px;
2302
+ }
2303
+
2304
+ .nice-theme-ai__tab {
2305
+ padding: 8px 16px;
2306
+ border: none;
2307
+ background: var(--nice-bg-subtle, #f5f5f5);
2308
+ border-radius: 6px;
2309
+ font-size: 13px;
2310
+ cursor: pointer;
2311
+ transition: all 0.2s;
2312
+ }
2313
+
2314
+ .nice-theme-ai__tab:hover {
2315
+ background: var(--nice-bg-secondary, #e0e0e0);
2316
+ }
2317
+
2318
+ .nice-theme-ai__tab--active {
2319
+ background: var(--nice-primary, #0066cc);
2320
+ color: white;
2321
+ }
2322
+
2323
+ .nice-theme-ai__input-section {
2324
+ display: flex;
2325
+ flex-direction: column;
2326
+ gap: 12px;
2327
+ margin-bottom: 16px;
2328
+ }
2329
+
2330
+ .nice-theme-ai__textarea,
2331
+ .nice-theme-ai__input {
2332
+ padding: 12px;
2333
+ border: 1px solid var(--nice-border-color, #e0e0e0);
2334
+ border-radius: 8px;
2335
+ font-size: 14px;
2336
+ }
2337
+
2338
+ .nice-theme-ai__textarea:focus,
2339
+ .nice-theme-ai__input:focus {
2340
+ outline: none;
2341
+ border-color: var(--nice-primary, #0066cc);
2342
+ }
2343
+
2344
+ .nice-theme-ai__brand-inputs {
2345
+ display: flex;
2346
+ gap: 12px;
2347
+ }
2348
+
2349
+ .nice-theme-ai__brand-inputs .nice-theme-ai__input {
2350
+ flex: 1;
2351
+ }
2352
+
2353
+ .nice-theme-ai__color-input {
2354
+ display: flex;
2355
+ align-items: center;
2356
+ gap: 12px;
2357
+ }
2358
+
2359
+ .nice-theme-ai__color-input label {
2360
+ display: flex;
2361
+ align-items: center;
2362
+ gap: 8px;
2363
+ }
2364
+
2365
+ .nice-theme-ai__color-picker {
2366
+ width: 48px;
2367
+ height: 32px;
2368
+ padding: 0;
2369
+ border: none;
2370
+ border-radius: 4px;
2371
+ cursor: pointer;
2372
+ }
2373
+
2374
+ .nice-theme-ai__color-value {
2375
+ font-family: monospace;
2376
+ font-size: 12px;
2377
+ color: var(--nice-text-muted, #666);
2378
+ }
2379
+
2380
+ .nice-theme-ai__submit {
2381
+ padding: 12px 24px;
2382
+ background: var(--nice-primary, #0066cc);
2383
+ color: white;
2384
+ border: none;
2385
+ border-radius: 8px;
2386
+ font-weight: 500;
2387
+ cursor: pointer;
2388
+ align-self: flex-start;
2389
+ }
2390
+
2391
+ .nice-theme-ai__submit:hover:not(:disabled) {
2392
+ background: var(--nice-primary-dark, #0052a3);
2393
+ }
2394
+
2395
+ .nice-theme-ai__submit:disabled {
2396
+ opacity: 0.5;
2397
+ }
2398
+
2399
+ .nice-theme-ai__spinner {
2400
+ display: inline-block;
2401
+ width: 16px;
2402
+ height: 16px;
2403
+ border: 2px solid rgba(255, 255, 255, 0.3);
2404
+ border-top-color: white;
2405
+ border-radius: 50%;
2406
+ animation: nice-spin 0.8s linear infinite;
2407
+ }
2408
+
2409
+ @keyframes nice-spin {
2410
+ to { transform: rotate(360deg); }
2411
+ }
2412
+
2413
+ .nice-theme-ai__result {
2414
+ padding: 20px;
2415
+ background: var(--nice-bg-subtle, #f8f9fa);
2416
+ border-radius: 8px;
2417
+ border: 1px solid var(--nice-border-color, #e0e0e0);
2418
+ }
2419
+
2420
+ .nice-theme-ai__result-header {
2421
+ display: flex;
2422
+ justify-content: space-between;
2423
+ align-items: center;
2424
+ margin-bottom: 16px;
2425
+ }
2426
+
2427
+ .nice-theme-ai__theme-info {
2428
+ display: flex;
2429
+ flex-direction: column;
2430
+ gap: 4px;
2431
+ }
2432
+
2433
+ .nice-theme-ai__theme-name {
2434
+ font-size: 18px;
2435
+ font-weight: 600;
2436
+ }
2437
+
2438
+ .nice-theme-ai__theme-desc {
2439
+ font-size: 14px;
2440
+ color: var(--nice-text-muted, #666);
2441
+ }
2442
+
2443
+ .nice-theme-ai__actions {
2444
+ display: flex;
2445
+ gap: 8px;
2446
+ }
2447
+
2448
+ .nice-theme-ai__actions button {
2449
+ padding: 6px 12px;
2450
+ border: 1px solid var(--nice-border-color, #e0e0e0);
2451
+ border-radius: 6px;
2452
+ background: white;
2453
+ font-size: 12px;
2454
+ cursor: pointer;
2455
+ }
2456
+
2457
+ .nice-theme-ai__actions button:hover {
2458
+ border-color: var(--nice-primary, #0066cc);
2459
+ }
2460
+
2461
+ .nice-theme-ai__mode-toggle {
2462
+ display: flex;
2463
+ border-radius: 6px;
2464
+ overflow: hidden;
2465
+ border: 1px solid var(--nice-border-color, #e0e0e0);
2466
+ }
2467
+
2468
+ .nice-theme-ai__mode-toggle button {
2469
+ border: none;
2470
+ border-radius: 0;
2471
+ padding: 6px 10px;
2472
+ }
2473
+
2474
+ .nice-theme-ai__mode-toggle button.active {
2475
+ background: var(--nice-primary, #0066cc);
2476
+ color: white;
2477
+ }
2478
+
2479
+ .nice-theme-ai__palette {
2480
+ margin-top: 20px;
2481
+ }
2482
+
2483
+ .nice-theme-ai__palette-title,
2484
+ .nice-theme-ai__typography-title {
2485
+ font-weight: 600;
2486
+ margin-bottom: 12px;
2487
+ }
2488
+
2489
+ .nice-theme-ai__colors {
2490
+ display: grid;
2491
+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
2492
+ gap: 12px;
2493
+ }
2494
+
2495
+ .nice-theme-ai__color {
2496
+ display: flex;
2497
+ flex-direction: column;
2498
+ gap: 4px;
2499
+ }
2500
+
2501
+ .nice-theme-ai__color-swatch {
2502
+ width: 100%;
2503
+ height: 40px;
2504
+ border-radius: 6px;
2505
+ border: 1px solid rgba(0, 0, 0, 0.1);
2506
+ }
2507
+
2508
+ .nice-theme-ai__color-name {
2509
+ font-size: 12px;
2510
+ font-weight: 500;
2511
+ }
2512
+
2513
+ .nice-theme-ai__color-hex {
2514
+ font-size: 11px;
2515
+ font-family: monospace;
2516
+ color: var(--nice-text-muted, #666);
2517
+ }
2518
+
2519
+ .nice-theme-ai__typography {
2520
+ margin-top: 20px;
2521
+ }
2522
+ `})]}):e.jsx("div",{className:`nice-theme-ai nice-theme-ai--disabled ${s||""}`,style:p,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function Ji({theme:a}){return e.jsxs("div",{className:"theme-preview",style:{"--preview-primary":a.colors.primary,"--preview-bg":a.colors.background,"--preview-surface":a.colors.surface,"--preview-text":a.colors.text,"--preview-border":a.colors.border,"--preview-radius":a.borderRadius.md,fontFamily:a.typography.fontFamily},children:[e.jsxs("div",{className:"theme-preview__header",children:[e.jsx("span",{style:{color:a.colors.primary,fontWeight:a.typography.fontWeightBold},children:a.name}),e.jsxs("div",{className:"theme-preview__dots",children:[e.jsx("span",{style:{background:a.colors.error}}),e.jsx("span",{style:{background:a.colors.warning}}),e.jsx("span",{style:{background:a.colors.success}})]})]}),e.jsxs("div",{className:"theme-preview__content",children:[e.jsx("button",{style:{background:a.colors.primary,color:a.colors.textInverse,borderRadius:a.borderRadius.md,padding:`${a.spacing.sm} ${a.spacing.md}`},children:"Primary Button"}),e.jsx("button",{style:{background:a.colors.secondary,color:a.colors.textInverse,borderRadius:a.borderRadius.md,padding:`${a.spacing.sm} ${a.spacing.md}`},children:"Secondary"}),e.jsx("input",{type:"text",placeholder:"Input field",readOnly:!0,style:{border:`1px solid ${a.colors.border}`,borderRadius:a.borderRadius.md,padding:a.spacing.sm,background:a.colors.surface}})]}),e.jsx("style",{children:`
2523
+ .theme-preview {
2524
+ background: var(--preview-bg);
2525
+ border: 1px solid var(--preview-border);
2526
+ border-radius: var(--preview-radius);
2527
+ padding: 16px;
2528
+ margin-bottom: 16px;
2529
+ }
2530
+
2531
+ .theme-preview__header {
2532
+ display: flex;
2533
+ justify-content: space-between;
2534
+ align-items: center;
2535
+ margin-bottom: 16px;
2536
+ padding-bottom: 12px;
2537
+ border-bottom: 1px solid var(--preview-border);
2538
+ }
2539
+
2540
+ .theme-preview__dots {
2541
+ display: flex;
2542
+ gap: 6px;
2543
+ }
2544
+
2545
+ .theme-preview__dots span {
2546
+ width: 12px;
2547
+ height: 12px;
2548
+ border-radius: 50%;
2549
+ }
2550
+
2551
+ .theme-preview__content {
2552
+ display: flex;
2553
+ gap: 12px;
2554
+ flex-wrap: wrap;
2555
+ }
2556
+
2557
+ .theme-preview__content button,
2558
+ .theme-preview__content input {
2559
+ border: none;
2560
+ font-size: 13px;
2561
+ cursor: pointer;
2562
+ }
2563
+
2564
+ .theme-preview__content input {
2565
+ cursor: text;
2566
+ width: 150px;
2567
+ }
2568
+ `})]})}function yt(a={}){const{config:t,targetDevice:i="responsive",onLayoutGenerated:r,onError:n}=a,s=X(),[p,o]=c.useState(!1),[g,f]=c.useState(null),j=c.useRef(null),w=t||(s==null?void 0:s.config),N=c.useCallback(async(h,d)=>{var C,m,_;if(!w){const b="AI not configured";return n==null||n(b),{error:b}}o(!0);const y=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.
2569
+ Return JSON with this structure:
2570
+ {
2571
+ "id": "unique_id",
2572
+ "name": "Layout Name",
2573
+ "description": "Description",
2574
+ "type": "${d||"dashboard"}",
2575
+ "container": {
2576
+ "direction": "row|column|grid",
2577
+ "gap": "16px",
2578
+ "padding": "20px",
2579
+ "gridColumns": 12,
2580
+ "align": "start|center|end|stretch",
2581
+ "justify": "start|center|end|between|around"
2582
+ },
2583
+ "regions": [
2584
+ {
2585
+ "id": "region_id",
2586
+ "type": "header|sidebar|main|footer|aside|nav|content",
2587
+ "position": { "gridColumn": "1 / -1", "gridRow": "1" },
2588
+ "size": { "height": "64px" },
2589
+ "responsive": {
2590
+ "sm": { "size": { "height": "auto" } }
2591
+ }
2592
+ }
2593
+ ],
2594
+ "cssGrid": "grid-template-areas string",
2595
+ "breakpoints": {
2596
+ "xs": "320px",
2597
+ "sm": "640px",
2598
+ "md": "768px",
2599
+ "lg": "1024px",
2600
+ "xl": "1280px",
2601
+ "2xl": "1536px"
2602
+ }
2603
+ }`,v=await b.chat({messages:[{role:"system",content:u},{role:"user",content:`Create a ${i} layout: ${h}${d?` (type: ${d})`:""}`}],temperature:.5,maxTokens:2048}),A=qi(v),R={layout:A||void 0,rawResponse:(_=(m=v.choices[0])==null?void 0:m.message)==null?void 0:_.content,latencyMs:performance.now()-y,error:A?void 0:"Failed to generate layout",suggestions:Ui(A)};return A&&(r==null||r(A)),f(R),R}catch(b){const u=b instanceof Error?b.message:"Layout generation failed",v={error:u,latencyMs:performance.now()-y};return f(v),n==null||n(u),v}finally{o(!1)}},[w,i,r,n]),S=c.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 y=typeof h.container.gridColumns=="number"?`repeat(${h.container.gridColumns}, 1fr)`:h.container.gridColumns;d+=` grid-template-columns: ${y};
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};
2613
+ `),d+=`}
2614
+
2615
+ `,h.regions.forEach(y=>{var C,m,_,b,u,v;d+=`.${h.id}__${y.id} {
2616
+ `,(C=y.position)!=null&&C.gridColumn&&(d+=` grid-column: ${y.position.gridColumn};
2617
+ `),(m=y.position)!=null&&m.gridRow&&(d+=` grid-row: ${y.position.gridRow};
2618
+ `),(_=y.size)!=null&&_.width&&(d+=` width: ${y.size.width};
2619
+ `),(b=y.size)!=null&&b.height&&(d+=` height: ${y.size.height};
2620
+ `),(u=y.size)!=null&&u.minWidth&&(d+=` min-width: ${y.size.minWidth};
2621
+ `),(v=y.size)!=null&&v.maxWidth&&(d+=` max-width: ${y.size.maxWidth};
2622
+ `),d+=`}
2623
+
2624
+ `}),h.breakpoints&&Object.entries(h.breakpoints).forEach(([y,C])=>{const m=h.regions.filter(_=>{var b;return(b=_.responsive)==null?void 0:b[y]});m.length>0&&(d+=`@media (max-width: ${C}) {
2625
+ `,m.forEach(_=>{var u,v;const b=_.responsive[y];d+=` .${h.id}__${_.id} {
2626
+ `,(u=b.size)!=null&&u.width&&(d+=` width: ${b.size.width};
2627
+ `),(v=b.size)!=null&&v.height&&(d+=` height: ${b.size.height};
2628
+ `),d+=` }
2629
+ `}),d+=`}
2630
+
2631
+ `)}),d},[]),$=c.useCallback(h=>{const d=h.regions.map(y=>` <div className="${h.id}__${y.id}">{/* ${y.type} */}</div>`).join(`
2632
+ `);return`import React from 'react';
2633
+ import './${h.id}.css';
2634
+
2635
+ export function ${vt(h.name)}() {
2636
+ return (
2637
+ <div className="${h.id}">
2638
+ ${d}
2639
+ </div>
2640
+ );
2641
+ }`},[]),k=c.useCallback(()=>{f(null)},[]),P=c.useCallback(()=>{var h;(h=j.current)==null||h.abort(),o(!1)},[]);return c.useEffect(()=>()=>{var h;(h=j.current)==null||h.abort()},[]),{generateLayout:N,toCSS:S,toReactComponent:$,loading:p,lastResult:g,clearResults:k,abort:P,isConfigured:!!w}}function qi(a){var t,i,r;try{const n=((i=(t=a.choices[0])==null?void 0:t.message)==null?void 0:i.content)||"",p=((r=(n.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,n])[1])==null?void 0:r.trim())||n,o=JSON.parse(p);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 Ui(a){if(!a)return[];const t=[],i=new Set(a.regions.map(r=>r.type));return i.has("header")||t.push("Consider adding a header region for navigation"),!i.has("sidebar")&&a.type==="dashboard"&&t.push("Add a sidebar for dashboard navigation"),a.regions.some(r=>!r.responsive)&&t.push("Add responsive breakpoints for mobile compatibility"),t.slice(0,3)}function vt(a){return a.replace(/[^a-zA-Z0-9]+(.)/g,(t,i)=>i.toUpperCase()).replace(/^./,t=>t.toUpperCase())}const Hi=[{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:a,targetDevice:t="responsive",onGenerate:i,showTypeSelector:r=!0,showPreview:n=!0,className:s,style:p,renderLayout:o}){const[g,f]=c.useState(""),[j,w]=c.useState(null),{generateLayout:N,toCSS:S,toReactComponent:$,loading:k,lastResult:P,isConfigured:h}=yt({config:a,targetDevice:t,onLayoutGenerated:i}),d=async()=>{!g.trim()||k||await N(g,j||void 0)},y=()=>{if(!(P!=null&&P.layout))return;const m=S(P.layout),_=new Blob([m],{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 m=$(P.layout),_=new Blob([m],{type:"text/javascript"}),b=URL.createObjectURL(_),u=document.createElement("a");u.href=b,u.download=`${vt(P.layout.name)}.tsx`,u.click(),URL.revokeObjectURL(b)};return h?e.jsxs("div",{className:`nice-layout-ai ${s||""}`,style:p,children:[r&&e.jsx("div",{className:"nice-layout-ai__types",children:Hi.map(({type:m,icon:_,label:b})=>e.jsxs("button",{type:"button",className:`nice-layout-ai__type ${j===m?"nice-layout-ai__type--selected":""}`,onClick:()=>w(j===m?null:m),children:[e.jsx("span",{className:"nice-layout-ai__type-icon",children:_}),e.jsx("span",{className:"nice-layout-ai__type-label",children:b})]},m))}),e.jsxs("div",{className:"nice-layout-ai__input-section",children:[e.jsx("textarea",{value:g,onChange:m=>f(m.target.value),placeholder:"Describe the layout you need... (e.g., 'Admin dashboard with sidebar navigation and header')",className:"nice-layout-ai__input",rows:3,disabled:k}),e.jsx("button",{type:"button",onClick: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:()=>i==null?void 0:i(P.layout),children:"✅ Use Layout"}),e.jsx("button",{type:"button",onClick:y,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(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(P.layout):e.jsx(Gi,{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:`
2642
+ .nice-layout-ai {
2643
+ font-family: var(--nice-font-family, system-ui, sans-serif);
2644
+ }
2645
+
2646
+ .nice-layout-ai--disabled {
2647
+ padding: 20px;
2648
+ background: var(--nice-disabled-bg, #f5f5f5);
2649
+ border-radius: 8px;
2650
+ color: var(--nice-text-muted, #666);
2651
+ }
2652
+
2653
+ .nice-layout-ai__types {
2654
+ display: flex;
2655
+ flex-wrap: wrap;
2656
+ gap: 8px;
2657
+ margin-bottom: 16px;
2658
+ }
2659
+
2660
+ .nice-layout-ai__type {
2661
+ display: flex;
2662
+ flex-direction: column;
2663
+ align-items: center;
2664
+ gap: 4px;
2665
+ padding: 8px 12px;
2666
+ border: 1px solid var(--nice-border-color, #e0e0e0);
2667
+ border-radius: 8px;
2668
+ background: white;
2669
+ cursor: pointer;
2670
+ transition: all 0.2s;
2671
+ }
2672
+
2673
+ .nice-layout-ai__type:hover {
2674
+ border-color: var(--nice-primary, #0066cc);
2675
+ }
2676
+
2677
+ .nice-layout-ai__type--selected {
2678
+ border-color: var(--nice-primary, #0066cc);
2679
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.1));
2680
+ }
2681
+
2682
+ .nice-layout-ai__type-icon {
2683
+ font-size: 20px;
2684
+ }
2685
+
2686
+ .nice-layout-ai__type-label {
2687
+ font-size: 11px;
2688
+ color: var(--nice-text-muted, #666);
2689
+ }
2690
+
2691
+ .nice-layout-ai__input-section {
2692
+ display: flex;
2693
+ gap: 12px;
2694
+ margin-bottom: 16px;
2695
+ }
2696
+
2697
+ .nice-layout-ai__input {
2698
+ flex: 1;
2699
+ padding: 12px;
2700
+ border: 1px solid var(--nice-border-color, #e0e0e0);
2701
+ border-radius: 8px;
2702
+ font-size: 14px;
2703
+ resize: vertical;
2704
+ }
2705
+
2706
+ .nice-layout-ai__input:focus {
2707
+ outline: none;
2708
+ border-color: var(--nice-primary, #0066cc);
2709
+ }
2710
+
2711
+ .nice-layout-ai__submit {
2712
+ padding: 12px 24px;
2713
+ background: var(--nice-primary, #0066cc);
2714
+ color: white;
2715
+ border: none;
2716
+ border-radius: 8px;
2717
+ font-weight: 500;
2718
+ cursor: pointer;
2719
+ white-space: nowrap;
2720
+ }
2721
+
2722
+ .nice-layout-ai__submit:disabled {
2723
+ opacity: 0.5;
2724
+ }
2725
+
2726
+ .nice-layout-ai__spinner {
2727
+ display: inline-block;
2728
+ width: 16px;
2729
+ height: 16px;
2730
+ border: 2px solid rgba(255, 255, 255, 0.3);
2731
+ border-top-color: white;
2732
+ border-radius: 50%;
2733
+ animation: nice-spin 0.8s linear infinite;
2734
+ }
2735
+
2736
+ @keyframes nice-spin {
2737
+ to { transform: rotate(360deg); }
2738
+ }
2739
+
2740
+ .nice-layout-ai__result {
2741
+ padding: 20px;
2742
+ background: var(--nice-bg-subtle, #f8f9fa);
2743
+ border-radius: 8px;
2744
+ border: 1px solid var(--nice-border-color, #e0e0e0);
2745
+ }
2746
+
2747
+ .nice-layout-ai__result-header {
2748
+ display: flex;
2749
+ justify-content: space-between;
2750
+ align-items: center;
2751
+ margin-bottom: 16px;
2752
+ }
2753
+
2754
+ .nice-layout-ai__layout-info {
2755
+ display: flex;
2756
+ align-items: center;
2757
+ gap: 12px;
2758
+ }
2759
+
2760
+ .nice-layout-ai__layout-name {
2761
+ font-size: 18px;
2762
+ font-weight: 600;
2763
+ }
2764
+
2765
+ .nice-layout-ai__layout-type {
2766
+ padding: 4px 10px;
2767
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.1));
2768
+ border-radius: 4px;
2769
+ font-size: 12px;
2770
+ color: var(--nice-primary, #0066cc);
2771
+ }
2772
+
2773
+ .nice-layout-ai__actions {
2774
+ display: flex;
2775
+ gap: 8px;
2776
+ }
2777
+
2778
+ .nice-layout-ai__actions button {
2779
+ padding: 6px 12px;
2780
+ border: 1px solid var(--nice-border-color, #e0e0e0);
2781
+ border-radius: 6px;
2782
+ background: white;
2783
+ font-size: 12px;
2784
+ cursor: pointer;
2785
+ }
2786
+
2787
+ .nice-layout-ai__actions button:first-child {
2788
+ background: var(--nice-success, #2e7d32);
2789
+ color: white;
2790
+ border: none;
2791
+ }
2792
+
2793
+ .nice-layout-ai__regions {
2794
+ margin-bottom: 16px;
2795
+ }
2796
+
2797
+ .nice-layout-ai__regions-title {
2798
+ font-weight: 500;
2799
+ margin-bottom: 8px;
2800
+ }
2801
+
2802
+ .nice-layout-ai__regions-list {
2803
+ display: flex;
2804
+ flex-wrap: wrap;
2805
+ gap: 8px;
2806
+ }
2807
+
2808
+ .nice-layout-ai__region {
2809
+ padding: 6px 12px;
2810
+ border-radius: 6px;
2811
+ font-size: 12px;
2812
+ font-weight: 500;
2813
+ }
2814
+
2815
+ .nice-layout-ai__region--header {
2816
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.1));
2817
+ color: var(--nice-primary, #0066cc);
2818
+ }
2819
+
2820
+ .nice-layout-ai__region--sidebar,
2821
+ .nice-layout-ai__region--aside {
2822
+ background: var(--nice-success-light, #e8f5e9);
2823
+ color: var(--nice-success, #2e7d32);
2824
+ }
2825
+
2826
+ .nice-layout-ai__region--main,
2827
+ .nice-layout-ai__region--content {
2828
+ background: var(--nice-info-light, #e3f2fd);
2829
+ color: var(--nice-info, #0288d1);
2830
+ }
2831
+
2832
+ .nice-layout-ai__region--footer {
2833
+ background: var(--nice-bg-secondary, #e0e0e0);
2834
+ color: var(--nice-text-muted, #666);
2835
+ }
2836
+
2837
+ .nice-layout-ai__region--nav {
2838
+ background: var(--nice-warning-light, #fff3e0);
2839
+ color: var(--nice-warning, #f57c00);
2840
+ }
2841
+
2842
+ .nice-layout-ai__preview {
2843
+ margin-bottom: 16px;
2844
+ padding: 20px;
2845
+ background: white;
2846
+ border-radius: 8px;
2847
+ border: 1px solid var(--nice-border-color, #e0e0e0);
2848
+ }
2849
+
2850
+ .nice-layout-ai__json summary {
2851
+ cursor: pointer;
2852
+ font-size: 13px;
2853
+ color: var(--nice-text-muted, #666);
2854
+ }
2855
+
2856
+ .nice-layout-ai__json pre {
2857
+ margin: 8px 0 0;
2858
+ padding: 12px;
2859
+ background: var(--nice-code-bg, #1e1e1e);
2860
+ color: var(--nice-code-color, #d4d4d4);
2861
+ border-radius: 6px;
2862
+ font-size: 12px;
2863
+ overflow-x: auto;
2864
+ }
2865
+ `})]}):e.jsx("div",{className:`nice-layout-ai nice-layout-ai--disabled ${s||""}`,style:p,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}function Gi({layout:a}){const t=i=>({header:"#e3f2fd",sidebar:"#e8f5e9",aside:"#e8f5e9",main:"#fff3e0",content:"#fff3e0",footer:"#f5f5f5",nav:"#fce4ec"})[i]||"#f5f5f5";return e.jsx("div",{className:"layout-preview",style:{display:a.container.direction==="grid"?"grid":"flex",flexDirection:a.container.direction==="column"?"column":"row",gridTemplateColumns:a.container.direction==="grid"&&a.container.gridColumns?typeof a.container.gridColumns=="number"?`repeat(${a.container.gridColumns}, 1fr)`:a.container.gridColumns:void 0,gap:a.container.gap||"8px",minHeight:"300px"},children:a.regions.map(i=>{var r,n,s,p,o,g;return e.jsx("div",{className:"layout-preview__region",style:{gridColumn:(r=i.position)==null?void 0:r.gridColumn,gridRow:(n=i.position)==null?void 0:n.gridRow,width:(s=i.size)==null?void 0:s.width,height:((p=i.size)==null?void 0:p.height)||"80px",minWidth:(o=i.size)==null?void 0:o.minWidth,maxWidth:(g=i.size)==null?void 0:g.maxWidth,background:t(i.type),borderRadius:"6px",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",fontWeight:500,color:"#666",border:"1px dashed #ccc"},children:i.type},i.id)})})}function _t(a={}){const{config:t,wcagLevel:i="AA",onAuditComplete:r,onError:n}=a,s=X(),[p,o]=c.useState(!1),[g,f]=c.useState(null),j=c.useRef(null),w=t||(s==null?void 0:s.config),N=c.useCallback(async(d,y)=>{var C;if(!w){const m="AI not configured";return n==null||n(m),je("html",i,m)}o(!0),(C=j.current)==null||C.abort(),j.current=new AbortController;try{const m=G(w),_=`You are a WCAG accessibility expert. Analyze the provided HTML code for accessibility issues at WCAG ${i} level.
2866
+
2867
+ Return JSON with this exact structure:
2868
+ {
2869
+ "issues": [
2870
+ {
2871
+ "id": "issue_1",
2872
+ "category": "color-contrast|aria-labels|keyboard-nav|focus-management|alt-text|form-labels|headings|landmarks|semantic-html|language|motion|timing",
2873
+ "severity": "critical|serious|moderate|minor",
2874
+ "wcagCriteria": "1.1.1",
2875
+ "wcagLevel": "A|AA|AAA",
2876
+ "title": "Issue Title",
2877
+ "description": "Detailed description",
2878
+ "element": "<button>...</button>",
2879
+ "selector": "button.submit",
2880
+ "impact": "Impact on users",
2881
+ "suggestion": "How to fix",
2882
+ "codeExample": "Fixed code example"
2883
+ }
2884
+ ],
2885
+ "score": 85,
2886
+ "recommendations": ["General recommendation 1", "Recommendation 2"]
2887
+ }
2888
+
2889
+ Focus on:
2890
+ 1. Color contrast ratios
2891
+ 2. Missing ARIA labels
2892
+ 3. Keyboard accessibility
2893
+ 4. Focus management
2894
+ 5. Alt text for images
2895
+ 6. Form labels
2896
+ 7. Heading hierarchy
2897
+ 8. Landmark regions
2898
+ 9. Semantic HTML usage
2899
+ 10. Language attributes`,b=await m.chat({messages:[{role:"system",content:_},{role:"user",content:`Analyze this HTML for accessibility:
2900
+ ${y?`Context: ${y}
2901
+
2902
+ `:""}${d}`}],temperature:.3,maxTokens:4096}),u=Vi(b,"html",i);return f(u),r==null||r(u),u}catch(m){const _=m instanceof Error?m.message:"Audit failed";return n==null||n(_),je("html",i,_)}finally{o(!1)}},[w,i,r,n]),S=c.useCallback((d,y)=>{const C=pe(me(d)),m=pe(me(y)),_=(Math.max(C,m)+.05)/(Math.min(C,m)+.05),b={foreground:d,background:y,ratio:Math.round(_*100)/100,passesAA:_>=4.5,passesAALarge:_>=3,passesAAA:_>=7,passesAAALarge:_>=4.5};return b.passesAA||(b.suggestions=Yi(d,y,4.5)),b},[]),$=c.useCallback(async d=>{var y,C;if(!w)return n==null||n("AI not configured"),[];try{const v=(((C=(y=(await G(w).chat({messages:[{role:"system",content:`Analyze the HTML for ARIA attribute issues.
2903
+ Return JSON array:
2904
+ [{
2905
+ "element": "<button>...",
2906
+ "hasRole": boolean,
2907
+ "hasLabel": boolean,
2908
+ "role": "button",
2909
+ "label": "Submit form",
2910
+ "issues": ["Missing aria-label"],
2911
+ "suggestions": ["Add aria-label='Submit form'"]
2912
+ }]`},{role:"user",content:`Validate ARIA in:
2913
+ ${d}`}],temperature:.2,maxTokens:2048})).choices[0])==null?void 0:y.message)==null?void 0:C.content)||"").match(/\[[\s\S]*\]/);if(v)return JSON.parse(v[0])}catch{}return[]},[w,n]),k=c.useCallback(async d=>{var y,C;if(!w)return n==null||n("AI not configured"),d;try{const b=((C=(y=(await G(w).chat({messages:[{role:"system",content:`You are an accessibility expert. Improve the HTML to be fully WCAG ${i} compliant.
2914
+ Add proper ARIA attributes, semantic HTML, keyboard handlers, focus management.
2915
+ Return only the improved HTML code.`},{role:"user",content:`Make this accessible:
2916
+ ${d}`}],temperature:.3,maxTokens:2048})).choices[0])==null?void 0:y.message)==null?void 0:C.content)||"",u=b.match(/```(?:html)?\s*([\s\S]*?)```/);return u?u[1].trim():b.trim()}catch{return d}},[w,i,n]),P=c.useCallback(()=>{f(null)},[]),h=c.useCallback(()=>{var d;(d=j.current)==null||d.abort(),o(!1)},[]);return c.useEffect(()=>()=>{var d;(d=j.current)==null||d.abort()},[]),{analyzeHTML:N,checkContrast:S,validateARIA:$,suggestAccessibleCode:k,loading:p,lastAudit:g,clearAudit:P,abort:h,isConfigured:!!w}}function je(a,t,i){return{timestamp:new Date,target:a,wcagLevel:t,issues:i?[{id:"error",category:"semantic-html",severity:"critical",wcagCriteria:"N/A",wcagLevel:"A",title:"Audit Error",description:i,impact:"Audit could not complete",suggestion:"Try again or check configuration"}]:[],score:i?0:100,summary:{critical:i?1:0,serious:0,moderate:0,minor:0,passed:0},recommendations:[]}}function Vi(a,t,i){var r,n,s;try{const p=((n=(r=a.choices[0])==null?void 0:r.message)==null?void 0:n.content)||"",g=((s=(p.match(/```(?:json)?\s*([\s\S]*?)```/)||[null,p])[1])==null?void 0:s.trim())||p,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:t,wcagLevel:i,issues:j,score:f.score??Ki(w),summary:w,recommendations:f.recommendations||[]}}catch{return je(t,i,"Failed to parse audit results")}}function Ki(a){const t=a.critical*25+a.serious*15+a.moderate*5+a.minor*2;return Math.max(0,100-t)}function me(a){const t=a.replace("#","");return t.length===3?{r:parseInt(t[0]+t[0],16),g:parseInt(t[1]+t[1],16),b:parseInt(t[2]+t[2],16)}:{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}}function pe(a){const[t,i,r]=[a.r,a.g,a.b].map(n=>(n/=255,n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4)));return .2126*t+.7152*i+.0722*r}function Yi(a,t,i){const r=[],n=me(a),s=me(t),p={r:Math.max(0,n.r-40),g:Math.max(0,n.g-40),b:Math.max(0,n.b-40)},o=`#${p.r.toString(16).padStart(2,"0")}${p.g.toString(16).padStart(2,"0")}${p.b.toString(16).padStart(2,"0")}`,g=pe(p),f=pe(s);(Math.max(g,f)+.05)/(Math.min(g,f)+.05)>=i&&r.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)},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:"#ffebee",color:"#c62828",icon:"🚫"},serious:{bg:"#fff3e0",color:"#e65100",icon:"⚠️"},moderate:{bg:"#fff8e1",color:"#f57f17",icon:"⚡"},minor:{bg:"#e3f2fd",color:"#1565c0",icon:"ℹ️"}};function Xi({config:a,wcagLevel:t="AA",onAuditComplete:i,showContrastChecker:r=!0,className:n,style:s,renderIssue:p}){const[o,g]=c.useState(""),[f,j]=c.useState("#333333"),[w,N]=c.useState("#ffffff"),[S,$]=c.useState(null),{analyzeHTML:k,checkContrast:P,suggestAccessibleCode:h,loading:d,lastAudit:y,isConfigured:C}=_t({config:a,wcagLevel:t,onAuditComplete:i}),m=async()=>{!o.trim()||d||await k(o)},_=()=>{const u=P(f,w);$(u)},b=async()=>{if(!o.trim())return;const u=await h(o);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,v)=>e.jsx("div",{children:u},v))})]})]}),e.jsxs("div",{className:"nice-a11y-ai__analyzer",children:[e.jsxs("h3",{children:["HTML Accessibility Analyzer (WCAG ",t,")"]}),e.jsx("textarea",{value:o,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:m,disabled:d||!o.trim(),children:d?e.jsx("span",{className:"nice-a11y-ai__spinner"}):"🔍 Analyze"}),e.jsx("button",{type:"button",onClick:b,disabled:d||!o.trim(),children:"🔧 Auto-Fix"})]})]}),y&&e.jsxs("div",{className:"nice-a11y-ai__audit",children:[e.jsxs("div",{className:"nice-a11y-ai__audit-header",children:[e.jsxs("div",{className:"nice-a11y-ai__score",children:[e.jsx("span",{className:"nice-a11y-ai__score-value",children:y.score}),e.jsx("span",{className:"nice-a11y-ai__score-label",children:"Score"})]}),e.jsxs("div",{className:"nice-a11y-ai__summary",children:[e.jsxs("span",{className:"critical",children:[y.summary.critical," Critical"]}),e.jsxs("span",{className:"serious",children:[y.summary.serious," Serious"]}),e.jsxs("span",{className:"moderate",children:[y.summary.moderate," Moderate"]}),e.jsxs("span",{className:"minor",children:[y.summary.minor," Minor"]})]})]}),e.jsx("div",{className:"nice-a11y-ai__issues",children:y.issues.map(u=>p?p(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))}),y.recommendations.length>0&&e.jsxs("div",{className:"nice-a11y-ai__recommendations",children:[e.jsx("h4",{children:"General Recommendations"}),e.jsx("ul",{children:y.recommendations.map((u,v)=>e.jsx("li",{children:u},v))})]})]}),e.jsx("style",{children:`
2917
+ .nice-a11y-ai {
2918
+ font-family: var(--nice-font-family, system-ui, sans-serif);
2919
+ }
2920
+
2921
+ .nice-a11y-ai--disabled {
2922
+ padding: 20px;
2923
+ background: var(--nice-disabled-bg, #f5f5f5);
2924
+ border-radius: 8px;
2925
+ color: var(--nice-text-muted, #666);
2926
+ }
2927
+
2928
+ .nice-a11y-ai__contrast {
2929
+ padding: 20px;
2930
+ background: var(--nice-bg-subtle, #f8f9fa);
2931
+ border-radius: 8px;
2932
+ margin-bottom: 20px;
2933
+ }
2934
+
2935
+ .nice-a11y-ai__contrast h3 {
2936
+ margin: 0 0 16px;
2937
+ font-size: 16px;
2938
+ }
2939
+
2940
+ .nice-a11y-ai__contrast-inputs {
2941
+ display: flex;
2942
+ gap: 20px;
2943
+ align-items: flex-end;
2944
+ }
2945
+
2946
+ .nice-a11y-ai__contrast-inputs label {
2947
+ display: flex;
2948
+ flex-direction: column;
2949
+ gap: 6px;
2950
+ font-size: 13px;
2951
+ }
2952
+
2953
+ .nice-a11y-ai__contrast-inputs input[type="color"] {
2954
+ width: 40px;
2955
+ height: 30px;
2956
+ border: 1px solid #ddd;
2957
+ border-radius: 4px;
2958
+ cursor: pointer;
2959
+ }
2960
+
2961
+ .nice-a11y-ai__contrast-inputs input[type="text"] {
2962
+ width: 80px;
2963
+ padding: 6px;
2964
+ border: 1px solid #ddd;
2965
+ border-radius: 4px;
2966
+ font-family: monospace;
2967
+ }
2968
+
2969
+ .nice-a11y-ai__contrast-inputs button {
2970
+ padding: 8px 20px;
2971
+ background: var(--nice-primary, #0066cc);
2972
+ color: white;
2973
+ border: none;
2974
+ border-radius: 6px;
2975
+ cursor: pointer;
2976
+ }
2977
+
2978
+ .nice-a11y-ai__contrast-result {
2979
+ margin-top: 16px;
2980
+ display: flex;
2981
+ gap: 20px;
2982
+ align-items: center;
2983
+ }
2984
+
2985
+ .nice-a11y-ai__contrast-preview {
2986
+ padding: 20px 30px;
2987
+ border-radius: 8px;
2988
+ font-size: 18px;
2989
+ font-weight: 500;
2990
+ border: 1px solid #ddd;
2991
+ }
2992
+
2993
+ .nice-a11y-ai__contrast-ratio {
2994
+ display: flex;
2995
+ flex-direction: column;
2996
+ gap: 8px;
2997
+ }
2998
+
2999
+ .nice-a11y-ai__ratio-value {
3000
+ font-size: 24px;
3001
+ font-weight: 700;
3002
+ }
3003
+
3004
+ .nice-a11y-ai__passes {
3005
+ display: flex;
3006
+ gap: 12px;
3007
+ font-size: 13px;
3008
+ }
3009
+
3010
+ .nice-a11y-ai__passes .pass { color: var(--nice-success, #2e7d32); }
3011
+ .nice-a11y-ai__passes .fail { color: var(--nice-error, #c62828); }
3012
+
3013
+ .nice-a11y-ai__suggestions {
3014
+ padding: 12px;
3015
+ background: var(--nice-warning-light, #fff8e1);
3016
+ border-radius: 6px;
3017
+ font-size: 13px;
3018
+ }
3019
+
3020
+ .nice-a11y-ai__analyzer {
3021
+ padding: 20px;
3022
+ background: var(--nice-bg-subtle, #f8f9fa);
3023
+ border-radius: 8px;
3024
+ margin-bottom: 20px;
3025
+ }
3026
+
3027
+ .nice-a11y-ai__analyzer h3 {
3028
+ margin: 0 0 16px;
3029
+ font-size: 16px;
3030
+ }
3031
+
3032
+ .nice-a11y-ai__input {
3033
+ width: 100%;
3034
+ padding: 12px;
3035
+ border: 1px solid var(--nice-border-color, #e0e0e0);
3036
+ border-radius: 8px;
3037
+ font-family: monospace;
3038
+ font-size: 13px;
3039
+ resize: vertical;
3040
+ margin-bottom: 12px;
3041
+ }
3042
+
3043
+ .nice-a11y-ai__actions {
3044
+ display: flex;
3045
+ gap: 12px;
3046
+ }
3047
+
3048
+ .nice-a11y-ai__actions button {
3049
+ padding: 10px 24px;
3050
+ border: none;
3051
+ border-radius: 6px;
3052
+ font-weight: 500;
3053
+ cursor: pointer;
3054
+ }
3055
+
3056
+ .nice-a11y-ai__actions button:first-child {
3057
+ background: var(--nice-primary, #0066cc);
3058
+ color: white;
3059
+ }
3060
+
3061
+ .nice-a11y-ai__actions button:last-child {
3062
+ background: var(--nice-success, #2e7d32);
3063
+ color: white;
3064
+ }
3065
+
3066
+ .nice-a11y-ai__actions button:disabled {
3067
+ opacity: 0.5;
3068
+ }
3069
+
3070
+ .nice-a11y-ai__spinner {
3071
+ display: inline-block;
3072
+ width: 16px;
3073
+ height: 16px;
3074
+ border: 2px solid rgba(255, 255, 255, 0.3);
3075
+ border-top-color: white;
3076
+ border-radius: 50%;
3077
+ animation: nice-spin 0.8s linear infinite;
3078
+ }
3079
+
3080
+ @keyframes nice-spin {
3081
+ to { transform: rotate(360deg); }
3082
+ }
3083
+
3084
+ .nice-a11y-ai__audit {
3085
+ padding: 20px;
3086
+ background: white;
3087
+ border-radius: 8px;
3088
+ border: 1px solid var(--nice-border-color, #e0e0e0);
3089
+ }
3090
+
3091
+ .nice-a11y-ai__audit-header {
3092
+ display: flex;
3093
+ justify-content: space-between;
3094
+ align-items: center;
3095
+ margin-bottom: 20px;
3096
+ padding-bottom: 16px;
3097
+ border-bottom: 1px solid var(--nice-border-color, #e0e0e0);
3098
+ }
3099
+
3100
+ .nice-a11y-ai__score {
3101
+ display: flex;
3102
+ flex-direction: column;
3103
+ align-items: center;
3104
+ }
3105
+
3106
+ .nice-a11y-ai__score-value {
3107
+ font-size: 48px;
3108
+ font-weight: 700;
3109
+ line-height: 1;
3110
+ }
3111
+
3112
+ .nice-a11y-ai__score-label {
3113
+ font-size: 13px;
3114
+ color: var(--nice-text-muted, #666);
3115
+ }
3116
+
3117
+ .nice-a11y-ai__summary {
3118
+ display: flex;
3119
+ gap: 16px;
3120
+ }
3121
+
3122
+ .nice-a11y-ai__summary span {
3123
+ padding: 6px 12px;
3124
+ border-radius: 6px;
3125
+ font-size: 13px;
3126
+ font-weight: 500;
3127
+ }
3128
+
3129
+ .nice-a11y-ai__summary .critical { background: #ffebee; color: #c62828; }
3130
+ .nice-a11y-ai__summary .serious { background: #fff3e0; color: #e65100; }
3131
+ .nice-a11y-ai__summary .moderate { background: #fff8e1; color: #f57f17; }
3132
+ .nice-a11y-ai__summary .minor { background: #e3f2fd; color: #1565c0; }
3133
+
3134
+ .nice-a11y-ai__issues {
3135
+ display: flex;
3136
+ flex-direction: column;
3137
+ gap: 12px;
3138
+ }
3139
+
3140
+ .nice-a11y-ai__issue {
3141
+ padding: 16px;
3142
+ border-radius: 8px;
3143
+ border-left: 4px solid;
3144
+ }
3145
+
3146
+ .nice-a11y-ai__issue-header {
3147
+ display: flex;
3148
+ align-items: center;
3149
+ gap: 8px;
3150
+ margin-bottom: 8px;
3151
+ }
3152
+
3153
+ .nice-a11y-ai__issue-title {
3154
+ font-weight: 600;
3155
+ flex: 1;
3156
+ }
3157
+
3158
+ .nice-a11y-ai__issue-wcag {
3159
+ font-size: 12px;
3160
+ padding: 2px 8px;
3161
+ background: rgba(0, 0, 0, 0.1);
3162
+ border-radius: 4px;
3163
+ }
3164
+
3165
+ .nice-a11y-ai__issue-desc {
3166
+ margin: 0 0 8px;
3167
+ font-size: 14px;
3168
+ }
3169
+
3170
+ .nice-a11y-ai__issue-element {
3171
+ display: block;
3172
+ padding: 8px;
3173
+ background: rgba(0, 0, 0, 0.05);
3174
+ border-radius: 4px;
3175
+ font-size: 12px;
3176
+ margin-bottom: 8px;
3177
+ overflow-x: auto;
3178
+ }
3179
+
3180
+ .nice-a11y-ai__issue-suggestion {
3181
+ font-size: 13px;
3182
+ color: var(--nice-success, #2e7d32);
3183
+ }
3184
+
3185
+ .nice-a11y-ai__issue-example {
3186
+ margin: 8px 0 0;
3187
+ padding: 12px;
3188
+ background: var(--nice-code-bg, #1e1e1e);
3189
+ color: var(--nice-code-color, #d4d4d4);
3190
+ border-radius: 6px;
3191
+ font-size: 12px;
3192
+ overflow-x: auto;
3193
+ }
3194
+
3195
+ .nice-a11y-ai__recommendations {
3196
+ margin-top: 20px;
3197
+ padding-top: 16px;
3198
+ border-top: 1px solid var(--nice-border-color, #e0e0e0);
3199
+ }
3200
+
3201
+ .nice-a11y-ai__recommendations h4 {
3202
+ margin: 0 0 12px;
3203
+ }
3204
+
3205
+ .nice-a11y-ai__recommendations ul {
3206
+ margin: 0;
3207
+ padding-left: 20px;
3208
+ }
3209
+
3210
+ .nice-a11y-ai__recommendations li {
3211
+ margin-bottom: 6px;
3212
+ font-size: 14px;
3213
+ }
3214
+ `})]}):e.jsx("div",{className:`nice-a11y-ai nice-a11y-ai--disabled ${n||""}`,style:s,children:e.jsx("p",{children:"AI not configured. Please provide config or wrap in NiceAIProvider."})})}const ye=[{name:"home",category:"navigation",keywords:["home","house","start","main"],svgPath:"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"},{name:"menu",category:"navigation",keywords:["menu","hamburger","nav","bars"],svgPath:"M4 6h16M4 12h16M4 18h16"},{name:"arrow-left",category:"navigation",keywords:["back","previous","left","arrow"],svgPath:"M10 19l-7-7m0 0l7-7m-7 7h18"},{name:"arrow-right",category:"navigation",keywords:["next","forward","right","arrow"],svgPath:"M14 5l7 7m0 0l-7 7m7-7H3"},{name:"chevron-down",category:"navigation",keywords:["expand","dropdown","down","chevron"],svgPath:"M19 9l-7 7-7-7"},{name:"chevron-up",category:"navigation",keywords:["collapse","up","chevron"],svgPath:"M5 15l7-7 7 7"},{name:"plus",category:"action",keywords:["add","create","new","plus"],svgPath:"M12 4v16m8-8H4"},{name:"minus",category:"action",keywords:["remove","subtract","minus"],svgPath:"M20 12H4"},{name:"x",category:"action",keywords:["close","cancel","delete","remove","x"],svgPath:"M6 18L18 6M6 6l12 12"},{name:"check",category:"action",keywords:["done","complete","success","check","tick"],svgPath:"M5 13l4 4L19 7"},{name:"edit",category:"action",keywords:["edit","modify","pencil","write"],svgPath:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"},{name:"trash",category:"action",keywords:["delete","remove","trash","bin"],svgPath:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"},{name:"search",category:"action",keywords:["search","find","magnify","lookup"],svgPath:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"},{name:"filter",category:"action",keywords:["filter","sort","funnel"],svgPath:"M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"},{name:"download",category:"action",keywords:["download","save","export"],svgPath:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"},{name:"upload",category:"action",keywords:["upload","import","send"],svgPath:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"},{name:"refresh",category:"action",keywords:["refresh","reload","sync"],svgPath:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"},{name:"copy",category:"action",keywords:["copy","duplicate","clone"],svgPath:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"},{name:"mail",category:"communication",keywords:["email","mail","message","envelope"],svgPath:"M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"},{name:"phone",category:"communication",keywords:["phone","call","telephone","contact"],svgPath:"M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"},{name:"chat",category:"communication",keywords:["chat","message","comment","bubble"],svgPath:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"},{name:"bell",category:"notification",keywords:["notification","bell","alert","alarm"],svgPath:"M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"},{name:"file",category:"file",keywords:["file","document","page"],svgPath:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"},{name:"folder",category:"file",keywords:["folder","directory","category"],svgPath:"M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"},{name:"image",category:"image",keywords:["image","photo","picture","gallery"],svgPath:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"},{name:"video",category:"av",keywords:["video","movie","film","camera"],svgPath:"M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"},{name:"user",category:"social",keywords:["user","person","account","profile"],svgPath:"M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"},{name:"users",category:"social",keywords:["users","group","team","people"],svgPath:"M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"},{name:"settings",category:"action",keywords:["settings","config","gear","cog","preferences"],svgPath:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z"},{name:"calendar",category:"business",keywords:["calendar","date","schedule","event"],svgPath:"M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"},{name:"clock",category:"business",keywords:["time","clock","schedule","hour"],svgPath:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"credit-card",category:"finance",keywords:["payment","card","credit","money"],svgPath:"M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"},{name:"chart",category:"business",keywords:["chart","graph","analytics","statistics"],svgPath:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"},{name:"lock",category:"security",keywords:["lock","secure","private","password"],svgPath:"M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"},{name:"unlock",category:"security",keywords:["unlock","open","access"],svgPath:"M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z"},{name:"shield",category:"security",keywords:["shield","security","protect","safe"],svgPath:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"},{name:"eye",category:"action",keywords:["view","show","visible","eye","visibility"],svgPath:"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"},{name:"eye-off",category:"action",keywords:["hide","invisible","hidden","eye-off"],svgPath:"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"},{name:"info",category:"alert",keywords:["info","information","help","about"],svgPath:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"warning",category:"alert",keywords:["warning","caution","alert","attention"],svgPath:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"},{name:"error",category:"alert",keywords:["error","danger","fail","problem"],svgPath:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"success",category:"alert",keywords:["success","done","complete","check-circle"],svgPath:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"},{name:"star",category:"action",keywords:["star","favorite","bookmark","rating"],svgPath:"M11.049 2.927c.3-.921 1.603-.921 1.902 0l1.519 4.674a1 1 0 00.95.69h4.915c.969 0 1.371 1.24.588 1.81l-3.976 2.888a1 1 0 00-.363 1.118l1.518 4.674c.3.922-.755 1.688-1.538 1.118l-3.976-2.888a1 1 0 00-1.176 0l-3.976 2.888c-.783.57-1.838-.197-1.538-1.118l1.518-4.674a1 1 0 00-.363-1.118l-3.976-2.888c-.784-.57-.38-1.81.588-1.81h4.914a1 1 0 00.951-.69l1.519-4.674z"},{name:"heart",category:"social",keywords:["heart","love","like","favorite"],svgPath:"M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"},{name:"share",category:"social",keywords:["share","send","forward"],svgPath:"M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z"},{name:"link",category:"action",keywords:["link","url","chain","hyperlink"],svgPath:"M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"},{name:"external-link",category:"action",keywords:["external","open","new-window"],svgPath:"M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"}];function wt(a={}){const{config:t,defaultLibrary:i="lucide",defaultStyle:r="outline",maxSuggestions:n=10,onSuggestion:s,onError:p}=a,o=X(),[g,f]=c.useState(!1),[j,w]=c.useState(null),N=c.useRef(null),S=t||(o==null?void 0:o.config),$=c.useCallback(C=>{const m=C.toLowerCase(),_=m.split(/\s+/);return ye.map(b=>{let u=0;return b.name===m?u+=100:b.name.includes(m)&&(u+=50),_.forEach(v=>{b.keywords.forEach(A=>{A===v?u+=30:(A.includes(v)||v.includes(A))&&(u+=15)})}),b.category===m&&(u+=20),{id:`icon_${b.name}`,name:b.name,displayName:b.name.replace(/-/g," ").replace(/\b\w/g,v=>v.toUpperCase()),category:b.category,style:r,library:i,relevanceScore:u,keywords:b.keywords,svgPath:b.svgPath}}).filter(b=>b.relevanceScore>0).sort((b,u)=>u.relevanceScore-b.relevanceScore).slice(0,n)},[i,r,n]),k=c.useCallback(async(C,m)=>{var u,v,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=m?`
3215
+ Context:
3216
+ - Component type: ${m.componentType||"any"}
3217
+ - Purpose: ${m.purpose||"general"}
3218
+ - Related icons: ${((v=m.relatedIcons)==null?void 0:v.join(", "))||"none"}
3219
+ - Theme: ${m.theme||"light"}
3220
+ - Preferred style: ${m.preferredStyle||r}
3221
+ - Preferred library: ${m.preferredLibrary||i}`:"",D=(((R=(A=(await l.chat({messages:[{role:"system",content:`You are an icon recommendation expert. Suggest icons based on user query.
3222
+ Return JSON array of 5-10 icon suggestions:
3223
+ [{
3224
+ "name": "icon-name",
3225
+ "displayName": "Icon Name",
3226
+ "category": "action|alert|navigation|etc",
3227
+ "relevanceScore": 85,
3228
+ "keywords": ["keyword1", "keyword2"],
3229
+ "usage": "Brief usage description"
3230
+ }]
3231
+
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((B,q)=>({id:B.id||`ai_icon_${q}`,name:B.name||"unknown",displayName:B.displayName||B.name||"Unknown",category:B.category||"action",style:(m==null?void 0:m.preferredStyle)||r,library:(m==null?void 0:m.preferredLibrary)||i,relevanceScore:B.relevanceScore||50,keywords:B.keywords||[],usage:B.usage}))}catch{}const H=Qi(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),p==null||p(x),M}finally{f(!1)}},[S,i,r,n,$,s,p]),P=c.useCallback(C=>ye.filter(m=>m.category===C).map(m=>({id:`icon_${m.name}`,name:m.name,displayName:m.name.replace(/-/g," ").replace(/\b\w/g,_=>_.toUpperCase()),category:m.category,style:r,library:i,relevanceScore:100,keywords:m.keywords,svgPath:m.svgPath})),[i,r]),h=c.useMemo(()=>{const C=new Set;return ye.forEach(m=>C.add(m.category)),Array.from(C)},[]),d=c.useCallback(()=>{w(null)},[]),y=c.useCallback(()=>{var C;(C=N.current)==null||C.abort(),f(!1)},[]);return c.useEffect(()=>()=>{var C;(C=N.current)==null||C.abort()},[]),{suggestIcons:k,localSearch:$,getByCategory:P,categories:h,loading:g,lastResult:j,clearResults:d,abort:y,isConfigured:!!S}}function Qi(a,t,i){const r=new Set,n=[];for(const s of a)r.has(s.name)||(r.add(s.name),n.push(s));for(const s of t)!r.has(s.name)&&n.length<i&&(r.add(s.name),n.push(s));return n.slice(0,i)}function Zi({config:a,defaultLibrary:t="lucide",defaultStyle:i="outline",maxSuggestions:r=10,onSelect:n,showCategories:s=!0,showPreview:p=!0,className:o,style:g}){const[f,j]=c.useState(""),[w,N]=c.useState(null),[S,$]=c.useState(null),{suggestIcons:k,getByCategory:P,categories:h,loading:d,lastResult:y}=wt({config:a,defaultLibrary:t,defaultStyle:i,maxSuggestions:r}),C=async()=>{f.trim()&&(N(null),await k(f))},m=v=>{v.key==="Enter"&&C()},_=v=>{w===v?N(null):(N(v),j(""))},b=v=>{$(v),n==null||n(v)},u=w?P(w):(y==null?void 0:y.suggestions)||[];return e.jsxs("div",{className:`nice-icon-ai ${o||""}`,style:g,children:[e.jsxs("div",{className:"nice-icon-ai__search",children:[e.jsx("input",{type:"text",value:f,onChange:v=>j(v.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: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(v=>e.jsx("button",{type:"button",className:`nice-icon-ai__category ${w===v?"nice-icon-ai__category--selected":""}`,onClick:()=>_(v),children:v},v))}),u.length>0&&e.jsx("div",{className:"nice-icon-ai__results",children:u.map(v=>e.jsxs("button",{type:"button",className:`nice-icon-ai__icon ${(S==null?void 0:S.id)===v.id?"nice-icon-ai__icon--selected":""}`,onClick:()=>b(v),title:v.displayName,children:[e.jsx(De,{icon:v}),e.jsx("span",{className:"nice-icon-ai__icon-name",children:v.displayName})]},v.id))}),p&&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(v=>e.jsx("span",{className:"nice-icon-ai__keyword",children:v},v))}),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
+ .nice-icon-ai {
3234
+ font-family: var(--nice-font-family, system-ui, sans-serif);
3235
+ }
3236
+
3237
+ .nice-icon-ai__search {
3238
+ display: flex;
3239
+ gap: 8px;
3240
+ margin-bottom: 16px;
3241
+ }
3242
+
3243
+ .nice-icon-ai__input {
3244
+ flex: 1;
3245
+ padding: 12px 16px;
3246
+ border: 1px solid var(--nice-border-color, #e0e0e0);
3247
+ border-radius: 8px;
3248
+ font-size: 14px;
3249
+ }
3250
+
3251
+ .nice-icon-ai__input:focus {
3252
+ outline: none;
3253
+ border-color: var(--nice-primary, #0066cc);
3254
+ }
3255
+
3256
+ .nice-icon-ai__search-btn {
3257
+ padding: 12px 20px;
3258
+ background: var(--nice-primary, #0066cc);
3259
+ color: white;
3260
+ border: none;
3261
+ border-radius: 8px;
3262
+ cursor: pointer;
3263
+ font-size: 16px;
3264
+ }
3265
+
3266
+ .nice-icon-ai__search-btn:disabled {
3267
+ opacity: 0.5;
3268
+ }
3269
+
3270
+ .nice-icon-ai__spinner {
3271
+ display: inline-block;
3272
+ width: 16px;
3273
+ height: 16px;
3274
+ border: 2px solid rgba(255, 255, 255, 0.3);
3275
+ border-top-color: white;
3276
+ border-radius: 50%;
3277
+ animation: nice-spin 0.8s linear infinite;
3278
+ }
3279
+
3280
+ @keyframes nice-spin {
3281
+ to { transform: rotate(360deg); }
3282
+ }
3283
+
3284
+ .nice-icon-ai__categories {
3285
+ display: flex;
3286
+ flex-wrap: wrap;
3287
+ gap: 8px;
3288
+ margin-bottom: 16px;
3289
+ }
3290
+
3291
+ .nice-icon-ai__category {
3292
+ padding: 6px 12px;
3293
+ border: 1px solid var(--nice-border-color, #e0e0e0);
3294
+ border-radius: 20px;
3295
+ background: white;
3296
+ font-size: 12px;
3297
+ cursor: pointer;
3298
+ text-transform: capitalize;
3299
+ transition: all 0.2s;
3300
+ }
3301
+
3302
+ .nice-icon-ai__category:hover {
3303
+ border-color: var(--nice-primary, #0066cc);
3304
+ }
3305
+
3306
+ .nice-icon-ai__category--selected {
3307
+ background: var(--nice-primary, #0066cc);
3308
+ color: white;
3309
+ border-color: var(--nice-primary, #0066cc);
3310
+ }
3311
+
3312
+ .nice-icon-ai__results {
3313
+ display: grid;
3314
+ grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
3315
+ gap: 12px;
3316
+ margin-bottom: 20px;
3317
+ }
3318
+
3319
+ .nice-icon-ai__icon {
3320
+ display: flex;
3321
+ flex-direction: column;
3322
+ align-items: center;
3323
+ gap: 8px;
3324
+ padding: 16px 8px;
3325
+ border: 1px solid var(--nice-border-color, #e0e0e0);
3326
+ border-radius: 8px;
3327
+ background: white;
3328
+ cursor: pointer;
3329
+ transition: all 0.2s;
3330
+ }
3331
+
3332
+ .nice-icon-ai__icon:hover {
3333
+ border-color: var(--nice-primary, #0066cc);
3334
+ transform: translateY(-2px);
3335
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
3336
+ }
3337
+
3338
+ .nice-icon-ai__icon--selected {
3339
+ border-color: var(--nice-primary, #0066cc);
3340
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.05));
3341
+ }
3342
+
3343
+ .nice-icon-ai__icon-name {
3344
+ font-size: 11px;
3345
+ color: var(--nice-text-muted, #666);
3346
+ text-align: center;
3347
+ line-height: 1.3;
3348
+ }
3349
+
3350
+ .nice-icon-ai__preview {
3351
+ display: flex;
3352
+ gap: 24px;
3353
+ padding: 24px;
3354
+ background: var(--nice-bg-subtle, #f8f9fa);
3355
+ border-radius: 12px;
3356
+ margin-top: 20px;
3357
+ }
3358
+
3359
+ .nice-icon-ai__preview-icon {
3360
+ display: flex;
3361
+ align-items: center;
3362
+ justify-content: center;
3363
+ width: 100px;
3364
+ height: 100px;
3365
+ background: white;
3366
+ border-radius: 12px;
3367
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
3368
+ }
3369
+
3370
+ .nice-icon-ai__preview-info {
3371
+ flex: 1;
3372
+ }
3373
+
3374
+ .nice-icon-ai__preview-name {
3375
+ font-size: 20px;
3376
+ font-weight: 600;
3377
+ margin-bottom: 8px;
3378
+ }
3379
+
3380
+ .nice-icon-ai__preview-details {
3381
+ display: flex;
3382
+ gap: 16px;
3383
+ font-size: 13px;
3384
+ color: var(--nice-text-muted, #666);
3385
+ margin-bottom: 12px;
3386
+ }
3387
+
3388
+ .nice-icon-ai__preview-keywords {
3389
+ display: flex;
3390
+ flex-wrap: wrap;
3391
+ gap: 6px;
3392
+ margin-bottom: 12px;
3393
+ }
3394
+
3395
+ .nice-icon-ai__keyword {
3396
+ padding: 3px 8px;
3397
+ background: var(--nice-primary-light, rgba(0, 102, 204, 0.1));
3398
+ border-radius: 4px;
3399
+ font-size: 11px;
3400
+ color: var(--nice-primary, #0066cc);
3401
+ }
3402
+
3403
+ .nice-icon-ai__preview-usage {
3404
+ font-size: 13px;
3405
+ color: var(--nice-text-muted, #666);
3406
+ font-style: italic;
3407
+ margin-bottom: 12px;
3408
+ }
3409
+
3410
+ .nice-icon-ai__preview-actions {
3411
+ display: flex;
3412
+ gap: 8px;
3413
+ }
3414
+
3415
+ .nice-icon-ai__preview-actions button {
3416
+ padding: 8px 16px;
3417
+ border: 1px solid var(--nice-border-color, #e0e0e0);
3418
+ border-radius: 6px;
3419
+ background: white;
3420
+ font-size: 12px;
3421
+ cursor: pointer;
3422
+ }
3423
+
3424
+ .nice-icon-ai__preview-actions button:first-child {
3425
+ background: var(--nice-primary, #0066cc);
3426
+ color: white;
3427
+ border: none;
3428
+ }
3429
+ `})]})}function De({icon:a,size:t=32}){return a.svgPath?e.jsx("svg",{viewBox:"0 0 24 24",width:t,height:t,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:a.svgPath})}):e.jsx("div",{style:{width:t,height:t,display:"flex",alignItems:"center",justifyContent:"center",background:"#f0f0f0",borderRadius:6,fontSize:t*.5,fontWeight:600,color:"#666"},children:a.name.charAt(0).toUpperCase()})}exports.ACCESSIBILITY_CHECKER_TEMPLATE=ve;exports.AnthropicProvider=at;exports.AzureOpenAIProvider=rt;exports.CHART_CONFIG_TEMPLATE=oe;exports.CODE_COMPLETION_TEMPLATE=ce;exports.CostTracker=ct;exports.DATA_GRID_FILTER_TEMPLATE=re;exports.DATA_GRID_SORT_TEMPLATE=ne;exports.FORM_BUILDER_TEMPLATE=se;exports.GroqProvider=st;exports.InMemoryCostStorage=Re;exports.LocalStorageCostStorage=ot;exports.NiceAIHintBubble=ke;exports.NiceAIProvider=jt;exports.NiceAccessibilityAI=Xi;exports.NiceChartAI=yi;exports.NiceCodeEditorAI=Ci;exports.NiceDataGridAI=pi;exports.NiceDataLabeler=ii;exports.NiceFormBuilderAI=gi;exports.NiceIconSuggestorAI=Zi;exports.NiceLayoutAI=Wi;exports.NiceMLStudio=ei;exports.NiceModelInference=ri;exports.NiceReportBuilderAI=Oi;exports.NiceThemeGeneratorAI=Bi;exports.NiceWorkflowDesignerAI=Mi;exports.OllamaProvider=nt;exports.OpenAIProvider=it;exports.PROMPT_TEMPLATES=he;exports.REPORT_LAYOUT_TEMPLATE=de;exports.RateLimiter=Fe;exports.ResilientLLMClient=lt;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=At;exports.buildCodeEditorContext=We;exports.buildColorPickerContext=Ae;exports.buildDataGridContext=Tt;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=et;exports.buildSelectContext=Se;exports.buildSlideDesignContext=tt;exports.buildTextInputContext=Ne;exports.buildValidationContext=He;exports.colorControlContext=Qt;exports.compileTemplate=Z;exports.createLLMProvider=te;exports.createProviderFromConfig=G;exports.createResilientClient=dt;exports.createResilientClientWithDefaults=di;exports.dateControlContext=Xt;exports.getTemplate=ni;exports.getTemplatesByCategory=si;exports.listTemplates=oi;exports.numberControlContext=Kt;exports.parseJSONResponse=qe;exports.parseSSEStream=Je;exports.selectControlContext=Yt;exports.textControlContext=Vt;exports.useAI3DHint=Ft;exports.useAIAudioHint=Dt;exports.useAICodeHint=Ot;exports.useAIColorHint=It;exports.useAIContext=X;exports.useAIDateHint=$t;exports.useAIDiagramLayout=Ut;exports.useAIFormFill=Lt;exports.useAIGraphicsHint=Bt;exports.useAIHtmlHint=Et;exports.useAIIconSearch=Jt;exports.useAINpcHint=qt;exports.useAINumberHint=Mt;exports.useAIPresentationGenerate=Ht;exports.useAISelectHint=Pt;exports.useAISlideDesign=Wt;exports.useAITextHint=Rt;exports.useAIValidation=zt;exports.useAccessibilityAI=_t;exports.useChartAI=pt;exports.useCodeEditorAI=ht;exports.useCostTracker=ci;exports.useDataGridAI=ut;exports.useFormBuilderAI=mt;exports.useIconSuggestorAI=wt;exports.useLayoutAI=yt;exports.useNiceAIHint=V;exports.useReportBuilderAI=ft;exports.useThemeGeneratorAI=bt;exports.useWorkflowDesignerAI=gt;exports.withAIHint=Gt;