@nice2dev/ui-math 1.0.11 → 1.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var B=Object.defineProperty;var T=(e,t,r)=>t in e?B(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var k=(e,t,r)=>T(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const jsxRuntime=require("react/jsx-runtime"),react=require("react"),MATH_SYMBOLS=[{name:"alpha",latex:"\\alpha",category:"greek",preview:"α"},{name:"beta",latex:"\\beta",category:"greek",preview:"β"},{name:"gamma",latex:"\\gamma",category:"greek",preview:"γ"},{name:"delta",latex:"\\delta",category:"greek",preview:"δ"},{name:"epsilon",latex:"\\epsilon",category:"greek",preview:"ε"},{name:"zeta",latex:"\\zeta",category:"greek",preview:"ζ"},{name:"eta",latex:"\\eta",category:"greek",preview:"η"},{name:"theta",latex:"\\theta",category:"greek",preview:"θ"},{name:"iota",latex:"\\iota",category:"greek",preview:"ι"},{name:"kappa",latex:"\\kappa",category:"greek",preview:"κ"},{name:"lambda",latex:"\\lambda",category:"greek",preview:"λ"},{name:"mu",latex:"\\mu",category:"greek",preview:"μ"},{name:"nu",latex:"\\nu",category:"greek",preview:"ν"},{name:"xi",latex:"\\xi",category:"greek",preview:"ξ"},{name:"pi",latex:"\\pi",category:"greek",preview:"π"},{name:"rho",latex:"\\rho",category:"greek",preview:"ρ"},{name:"sigma",latex:"\\sigma",category:"greek",preview:"σ"},{name:"tau",latex:"\\tau",category:"greek",preview:"τ"},{name:"upsilon",latex:"\\upsilon",category:"greek",preview:"υ"},{name:"phi",latex:"\\phi",category:"greek",preview:"φ"},{name:"chi",latex:"\\chi",category:"greek",preview:"χ"},{name:"psi",latex:"\\psi",category:"greek",preview:"ψ"},{name:"omega",latex:"\\omega",category:"greek",preview:"ω"},{name:"Gamma",latex:"\\Gamma",category:"greek",preview:"Γ"},{name:"Delta",latex:"\\Delta",category:"greek",preview:"Δ"},{name:"Theta",latex:"\\Theta",category:"greek",preview:"Θ"},{name:"Lambda",latex:"\\Lambda",category:"greek",preview:"Λ"},{name:"Xi",latex:"\\Xi",category:"greek",preview:"Ξ"},{name:"Pi",latex:"\\Pi",category:"greek",preview:"Π"},{name:"Sigma",latex:"\\Sigma",category:"greek",preview:"Σ"},{name:"Phi",latex:"\\Phi",category:"greek",preview:"Φ"},{name:"Psi",latex:"\\Psi",category:"greek",preview:"Ψ"},{name:"Omega",latex:"\\Omega",category:"greek",preview:"Ω"},{name:"plus/minus",latex:"\\pm",category:"operators",preview:"±"},{name:"minus/plus",latex:"\\mp",category:"operators",preview:"∓"},{name:"times",latex:"\\times",category:"operators",preview:"×"},{name:"divide",latex:"\\div",category:"operators",preview:"÷"},{name:"cdot",latex:"\\cdot",category:"operators",preview:"·"},{name:"star",latex:"\\star",category:"operators",preview:"⋆"},{name:"circle",latex:"\\circ",category:"operators",preview:"∘"},{name:"bullet",latex:"\\bullet",category:"operators",preview:"•"},{name:"oplus",latex:"\\oplus",category:"operators",preview:"⊕"},{name:"otimes",latex:"\\otimes",category:"operators",preview:"⊗"},{name:"odot",latex:"\\odot",category:"operators",preview:"⊙"},{name:"less than",latex:"<",category:"relations",preview:"<"},{name:"greater than",latex:">",category:"relations",preview:">"},{name:"less or equal",latex:"\\leq",category:"relations",preview:"≤"},{name:"greater or equal",latex:"\\geq",category:"relations",preview:"≥"},{name:"not equal",latex:"\\neq",category:"relations",preview:"≠"},{name:"approximately",latex:"\\approx",category:"relations",preview:"≈"},{name:"equivalent",latex:"\\equiv",category:"relations",preview:"≡"},{name:"similar",latex:"\\sim",category:"relations",preview:"∼"},{name:"proportional",latex:"\\propto",category:"relations",preview:"∝"},{name:"perpendicular",latex:"\\perp",category:"relations",preview:"⊥"},{name:"parallel",latex:"\\parallel",category:"relations",preview:"∥"},{name:"right arrow",latex:"\\rightarrow",category:"arrows",preview:"→"},{name:"left arrow",latex:"\\leftarrow",category:"arrows",preview:"←"},{name:"double right",latex:"\\Rightarrow",category:"arrows",preview:"⇒"},{name:"double left",latex:"\\Leftarrow",category:"arrows",preview:"⇐"},{name:"iff",latex:"\\Leftrightarrow",category:"arrows",preview:"⇔"},{name:"up arrow",latex:"\\uparrow",category:"arrows",preview:"↑"},{name:"down arrow",latex:"\\downarrow",category:"arrows",preview:"↓"},{name:"maps to",latex:"\\mapsto",category:"arrows",preview:"↦"},{name:"sine",latex:"\\sin",category:"functions",preview:"sin"},{name:"cosine",latex:"\\cos",category:"functions",preview:"cos"},{name:"tangent",latex:"\\tan",category:"functions",preview:"tan"},{name:"cotangent",latex:"\\cot",category:"functions",preview:"cot"},{name:"arcsine",latex:"\\arcsin",category:"functions",preview:"arcsin"},{name:"arccosine",latex:"\\arccos",category:"functions",preview:"arccos"},{name:"arctangent",latex:"\\arctan",category:"functions",preview:"arctan"},{name:"logarithm",latex:"\\log",category:"functions",preview:"log"},{name:"natural log",latex:"\\ln",category:"functions",preview:"ln"},{name:"exponential",latex:"\\exp",category:"functions",preview:"exp"},{name:"limit",latex:"\\lim",category:"functions",preview:"lim"},{name:"supremum",latex:"\\sup",category:"functions",preview:"sup"},{name:"infimum",latex:"\\inf",category:"functions",preview:"inf"},{name:"maximum",latex:"\\max",category:"functions",preview:"max"},{name:"minimum",latex:"\\min",category:"functions",preview:"min"},{name:"hat",latex:"\\hat{x}",category:"accents",preview:"x̂"},{name:"bar",latex:"\\bar{x}",category:"accents",preview:"x̄"},{name:"vector",latex:"\\vec{x}",category:"accents",preview:"x⃗"},{name:"dot",latex:"\\dot{x}",category:"accents",preview:"ẋ"},{name:"double dot",latex:"\\ddot{x}",category:"accents",preview:"ẍ"},{name:"tilde",latex:"\\tilde{x}",category:"accents",preview:"x̃"},{name:"parentheses",latex:"\\left( \\right)",category:"delimiters",preview:"( )"},{name:"brackets",latex:"\\left[ \\right]",category:"delimiters",preview:"[ ]"},{name:"braces",latex:"\\left\\{ \\right\\}",category:"delimiters",preview:"{ }"},{name:"angle brackets",latex:"\\left\\langle \\right\\rangle",category:"delimiters",preview:"⟨ ⟩"},{name:"ceiling",latex:"\\left\\lceil \\right\\rceil",category:"delimiters",preview:"⌈ ⌉"},{name:"floor",latex:"\\left\\lfloor \\right\\rfloor",category:"delimiters",preview:"⌊ ⌋"},{name:"absolute",latex:"\\left| \\right|",category:"delimiters",preview:"| |"},{name:"norm",latex:"\\left\\| \\right\\|",category:"delimiters",preview:"‖ ‖"},{name:"element of",latex:"\\in",category:"sets",preview:"∈"},{name:"not element",latex:"\\notin",category:"sets",preview:"∉"},{name:"contains",latex:"\\ni",category:"sets",preview:"∋"},{name:"subset",latex:"\\subset",category:"sets",preview:"⊂"},{name:"superset",latex:"\\supset",category:"sets",preview:"⊃"},{name:"subset or equal",latex:"\\subseteq",category:"sets",preview:"⊆"},{name:"union",latex:"\\cup",category:"sets",preview:"∪"},{name:"intersection",latex:"\\cap",category:"sets",preview:"∩"},{name:"set minus",latex:"\\setminus",category:"sets",preview:"∖"},{name:"empty set",latex:"\\emptyset",category:"sets",preview:"∅"},{name:"naturals",latex:"\\mathbb{N}",category:"sets",preview:"ℕ"},{name:"integers",latex:"\\mathbb{Z}",category:"sets",preview:"ℤ"},{name:"rationals",latex:"\\mathbb{Q}",category:"sets",preview:"ℚ"},{name:"reals",latex:"\\mathbb{R}",category:"sets",preview:"ℝ"},{name:"complex",latex:"\\mathbb{C}",category:"sets",preview:"ℂ"},{name:"for all",latex:"\\forall",category:"logic",preview:"∀"},{name:"exists",latex:"\\exists",category:"logic",preview:"∃"},{name:"not exists",latex:"\\nexists",category:"logic",preview:"∄"},{name:"and",latex:"\\land",category:"logic",preview:"∧"},{name:"or",latex:"\\lor",category:"logic",preview:"∨"},{name:"not",latex:"\\neg",category:"logic",preview:"¬"},{name:"therefore",latex:"\\therefore",category:"logic",preview:"∴"},{name:"because",latex:"\\because",category:"logic",preview:"∵"},{name:"integral",latex:"\\int",category:"calculus",preview:"∫"},{name:"double integral",latex:"\\iint",category:"calculus",preview:"∬"},{name:"triple integral",latex:"\\iiint",category:"calculus",preview:"∭"},{name:"contour integral",latex:"\\oint",category:"calculus",preview:"∮"},{name:"partial",latex:"\\partial",category:"calculus",preview:"∂"},{name:"nabla/gradient",latex:"\\nabla",category:"calculus",preview:"∇"},{name:"summation",latex:"\\sum",category:"calculus",preview:"Σ"},{name:"product",latex:"\\prod",category:"calculus",preview:"Π"},{name:"infinity",latex:"\\infty",category:"calculus",preview:"∞"},{name:"matrix",latex:"\\begin{pmatrix} a & b \\\\ c & d \\end{pmatrix}",category:"matrices",preview:"[ ]"},{name:"determinant",latex:"\\begin{vmatrix} a & b \\\\ c & d \\end{vmatrix}",category:"matrices",preview:"| |"},{name:"bracket matrix",latex:"\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}",category:"matrices",preview:"[[ ]]"},{name:"cases",latex:"\\begin{cases} a & \\text{if } x > 0 \\\\ b & \\text{otherwise} \\end{cases}",category:"matrices",preview:"{ }"}];function getSymbolsByCategory(e){return MATH_SYMBOLS.filter(t=>t.category===e)}const EQUATION_TEMPLATES=[{name:"Fraction",latex:"\\frac{a}{b}",category:"basic"},{name:"Square root",latex:"\\sqrt{x}",category:"basic"},{name:"Nth root",latex:"\\sqrt[n]{x}",category:"basic"},{name:"Power",latex:"x^{n}",category:"basic"},{name:"Subscript",latex:"x_{n}",category:"basic"},{name:"Both",latex:"x_{i}^{n}",category:"basic"},{name:"Derivative",latex:"\\frac{d}{dx}f(x)",category:"calculus"},{name:"Partial derivative",latex:"\\frac{\\partial f}{\\partial x}",category:"calculus"},{name:"Definite integral",latex:"\\int_{a}^{b} f(x)\\,dx",category:"calculus"},{name:"Indefinite integral",latex:"\\int f(x)\\,dx",category:"calculus"},{name:"Limit",latex:"\\lim_{x \\to a} f(x)",category:"calculus"},{name:"Summation",latex:"\\sum_{i=1}^{n} a_i",category:"calculus"},{name:"Product",latex:"\\prod_{i=1}^{n} a_i",category:"calculus"},{name:"Quadratic formula",latex:"x = \\frac{-b \\pm \\sqrt{b^2-4ac}}{2a}",category:"algebra"},{name:"Binomial",latex:"\\binom{n}{k} = \\frac{n!}{k!(n-k)!}",category:"algebra"},{name:"System of equations",latex:"\\begin{cases} ax + by = c \\\\ dx + ey = f \\end{cases}",category:"algebra"},{name:"Pythagorean",latex:"a^2 + b^2 = c^2",category:"geometry"},{name:"Circle area",latex:"A = \\pi r^2",category:"geometry"},{name:"Sphere volume",latex:"V = \\frac{4}{3}\\pi r^3",category:"geometry"},{name:"Euler's identity",latex:"e^{i\\pi} + 1 = 0",category:"geometry"},{name:"Mean",latex:"\\bar{x} = \\frac{1}{n}\\sum_{i=1}^{n} x_i",category:"statistics"},{name:"Variance",latex:"\\sigma^2 = \\frac{1}{n}\\sum_{i=1}^{n}(x_i - \\bar{x})^2",category:"statistics"},{name:"Normal distribution",latex:"f(x) = \\frac{1}{\\sigma\\sqrt{2\\pi}}e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}",category:"statistics"},{name:"Einstein mass-energy",latex:"E = mc^2",category:"physics"},{name:"Newton's second law",latex:"F = ma",category:"physics"},{name:"Schrödinger equation",latex:"i\\hbar\\frac{\\partial}{\\partial t}\\Psi = \\hat{H}\\Psi",category:"physics"},{name:"Maxwell's equations",latex:"\\nabla \\cdot \\vec{E} = \\frac{\\rho}{\\epsilon_0}",category:"physics"}];class MathEditorService{constructor(t={}){k(this,"equations",new Map);k(this,"config");k(this,"nextNumber");this.config={enableNumbering:t.enableNumbering??!0,startNumber:t.startNumber??1,renderDelay:t.renderDelay??100},this.nextNumber=this.config.startNumber}createEquation(t,r){const n={id:this.generateId(),latex:t,label:r,number:this.config.enableNumbering?this.nextNumber++:void 0,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return this.equations.set(n.id,n),n}updateEquation(t,r,n){const a=this.equations.get(t);if(!a)throw new Error(`Equation not found: ${t}`);const s={...a,latex:r,label:n??a.label,updatedAt:new Date().toISOString()};return this.equations.set(t,s),s}deleteEquation(t){this.equations.delete(t)}getEquation(t){return this.equations.get(t)}listEquations(){return Array.from(this.equations.values()).sort((t,r)=>new Date(t.createdAt).getTime()-new Date(r.createdAt).getTime())}exportToLatex(){const t=["\\documentclass{article}","\\usepackage{amsmath}","\\usepackage{amssymb}","","\\begin{document}",""];for(const r of this.listEquations())r.number!==void 0?(t.push("\\begin{equation}"),r.label&&t.push(`\\label{${r.label}}`),t.push(r.latex),t.push("\\end{equation}")):(t.push("\\["),t.push(r.latex),t.push("\\]")),t.push("");return t.push("\\end{document}"),t.join(`
2
- `)}parseLatex(t){const r=[],n=/\\\[([\s\S]*?)\\\]/g;let a;for(;(a=n.exec(t))!==null;)r.push(this.createEquation(a[1].trim()));const s=/\\begin\{equation\}([\s\S]*?)\\end\{equation\}/g;for(;(a=s.exec(t))!==null;){const o=a[1].match(/\\label\{([^}]+)\}/),c=a[1].replace(/\\label\{[^}]+\}/,"").trim();r.push(this.createEquation(c,o==null?void 0:o[1]))}return r}generateId(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}}function createMathEditorService(e){return new MathEditorService(e)}async function recognizeHandwriting(e){return await new Promise(r=>setTimeout(r,500)),{latex:e.reduce((r,n)=>r+n.points.length,0)>50?"\\sqrt{x^2 + y^2}":"x",confidence:.85,alternatives:["x","X","\\times"]}}const MathEditorContext=react.createContext(null);function useMathEditor(){const e=react.useContext(MathEditorContext);if(!e)throw new Error("useMathEditor must be used within MathEditorProvider");return e}const styles$3={container:{display:"flex",flexDirection:"column",height:"100%",fontFamily:"'Inter', sans-serif",fontSize:"14px"},toolbar:{display:"flex",gap:"8px",padding:"8px",borderBottom:"1px solid #e0e0e0",backgroundColor:"#fafafa",flexWrap:"wrap",alignItems:"center"},main:{display:"flex",flex:1,overflow:"hidden"},sidebar:{width:"200px",borderRight:"1px solid #e0e0e0",overflow:"auto",backgroundColor:"#f5f5f5"},editor:{flex:1,display:"flex",flexDirection:"column",padding:"16px",overflow:"auto"},input:{width:"100%",minHeight:"100px",padding:"12px",fontFamily:"'JetBrains Mono', monospace",fontSize:"14px",border:"1px solid #ddd",borderRadius:"4px",resize:"vertical"},preview:{marginTop:"16px",padding:"20px",backgroundColor:"#fff",border:"1px solid #e0e0e0",borderRadius:"4px",minHeight:"60px",fontSize:"20px",textAlign:"center"},button:{padding:"6px 12px",backgroundColor:"#1976d2",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"13px"},symbolGrid:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:"4px",padding:"8px"},symbolButton:{padding:"8px",border:"1px solid #ddd",borderRadius:"4px",backgroundColor:"#fff",cursor:"pointer",fontSize:"16px",textAlign:"center"},categoryHeader:{padding:"8px 12px",backgroundColor:"#e0e0e0",fontWeight:600,fontSize:"12px",textTransform:"uppercase"},canvas:{width:"100%",height:"200px",border:"1px solid #ddd",borderRadius:"4px",backgroundColor:"#fff",cursor:"crosshair"}};function NiceMathEditor({service:e,initialLatex:t="",onChange:r,className:n,style:a}){const[s,o]=react.useState(t),[c,l]=react.useState("input"),i=react.useRef(null),p=react.useCallback(g=>{o(g),r==null||r(g)},[r]),d=react.useCallback(g=>{const m=i.current;if(!m){p(s+g);return}const y=m.selectionStart,x=m.selectionEnd,u=s.slice(0,y)+g+s.slice(x);p(u),setTimeout(()=>{m.focus(),m.selectionStart=m.selectionEnd=y+g.length},0)},[s,p]),h=react.useCallback(g=>{d(g.latex)},[d]),b={service:e,latex:s,setLatex:p,insertSymbol:d,insertTemplate:h,mode:c,setMode:l};return jsxRuntime.jsx(MathEditorContext.Provider,{value:b,children:jsxRuntime.jsxs("div",{className:n,style:{...styles$3.container,...a},children:[jsxRuntime.jsx(Toolbar$1,{}),jsxRuntime.jsxs("div",{style:styles$3.main,children:[jsxRuntime.jsx(SymbolPalette,{}),jsxRuntime.jsx("div",{style:styles$3.editor,children:c==="input"?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("textarea",{ref:i,value:s,onChange:g=>p(g.target.value),placeholder:"Enter LaTeX equation...",style:styles$3.input}),jsxRuntime.jsx(LatexPreview,{latex:s})]}):jsxRuntime.jsx(HandwritingCanvas,{})})]})]})})}function Toolbar$1(){const{mode:e,setMode:t,latex:r,insertTemplate:n}=useMathEditor(),[a,s]=react.useState(!1);return jsxRuntime.jsxs("div",{style:styles$3.toolbar,children:[jsxRuntime.jsx("button",{onClick:()=>t("input"),style:{...styles$3.button,backgroundColor:e==="input"?"#1976d2":"#9e9e9e"},children:"⌨️ LaTeX Input"}),jsxRuntime.jsx("button",{onClick:()=>t("handwriting"),style:{...styles$3.button,backgroundColor:e==="handwriting"?"#1976d2":"#9e9e9e"},children:"✏️ Handwriting"}),jsxRuntime.jsx("div",{style:{borderLeft:"1px solid #ccc",height:"24px",margin:"0 8px"}}),jsxRuntime.jsxs("div",{style:{position:"relative"},children:[jsxRuntime.jsx("button",{onClick:()=>s(!a),style:styles$3.button,children:"📐 Templates ▾"}),a&&jsxRuntime.jsx("div",{style:{position:"absolute",top:"100%",left:0,backgroundColor:"#fff",border:"1px solid #ddd",borderRadius:"4px",boxShadow:"0 2px 8px rgba(0,0,0,0.15)",zIndex:100,width:"300px",maxHeight:"400px",overflow:"auto"},children:["basic","calculus","algebra","geometry","statistics","physics"].map(o=>jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("div",{style:styles$3.categoryHeader,children:o}),EQUATION_TEMPLATES.filter(c=>c.category===o).map(c=>jsxRuntime.jsxs("div",{onClick:()=>{n(c),s(!1)},style:{padding:"8px 12px",cursor:"pointer",borderBottom:"1px solid #eee"},onMouseOver:l=>l.target.style.backgroundColor="#f5f5f5",onMouseOut:l=>l.target.style.backgroundColor="transparent",children:[jsxRuntime.jsx("div",{style:{fontWeight:500},children:c.name}),jsxRuntime.jsxs("div",{style:{fontSize:"12px",color:"#666",fontFamily:"monospace"},children:[c.latex.substring(0,40),c.latex.length>40?"...":""]})]},c.name))]},o))})]}),jsxRuntime.jsx("div",{style:{flex:1}}),jsxRuntime.jsx("button",{onClick:()=>navigator.clipboard.writeText(r),style:{...styles$3.button,backgroundColor:"#4caf50"},children:"📋 Copy LaTeX"})]})}function SymbolPalette(){const{insertSymbol:e}=useMathEditor(),[t,r]=react.useState("greek"),n=["greek","operators","relations","arrows","functions","accents","delimiters","sets","logic","calculus","matrices"],a=getSymbolsByCategory(t);return jsxRuntime.jsxs("div",{style:styles$3.sidebar,children:[jsxRuntime.jsx("div",{style:{display:"flex",flexWrap:"wrap",padding:"8px",gap:"4px"},children:n.map(s=>jsxRuntime.jsx("button",{onClick:()=>r(s),style:{padding:"4px 8px",fontSize:"11px",border:"1px solid #ddd",borderRadius:"4px",backgroundColor:t===s?"#1976d2":"#fff",color:t===s?"#fff":"#333",cursor:"pointer"},children:s},s))}),jsxRuntime.jsx("div",{style:styles$3.symbolGrid,children:a.map(s=>jsxRuntime.jsx("button",{onClick:()=>e(s.latex),style:styles$3.symbolButton,title:`${s.name}: ${s.latex}`,children:s.preview||s.latex},s.name))})]})}function LatexPreview({latex:e}){return jsxRuntime.jsxs("div",{style:styles$3.preview,children:[jsxRuntime.jsx("div",{style:{fontSize:"12px",color:"#666",marginBottom:"8px"},children:"Preview (requires KaTeX/MathJax integration):"}),jsxRuntime.jsx("code",{style:{fontSize:"16px"},children:e||"(empty)"})]})}function HandwritingCanvas(){const{setLatex:e,setMode:t}=useMathEditor(),r=react.useRef(null),[n,a]=react.useState([]),[s,o]=react.useState([]),[c,l]=react.useState(!1),[i,p]=react.useState(!1),d=y=>{const x=r.current;if(!x)return;l(!0);const u=x.getBoundingClientRect();o([{x:y.clientX-u.left,y:y.clientY-u.top,pressure:y.pressure,timestamp:Date.now()}])},h=y=>{if(!c)return;const x=r.current,u=x==null?void 0:x.getContext("2d");if(!x||!u)return;const w=x.getBoundingClientRect(),j={x:y.clientX-w.left,y:y.clientY-w.top,pressure:y.pressure,timestamp:Date.now()};if(o(f=>[...f,j]),s.length>0){const f=s[s.length-1];u.beginPath(),u.moveTo(f.x,f.y),u.lineTo(j.x,j.y),u.strokeStyle="#000",u.lineWidth=2,u.lineCap="round",u.stroke()}},b=()=>{if(c){if(l(!1),s.length>1){const y={id:Date.now().toString(),points:[...s]};a(x=>[...x,y])}o([])}},g=()=>{const y=r.current,x=y==null?void 0:y.getContext("2d");x&&y&&x.clearRect(0,0,y.width,y.height),a([])},m=async()=>{if(n.length!==0){p(!0);try{const y=await recognizeHandwriting(n);e(y.latex),t("input")}finally{p(!1)}}};return react.useEffect(()=>{const y=r.current;y&&(y.width=y.offsetWidth,y.height=200)},[]),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("canvas",{ref:r,style:styles$3.canvas,onPointerDown:d,onPointerMove:h,onPointerUp:b,onPointerLeave:b}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"8px",marginTop:"12px"},children:[jsxRuntime.jsx("button",{onClick:g,style:{...styles$3.button,backgroundColor:"#f44336"},children:"Clear"}),jsxRuntime.jsx("button",{onClick:m,disabled:n.length===0||i,style:styles$3.button,children:i?"Recognizing...":"Recognize"})]}),jsxRuntime.jsx("p",{style:{fontSize:"12px",color:"#666",marginTop:"8px"},children:"Draw your equation above. Handwriting recognition requires external API integration."})]})}const mathConstants={pi:Math.PI,PI:Math.PI,e:Math.E,E:Math.E,phi:(1+Math.sqrt(5))/2,tau:Math.PI*2},mathFunctions={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,atan2:Math.atan2,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,sqrt:Math.sqrt,cbrt:Math.cbrt,abs:Math.abs,floor:Math.floor,ceil:Math.ceil,round:Math.round,exp:Math.exp,log:Math.log,log10:Math.log10,log2:Math.log2,pow:Math.pow,min:Math.min,max:Math.max,sign:Math.sign,hypot:Math.hypot,sec:e=>1/Math.cos(e),csc:e=>1/Math.sin(e),cot:e=>1/Math.tan(e),ln:Math.log};class ExpressionParser{constructor(){k(this,"pos",0);k(this,"expr","")}parse(t){this.expr=t.replace(/\s+/g,""),this.pos=0;const r=this.parseAddSub();return n=>this.evaluate(r,{...mathConstants,...n})}parseAddSub(){let t=this.parseMulDiv();for(;this.pos<this.expr.length;){const r=this.expr[this.pos];if(r!=="+"&&r!=="-")break;this.pos++;const n=this.parseMulDiv();t={type:"binary",op:r,left:t,right:n}}return t}parseMulDiv(){let t=this.parsePower();for(;this.pos<this.expr.length;){const r=this.expr[this.pos];if(r!=="*"&&r!=="/")break;this.pos++;const n=this.parsePower();t={type:"binary",op:r,left:t,right:n}}return t}parsePower(){let t=this.parseUnary();for(;this.pos<this.expr.length&&this.expr[this.pos]==="^";){this.pos++;const r=this.parseUnary();t={type:"binary",op:"^",left:t,right:r}}return t}parseUnary(){return this.expr[this.pos]==="-"?(this.pos++,{type:"unary",op:"-",arg:this.parseUnary()}):(this.expr[this.pos]==="+"&&this.pos++,this.parsePrimary())}parsePrimary(){if(this.expr[this.pos]==="("){this.pos++;const n=this.parseAddSub();return this.expr[this.pos]===")"&&this.pos++,n}const t=this.expr.slice(this.pos).match(/^(\d+\.?\d*)/);if(t)return this.pos+=t[1].length,{type:"number",value:parseFloat(t[1])};const r=this.expr.slice(this.pos).match(/^([a-zA-Z_][a-zA-Z0-9_]*)/);if(r){const n=r[1];if(this.pos+=n.length,this.expr[this.pos]==="("){this.pos++;const a=[];for(;this.expr[this.pos]!==")"&&this.pos<this.expr.length;)a.push(this.parseAddSub()),this.expr[this.pos]===","&&this.pos++;return this.expr[this.pos]===")"&&this.pos++,{type:"call",name:n,args:a}}return{type:"variable",name:n}}return{type:"number",value:0}}evaluate(t,r){switch(t.type){case"number":return t.value;case"variable":if(t.name in r)return r[t.name];throw new Error(`Unknown variable: ${t.name}`);case"unary":return t.op==="-"?-this.evaluate(t.arg,r):this.evaluate(t.arg,r);case"binary":{const n=this.evaluate(t.left,r),a=this.evaluate(t.right,r);switch(t.op){case"+":return n+a;case"-":return n-a;case"*":return n*a;case"/":return n/a;case"^":return Math.pow(n,a);default:return 0}}case"call":{const n=mathFunctions[t.name];if(!n)throw new Error(`Unknown function: ${t.name}`);const a=t.args.map(s=>this.evaluate(s,r));return n(...a)}default:return 0}}}class GraphService{constructor(t={}){k(this,"plots",new Map);k(this,"parser",new ExpressionParser);k(this,"config");this.config={defaultResolution:t.defaultResolution??200,maxResolution:t.maxResolution??1e3}}addPlot(t){const r={id:this.generateId(),type:t.type,expression:t.expression,expressionY:t.expressionY,expressionZ:t.expressionZ,label:t.label,color:t.color??{r:66,g:133,b:244},lineWidth:t.lineWidth??2,visible:t.visible??!0,parameterRange:t.parameterRange??{min:-Math.PI,max:Math.PI},parameterRange2:t.parameterRange2??{min:-Math.PI,max:Math.PI},resolution:t.resolution??this.config.defaultResolution};return this.plots.set(r.id,r),r}updatePlot(t,r){const n=this.plots.get(t);if(!n)throw new Error(`Plot not found: ${t}`);const a={...n,...r,id:n.id};return this.plots.set(t,a),a}removePlot(t){this.plots.delete(t)}getPlots(){return Array.from(this.plots.values())}getPlot(t){return this.plots.get(t)}compute2DFunction(t,r,n,a){const s=this.parser.parse(t),o=[],c=(r.max-r.min)/n;for(let l=0;l<=n;l++){const i=r.min+l*c;try{const p=s({x:i,...a});Number.isFinite(p)&&o.push({x:i,y:p})}catch{}}return o}compute2DParametric(t,r,n,a,s){const o=this.parser.parse(t),c=this.parser.parse(r),l=[],i=(n.max-n.min)/a;for(let p=0;p<=a;p++){const d=n.min+p*i;try{const h=o({t:d,...s}),b=c({t:d,...s});Number.isFinite(h)&&Number.isFinite(b)&&l.push({x:h,y:b})}catch{}}return l}compute2DPolar(t,r,n,a){const s=this.parser.parse(t),o=[],c=(r.max-r.min)/n;for(let l=0;l<=n;l++){const i=r.min+l*c;try{const p=s({theta:i,t:i,...a});if(Number.isFinite(p)){const d=p*Math.cos(i),h=p*Math.sin(i);o.push({x:d,y:h})}}catch{}}return o}compute3DSurface(t,r,n,a,s){const o=this.parser.parse(t),c=[],l=(r.max-r.min)/a,i=(n.max-n.min)/a;for(let p=0;p<=a;p++){const d=[],h=r.min+p*l;for(let b=0;b<=a;b++){const g=n.min+b*i;try{const m=o({x:h,y:g,...s});Number.isFinite(m)?d.push({x:h,y:g,z:m}):d.push({x:h,y:g,z:0})}catch{d.push({x:h,y:g,z:0})}}c.push(d)}return c}exportSVG(t,r,n,a){const o=n-80,c=a-40*2,l=d=>40+(d-r.xRange.min)/(r.xRange.max-r.xRange.min)*o,i=d=>a-40-(d-r.yRange.min)/(r.yRange.max-r.yRange.min)*c,p=[`<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${a}">`,`<rect width="100%" height="100%" fill="rgb(${r.backgroundColor.r},${r.backgroundColor.g},${r.backgroundColor.b})"/>`];if(r.showGrid){p.push('<g stroke="#ddd" stroke-width="0.5">');for(let d=Math.ceil(r.xRange.min);d<=r.xRange.max;d++){const h=l(d);p.push(`<line x1="${h}" y1="40" x2="${h}" y2="${a-40}"/>`)}for(let d=Math.ceil(r.yRange.min);d<=r.yRange.max;d++){const h=i(d);p.push(`<line x1="40" y1="${h}" x2="${n-40}" y2="${h}"/>`)}p.push("</g>")}if(r.showAxes){p.push('<g stroke="#333" stroke-width="1">');const d=i(0),h=l(0);p.push(`<line x1="40" y1="${d}" x2="${n-40}" y2="${d}"/>`),p.push(`<line x1="${h}" y1="40" x2="${h}" y2="${a-40}"/>`),p.push("</g>")}for(const d of t.filter(h=>h.visible))if(d.type==="2d-function"){const h=this.compute2DFunction(d.expression,r.xRange,d.resolution||200);if(h.length>0){const b=h.map((g,m)=>`${m===0?"M":"L"}${l(g.x)},${i(g.y)}`).join(" ");p.push(`<path d="${b}" fill="none" stroke="rgb(${d.color.r},${d.color.g},${d.color.b})" stroke-width="${d.lineWidth}"/>`)}}return r.showLabels&&(p.push(`<text x="${n/2}" y="${a-10}" text-anchor="middle" font-size="12">x</text>`),p.push(`<text x="10" y="${a/2}" text-anchor="middle" font-size="12" transform="rotate(-90,10,${a/2})">y</text>`)),p.push("</svg>"),p.join(`
3
- `)}async exportPNG(t,r,n,a){const s=this.exportSVG(t,r,n,a);return new Promise((o,c)=>{const l=new Image;l.onload=()=>{const i=document.createElement("canvas");i.width=n,i.height=a;const p=i.getContext("2d");if(!p){c(new Error("Could not get canvas context"));return}p.drawImage(l,0,0),o(i.toDataURL("image/png"))},l.onerror=c,l.src="data:image/svg+xml;base64,"+btoa(s)})}generateId(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}}function createGraphService(e){return new GraphService(e)}const FUNCTION_PRESETS=[{name:"Linear",expression:"x",type:"2d-function",category:"basic"},{name:"Quadratic",expression:"x^2",type:"2d-function",category:"basic"},{name:"Cubic",expression:"x^3",type:"2d-function",category:"basic"},{name:"Square root",expression:"sqrt(x)",type:"2d-function",category:"basic"},{name:"Absolute",expression:"abs(x)",type:"2d-function",category:"basic"},{name:"Reciprocal",expression:"1/x",type:"2d-function",category:"basic"},{name:"Sine",expression:"sin(x)",type:"2d-function",category:"trigonometric"},{name:"Cosine",expression:"cos(x)",type:"2d-function",category:"trigonometric"},{name:"Tangent",expression:"tan(x)",type:"2d-function",category:"trigonometric"},{name:"Sine wave",expression:"sin(2*x)",type:"2d-function",category:"trigonometric"},{name:"Damped oscillation",expression:"exp(-x/5)*sin(x*3)",type:"2d-function",category:"trigonometric"},{name:"Exponential",expression:"exp(x)",type:"2d-function",category:"exponential"},{name:"Natural log",expression:"ln(x)",type:"2d-function",category:"exponential"},{name:"Gaussian",expression:"exp(-x^2)",type:"2d-function",category:"exponential"},{name:"Sigmoid",expression:"1/(1+exp(-x))",type:"2d-function",category:"exponential"},{name:"Circle",expression:"cos(t)",expressionY:"sin(t)",type:"2d-parametric",category:"parametric"},{name:"Ellipse",expression:"2*cos(t)",expressionY:"sin(t)",type:"2d-parametric",category:"parametric"},{name:"Lissajous",expression:"sin(3*t)",expressionY:"sin(2*t)",type:"2d-parametric",category:"parametric"},{name:"Spiral",expression:"t*cos(t)",expressionY:"t*sin(t)",type:"2d-parametric",category:"parametric"},{name:"Cardioid",expression:"(1-cos(t))*cos(t)",expressionY:"(1-cos(t))*sin(t)",type:"2d-parametric",category:"parametric"},{name:"Rose curve",expression:"cos(3*t)*cos(t)",expressionY:"cos(3*t)*sin(t)",type:"2d-parametric",category:"parametric"},{name:"Polar rose 3",expression:"cos(3*theta)",type:"2d-polar",category:"polar"},{name:"Polar rose 5",expression:"cos(5*theta)",type:"2d-polar",category:"polar"},{name:"Archimedean spiral",expression:"theta",type:"2d-polar",category:"polar"},{name:"Logarithmic spiral",expression:"exp(theta/10)",type:"2d-polar",category:"polar"},{name:"Paraboloid",expression:"x^2 + y^2",type:"3d-surface",category:"3d"},{name:"Saddle",expression:"x^2 - y^2",type:"3d-surface",category:"3d"},{name:"Ripple",expression:"sin(sqrt(x^2 + y^2))",type:"3d-surface",category:"3d"},{name:"Torus slice",expression:"cos(x)*sin(y)",type:"3d-surface",category:"3d"},{name:"Peaks",expression:"3*(1-x)^2*exp(-x^2-(y+1)^2) - 10*(x/5-x^3-y^5)*exp(-x^2-y^2) - 1/3*exp(-(x+1)^2-y^2)",type:"3d-surface",category:"3d"}],GraphContext=react.createContext(null);function useGraph(){const e=react.useContext(GraphContext);if(!e)throw new Error("useGraph must be used within GraphProvider");return e}const styles$2={container:{display:"flex",height:"100%",fontFamily:"'Inter', sans-serif",fontSize:"14px"},sidebar:{width:"280px",borderRight:"1px solid #e0e0e0",display:"flex",flexDirection:"column",overflow:"hidden"},plotList:{flex:1,overflow:"auto",padding:"8px"},main:{flex:1,display:"flex",flexDirection:"column",backgroundColor:"#fff"},canvas:{flex:1,backgroundColor:"#fff"},toolbar:{display:"flex",gap:"8px",padding:"8px",borderBottom:"1px solid #e0e0e0",alignItems:"center"},button:{padding:"6px 12px",backgroundColor:"#1976d2",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"13px"},input:{padding:"6px 8px",border:"1px solid #ddd",borderRadius:"4px",fontSize:"13px"},plotItem:{padding:"8px",marginBottom:"8px",border:"1px solid #e0e0e0",borderRadius:"4px",backgroundColor:"#fafafa"}};function NiceGraphPlotter({service:e,width:t=800,height:r=600,className:n,style:a}){const[s,o]=react.useState([]),[c,l]=react.useState({xRange:{min:-10,max:10},yRange:{min:-10,max:10},zRange:{min:-5,max:5},showGrid:!0,showAxes:!0,showLabels:!0,backgroundColor:{r:255,g:255,b:255},cameraRotationX:30,cameraRotationY:45,cameraDistance:5}),[i,p]=react.useState({isPlaying:!1,parameter:"a",currentValue:0,minValue:-5,maxValue:5,speed:1}),d=react.useCallback(()=>{o(e.getPlots())},[e]),h=react.useCallback(u=>{l(w=>({...w,...u}))},[]),b=react.useCallback(u=>{p(w=>({...w,...u}))},[]),g=react.useCallback(u=>{e.addPlot(u),d()},[e,d]),m=react.useCallback(u=>{e.removePlot(u),d()},[e,d]),y=react.useCallback((u,w)=>{e.updatePlot(u,w),d()},[e,d]),x={service:e,plots:s,view:c,setView:h,addPlot:g,removePlot:m,updatePlot:y,animation:i,setAnimation:b,refresh:d};return jsxRuntime.jsx(GraphContext.Provider,{value:x,children:jsxRuntime.jsxs("div",{className:n,style:{...styles$2.container,...a},children:[jsxRuntime.jsxs("div",{style:styles$2.sidebar,children:[jsxRuntime.jsx(PlotControls,{}),jsxRuntime.jsx(PlotList,{})]}),jsxRuntime.jsxs("div",{style:styles$2.main,children:[jsxRuntime.jsx(GraphToolbar,{width:t,height:r}),jsxRuntime.jsx(Canvas2D,{width:t,height:r})]})]})})}function PlotControls(){const{addPlot:e}=useGraph(),[t,r]=react.useState("sin(x)"),[n,a]=react.useState("2d-function"),[s,o]=react.useState("cos(x)"),c=()=>{e({type:n,expression:t,expressionY:n==="2d-parametric"?s:void 0,color:{r:Math.floor(Math.random()*200),g:Math.floor(Math.random()*200),b:Math.floor(Math.random()*200)}})};return jsxRuntime.jsxs("div",{style:{padding:"12px",borderBottom:"1px solid #e0e0e0"},children:[jsxRuntime.jsx("div",{style:{marginBottom:"8px"},children:jsxRuntime.jsxs("select",{value:n,onChange:l=>a(l.target.value),style:{...styles$2.input,width:"100%"},children:[jsxRuntime.jsx("option",{value:"2d-function",children:"y = f(x)"}),jsxRuntime.jsx("option",{value:"2d-parametric",children:"Parametric (x(t), y(t))"}),jsxRuntime.jsx("option",{value:"2d-polar",children:"Polar r = f(θ)"}),jsxRuntime.jsx("option",{value:"3d-surface",children:"3D Surface z = f(x,y)"})]})}),jsxRuntime.jsx("div",{style:{marginBottom:"8px"},children:jsxRuntime.jsx("input",{type:"text",value:t,onChange:l=>r(l.target.value),placeholder:n==="2d-parametric"?"x(t) = ...":"Expression...",style:{...styles$2.input,width:"100%"}})}),n==="2d-parametric"&&jsxRuntime.jsx("div",{style:{marginBottom:"8px"},children:jsxRuntime.jsx("input",{type:"text",value:s,onChange:l=>o(l.target.value),placeholder:"y(t) = ...",style:{...styles$2.input,width:"100%"}})}),jsxRuntime.jsx("button",{onClick:c,style:{...styles$2.button,width:"100%"},children:"+ Add Plot"}),jsxRuntime.jsxs("select",{onChange:l=>{const i=FUNCTION_PRESETS.find(p=>p.name===l.target.value);i&&e({type:i.type,expression:i.expression,expressionY:i.expressionY,label:i.name,color:{r:Math.floor(Math.random()*200),g:Math.floor(Math.random()*200),b:Math.floor(Math.random()*200)}})},style:{...styles$2.input,width:"100%",marginTop:"8px"},value:"",children:[jsxRuntime.jsx("option",{value:"",disabled:!0,children:"Quick add preset..."}),["basic","trigonometric","exponential","parametric","polar","3d"].map(l=>jsxRuntime.jsx("optgroup",{label:l.charAt(0).toUpperCase()+l.slice(1),children:FUNCTION_PRESETS.filter(i=>i.category===l).map(i=>jsxRuntime.jsxs("option",{value:i.name,children:[i.name,": ",i.expression]},i.name))},l))]})]})}function PlotList(){const{plots:e,removePlot:t,updatePlot:r}=useGraph();return jsxRuntime.jsxs("div",{style:styles$2.plotList,children:[e.length===0&&jsxRuntime.jsx("div",{style:{color:"#666",textAlign:"center",padding:"16px"},children:"No plots added yet"}),e.map(n=>jsxRuntime.jsxs("div",{style:styles$2.plotItem,children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsxRuntime.jsx("input",{type:"checkbox",checked:n.visible,onChange:a=>r(n.id,{visible:a.target.checked})}),jsxRuntime.jsx("div",{style:{width:"16px",height:"16px",borderRadius:"3px",backgroundColor:`rgb(${n.color.r},${n.color.g},${n.color.b})`}}),jsxRuntime.jsx("span",{style:{flex:1,fontWeight:500},children:n.label||n.expression}),jsxRuntime.jsx("button",{onClick:()=>t(n.id),style:{padding:"2px 6px",backgroundColor:"#f44336",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"12px"},children:"×"})]}),jsxRuntime.jsx("div",{style:{fontSize:"12px",color:"#666",fontFamily:"monospace"},children:n.type==="2d-parametric"?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:["x(t) = ",n.expression,jsxRuntime.jsx("br",{}),"y(t) = ",n.expressionY]}):n.expression})]},n.id))]})}function GraphToolbar({width:e,height:t}){const{service:r,plots:n,view:a,setView:s}=useGraph(),o=()=>{const l=r.exportSVG(n,a,e,t),i=new Blob([l],{type:"image/svg+xml"}),p=URL.createObjectURL(i),d=document.createElement("a");d.href=p,d.download="graph.svg",d.click(),URL.revokeObjectURL(p)},c=async()=>{const l=await r.exportPNG(n,a,e,t),i=document.createElement("a");i.href=l,i.download="graph.png",i.click()};return jsxRuntime.jsxs("div",{style:styles$2.toolbar,children:[jsxRuntime.jsxs("label",{style:{fontSize:"12px"},children:["X: ["," ",jsxRuntime.jsx("input",{type:"number",value:a.xRange.min,onChange:l=>s({xRange:{...a.xRange,min:Number(l.target.value)}}),style:{...styles$2.input,width:"50px"}}),","," ",jsxRuntime.jsx("input",{type:"number",value:a.xRange.max,onChange:l=>s({xRange:{...a.xRange,max:Number(l.target.value)}}),style:{...styles$2.input,width:"50px"}}),"]"]}),jsxRuntime.jsxs("label",{style:{fontSize:"12px"},children:["Y: ["," ",jsxRuntime.jsx("input",{type:"number",value:a.yRange.min,onChange:l=>s({yRange:{...a.yRange,min:Number(l.target.value)}}),style:{...styles$2.input,width:"50px"}}),","," ",jsxRuntime.jsx("input",{type:"number",value:a.yRange.max,onChange:l=>s({yRange:{...a.yRange,max:Number(l.target.value)}}),style:{...styles$2.input,width:"50px"}}),"]"]}),jsxRuntime.jsxs("label",{style:{fontSize:"12px"},children:[jsxRuntime.jsx("input",{type:"checkbox",checked:a.showGrid,onChange:l=>s({showGrid:l.target.checked})}),"Grid"]}),jsxRuntime.jsxs("label",{style:{fontSize:"12px"},children:[jsxRuntime.jsx("input",{type:"checkbox",checked:a.showAxes,onChange:l=>s({showAxes:l.target.checked})}),"Axes"]}),jsxRuntime.jsx("div",{style:{flex:1}}),jsxRuntime.jsx("button",{onClick:o,style:{...styles$2.button,backgroundColor:"#4caf50"},children:"📥 SVG"}),jsxRuntime.jsx("button",{onClick:c,style:{...styles$2.button,backgroundColor:"#ff9800"},children:"📥 PNG"})]})}function Canvas2D({width:e,height:t}){const r=react.useRef(null),{service:n,plots:a,view:s,animation:o}=useGraph(),c=40;return react.useEffect(()=>{const l=r.current,i=l==null?void 0:l.getContext("2d");if(!l||!i)return;i.fillStyle=`rgb(${s.backgroundColor.r},${s.backgroundColor.g},${s.backgroundColor.b})`,i.fillRect(0,0,e,t);const p=e-c*2,d=t-c*2,h=m=>c+(m-s.xRange.min)/(s.xRange.max-s.xRange.min)*p,b=m=>t-c-(m-s.yRange.min)/(s.yRange.max-s.yRange.min)*d;if(s.showGrid){i.strokeStyle="#e0e0e0",i.lineWidth=.5;for(let m=Math.ceil(s.xRange.min);m<=s.xRange.max;m++){const y=h(m);i.beginPath(),i.moveTo(y,c),i.lineTo(y,t-c),i.stroke()}for(let m=Math.ceil(s.yRange.min);m<=s.yRange.max;m++){const y=b(m);i.beginPath(),i.moveTo(c,y),i.lineTo(e-c,y),i.stroke()}}if(s.showAxes){i.strokeStyle="#333",i.lineWidth=1;const m=b(0);i.beginPath(),i.moveTo(c,m),i.lineTo(e-c,m),i.stroke();const y=h(0);if(i.beginPath(),i.moveTo(y,c),i.lineTo(y,t-c),i.stroke(),s.showLabels){i.fillStyle="#333",i.font="12px sans-serif",i.textAlign="center",i.fillText("x",e-c+15,m+4),i.fillText("y",y,c-10),i.font="10px sans-serif";for(let x=Math.ceil(s.xRange.min);x<=s.xRange.max;x++)x!==0&&i.fillText(String(x),h(x),m+15);for(let x=Math.ceil(s.yRange.min);x<=s.yRange.max;x++)x!==0&&(i.textAlign="right",i.fillText(String(x),y-5,b(x)+4))}}const g=o.isPlaying?{[o.parameter]:o.currentValue}:{};for(const m of a.filter(y=>y.visible)){const y=`rgb(${m.color.r},${m.color.g},${m.color.b})`;i.strokeStyle=y,i.lineWidth=m.lineWidth||2;let x=[];switch(m.type){case"2d-function":x=n.compute2DFunction(m.expression,s.xRange,m.resolution||200,g);break;case"2d-parametric":x=n.compute2DParametric(m.expression,m.expressionY||"sin(t)",m.parameterRange||{min:0,max:2*Math.PI},m.resolution||200,g);break;case"2d-polar":x=n.compute2DPolar(m.expression,m.parameterRange||{min:0,max:2*Math.PI},m.resolution||200,g);break}if(x.length>0){i.beginPath();let u=!1;for(const w of x){const j=h(w.x),f=b(w.y);if(f<0||f>t){u=!1;continue}u?i.lineTo(j,f):(i.moveTo(j,f),u=!0)}i.stroke()}}},[a,s,o,n,e,t]),jsxRuntime.jsx("canvas",{ref:r,width:e,height:t,style:styles$2.canvas})}const UNITS=[{name:"Meter",symbol:"m",category:"Length",toBase:e=>e,fromBase:e=>e},{name:"Kilometer",symbol:"km",category:"Length",toBase:e=>e*1e3,fromBase:e=>e/1e3},{name:"Centimeter",symbol:"cm",category:"Length",toBase:e=>e/100,fromBase:e=>e*100},{name:"Millimeter",symbol:"mm",category:"Length",toBase:e=>e/1e3,fromBase:e=>e*1e3},{name:"Mile",symbol:"mi",category:"Length",toBase:e=>e*1609.344,fromBase:e=>e/1609.344},{name:"Yard",symbol:"yd",category:"Length",toBase:e=>e*.9144,fromBase:e=>e/.9144},{name:"Foot",symbol:"ft",category:"Length",toBase:e=>e*.3048,fromBase:e=>e/.3048},{name:"Inch",symbol:"in",category:"Length",toBase:e=>e*.0254,fromBase:e=>e/.0254},{name:"Kilogram",symbol:"kg",category:"Mass",toBase:e=>e,fromBase:e=>e},{name:"Gram",symbol:"g",category:"Mass",toBase:e=>e/1e3,fromBase:e=>e*1e3},{name:"Milligram",symbol:"mg",category:"Mass",toBase:e=>e/1e6,fromBase:e=>e*1e6},{name:"Pound",symbol:"lb",category:"Mass",toBase:e=>e*.453592,fromBase:e=>e/.453592},{name:"Ounce",symbol:"oz",category:"Mass",toBase:e=>e*.0283495,fromBase:e=>e/.0283495},{name:"Ton",symbol:"t",category:"Mass",toBase:e=>e*1e3,fromBase:e=>e/1e3},{name:"Celsius",symbol:"°C",category:"Temperature",toBase:e=>e,fromBase:e=>e},{name:"Fahrenheit",symbol:"°F",category:"Temperature",toBase:e=>(e-32)*5/9,fromBase:e=>e*9/5+32},{name:"Kelvin",symbol:"K",category:"Temperature",toBase:e=>e-273.15,fromBase:e=>e+273.15},{name:"Second",symbol:"s",category:"Time",toBase:e=>e,fromBase:e=>e},{name:"Millisecond",symbol:"ms",category:"Time",toBase:e=>e/1e3,fromBase:e=>e*1e3},{name:"Minute",symbol:"min",category:"Time",toBase:e=>e*60,fromBase:e=>e/60},{name:"Hour",symbol:"hr",category:"Time",toBase:e=>e*3600,fromBase:e=>e/3600},{name:"Day",symbol:"d",category:"Time",toBase:e=>e*86400,fromBase:e=>e/86400},{name:"Week",symbol:"wk",category:"Time",toBase:e=>e*604800,fromBase:e=>e/604800},{name:"Square meter",symbol:"m²",category:"Area",toBase:e=>e,fromBase:e=>e},{name:"Square kilometer",symbol:"km²",category:"Area",toBase:e=>e*1e6,fromBase:e=>e/1e6},{name:"Hectare",symbol:"ha",category:"Area",toBase:e=>e*1e4,fromBase:e=>e/1e4},{name:"Acre",symbol:"ac",category:"Area",toBase:e=>e*4046.86,fromBase:e=>e/4046.86},{name:"Square foot",symbol:"ft²",category:"Area",toBase:e=>e*.092903,fromBase:e=>e/.092903},{name:"Liter",symbol:"L",category:"Volume",toBase:e=>e,fromBase:e=>e},{name:"Milliliter",symbol:"mL",category:"Volume",toBase:e=>e/1e3,fromBase:e=>e*1e3},{name:"Cubic meter",symbol:"m³",category:"Volume",toBase:e=>e*1e3,fromBase:e=>e/1e3},{name:"Gallon (US)",symbol:"gal",category:"Volume",toBase:e=>e*3.78541,fromBase:e=>e/3.78541},{name:"Quart",symbol:"qt",category:"Volume",toBase:e=>e*.946353,fromBase:e=>e/.946353},{name:"Pint",symbol:"pt",category:"Volume",toBase:e=>e*.473176,fromBase:e=>e/.473176},{name:"Cup",symbol:"cup",category:"Volume",toBase:e=>e*.236588,fromBase:e=>e/.236588},{name:"Meters/second",symbol:"m/s",category:"Speed",toBase:e=>e,fromBase:e=>e},{name:"Kilometers/hour",symbol:"km/h",category:"Speed",toBase:e=>e/3.6,fromBase:e=>e*3.6},{name:"Miles/hour",symbol:"mph",category:"Speed",toBase:e=>e*.44704,fromBase:e=>e/.44704},{name:"Knots",symbol:"kn",category:"Speed",toBase:e=>e*.514444,fromBase:e=>e/.514444},{name:"Byte",symbol:"B",category:"Data",toBase:e=>e,fromBase:e=>e},{name:"Kilobyte",symbol:"KB",category:"Data",toBase:e=>e*1024,fromBase:e=>e/1024},{name:"Megabyte",symbol:"MB",category:"Data",toBase:e=>e*1048576,fromBase:e=>e/1048576},{name:"Gigabyte",symbol:"GB",category:"Data",toBase:e=>e*1073741824,fromBase:e=>e/1073741824},{name:"Terabyte",symbol:"TB",category:"Data",toBase:e=>e*1099511627776,fromBase:e=>e/1099511627776},{name:"Bit",symbol:"bit",category:"Data",toBase:e=>e/8,fromBase:e=>e*8}],MatrixOps={create(e,t,r=0){const n=[];for(let a=0;a<e;a++)n.push(new Array(t).fill(r));return{rows:e,cols:t,data:n}},identity(e){const t=this.create(e,e);for(let r=0;r<e;r++)t.data[r][r]=1;return t},add(e,t){if(e.rows!==t.rows||e.cols!==t.cols)throw new Error("Matrix dimensions must match for addition");const r=this.create(e.rows,e.cols);for(let n=0;n<e.rows;n++)for(let a=0;a<e.cols;a++)r.data[n][a]=e.data[n][a]+t.data[n][a];return r},subtract(e,t){if(e.rows!==t.rows||e.cols!==t.cols)throw new Error("Matrix dimensions must match for subtraction");const r=this.create(e.rows,e.cols);for(let n=0;n<e.rows;n++)for(let a=0;a<e.cols;a++)r.data[n][a]=e.data[n][a]-t.data[n][a];return r},multiply(e,t){if(e.cols!==t.rows)throw new Error("Matrix A columns must equal Matrix B rows for multiplication");const r=this.create(e.rows,t.cols);for(let n=0;n<e.rows;n++)for(let a=0;a<t.cols;a++){let s=0;for(let o=0;o<e.cols;o++)s+=e.data[n][o]*t.data[o][a];r.data[n][a]=s}return r},scalar(e,t){const r=this.create(e.rows,e.cols);for(let n=0;n<e.rows;n++)for(let a=0;a<e.cols;a++)r.data[n][a]=e.data[n][a]*t;return r},transpose(e){const t=this.create(e.cols,e.rows);for(let r=0;r<e.rows;r++)for(let n=0;n<e.cols;n++)t.data[n][r]=e.data[r][n];return t},determinant(e){if(e.rows!==e.cols)throw new Error("Determinant requires square matrix");if(e.rows===1)return e.data[0][0];if(e.rows===2)return e.data[0][0]*e.data[1][1]-e.data[0][1]*e.data[1][0];let t=0;for(let r=0;r<e.cols;r++)t+=Math.pow(-1,r)*e.data[0][r]*this.determinant(this.minor(e,0,r));return t},minor(e,t,r){const n=this.create(e.rows-1,e.cols-1);let a=0;for(let s=0;s<e.rows;s++){if(s===t)continue;let o=0;for(let c=0;c<e.cols;c++)c!==r&&(n.data[a][o]=e.data[s][c],o++);a++}return n},inverse(e){const t=this.determinant(e);if(t===0)throw new Error("Matrix is singular, cannot compute inverse");const r=e.rows,n=this.create(r,r);for(let a=0;a<r;a++)for(let s=0;s<r;s++){const o=Math.pow(-1,a+s),c=this.determinant(this.minor(e,a,s));n.data[s][a]=o*c}return this.scalar(n,1/t)},trace(e){if(e.rows!==e.cols)throw new Error("Trace requires square matrix");let t=0;for(let r=0;r<e.rows;r++)t+=e.data[r][r];return t},eigenvalues2x2(e){if(e.rows!==2||e.cols!==2)throw new Error("Only 2x2 matrices supported for eigenvalues");const t=e.data[0][0],r=e.data[0][1],n=e.data[1][0],a=e.data[1][1],s=t+a,o=t*a-r*n,c=s*s-4*o;if(c<0)throw new Error("Complex eigenvalues not supported");const l=Math.sqrt(c);return[(s+l)/2,(s-l)/2]},toString(e,t=4){return e.data.map(r=>"[ "+r.map(n=>n.toFixed(t).padStart(10)).join(" ")+" ]").join(`
4
- `)}},CalculusOps={derivative(e,t,r=1e-7){return(e(t+r)-e(t-r))/(2*r)},secondDerivative(e,t,r=1e-5){return(e(t+r)-2*e(t)+e(t-r))/(r*r)},integrate(e,t,r,n=1e3){n%2!==0&&n++;const a=(r-t)/n;let s=e(t)+e(r);for(let o=1;o<n;o++){const c=t+o*a;s+=o%2===0?2*e(c):4*e(c)}return a/3*s},findRoot(e,t,r=1e-10,n=100){let a=t;for(let s=0;s<n;s++){const o=e(a);if(Math.abs(o)<r)return a;const c=this.derivative(e,a);if(c===0)throw new Error("Derivative is zero, Newton-Raphson failed");a=a-o/c}throw new Error("Newton-Raphson did not converge")},symbolicDerivative(e){if(e=e.trim(),/^-?\d+\.?\d*$/.test(e))return"0";if(e==="x")return"1";const t=e.match(/^x\^(\d+)$/);if(t){const n=parseInt(t[1],10);return n===1?"1":n===2?"2*x":`${n}*x^${n-1}`}const r=e.match(/^(-?\d+\.?\d*)\*x\^(\d+)$/);if(r){const n=parseFloat(r[1]),a=parseInt(r[2],10),s=n*a;return a===1?String(s):a===2?`${s}*x`:`${s}*x^${a-1}`}return e==="sin(x)"?"cos(x)":e==="cos(x)"?"-sin(x)":e==="e^x"||e==="exp(x)"?"e^x":e==="ln(x)"?"1/x":`d/dx(${e})`},symbolicIntegral(e){if(e=e.trim(),/^-?\d+\.?\d*$/.test(e))return`${e}*x + C`;if(e==="x")return"x^2/2 + C";const t=e.match(/^x\^(\d+)$/);if(t){const r=parseInt(t[1],10);return`x^${r+1}/${r+1} + C`}return e==="sin(x)"?"-cos(x) + C":e==="cos(x)"?"sin(x) + C":e==="e^x"||e==="exp(x)"?"e^x + C":e==="1/x"?"ln|x| + C":`∫(${e})dx + C`},solveQuadratic(e,t,r){const n=t*t-4*e*r;if(n<0)throw new Error("No real solutions (complex roots)");if(n===0)return[-t/(2*e)];const a=Math.sqrt(n);return[(-t+a)/(2*e),(-t-a)/(2*e)]}};class CalculatorService{constructor(e={}){k(this,"history",[]);k(this,"memory",0);k(this,"variables",new Map);k(this,"config");this.config={precision:e.precision??12,angleUnit:e.angleUnit??"rad"}}evaluate(expression){let expr=expression.replace(/π|pi/gi,String(Math.PI)).replace(/e(?![xp])/gi,String(Math.E)).replace(/\^/g,"**").replace(/√/g,"Math.sqrt").replace(/sin/gi,"Math.sin").replace(/cos/gi,"Math.cos").replace(/tan/gi,"Math.tan").replace(/asin/gi,"Math.asin").replace(/acos/gi,"Math.acos").replace(/atan/gi,"Math.atan").replace(/sinh/gi,"Math.sinh").replace(/cosh/gi,"Math.cosh").replace(/tanh/gi,"Math.tanh").replace(/log10/gi,"Math.log10").replace(/log2/gi,"Math.log2").replace(/ln/gi,"Math.log").replace(/log\b/gi,"Math.log10").replace(/exp/gi,"Math.exp").replace(/sqrt/gi,"Math.sqrt").replace(/cbrt/gi,"Math.cbrt").replace(/abs/gi,"Math.abs").replace(/floor/gi,"Math.floor").replace(/ceil/gi,"Math.ceil").replace(/round/gi,"Math.round").replace(/pow/gi,"Math.pow").replace(/min/gi,"Math.min").replace(/max/gi,"Math.max");for(const[e,t]of this.variables)expr=expr.replace(new RegExp(`\\b${e}\\b`,"g"),String(t));try{const result=eval(expr);if(typeof result!="number"||!Number.isFinite(result))throw new Error("Invalid result");return result}catch(e){throw new Error(`Invalid expression: ${e.message}`)}}addHistory(e,t,r){this.history.unshift({id:Date.now().toString(36),expression:e,result:t,timestamp:new Date().toISOString(),mode:r}),this.history.length>100&&this.history.pop()}getHistory(){return this.history}clearHistory(){this.history=[]}memoryStore(e){this.memory=e}memoryRecall(){return this.memory}memoryAdd(e){this.memory+=e}memoryClear(){this.memory=0}setVariable(e,t){this.variables.set(e,t)}getVariable(e){return this.variables.get(e)}convertBase(e,t,r){const n={BIN:2,OCT:8,DEC:10,HEX:16},a=parseInt(e,n[t]);if(isNaN(a))throw new Error("Invalid number for base conversion");return a.toString(n[r]).toUpperCase()}convertUnits(e,t,r){const n=UNITS.find(o=>o.symbol===t),a=UNITS.find(o=>o.symbol===r);if(!n||!a)throw new Error("Unknown unit");if(n.category!==a.category)throw new Error("Cannot convert between different unit categories");const s=n.toBase(e);return a.fromBase(s)}getUnitsByCategory(e){return UNITS.filter(t=>t.category===e)}getUnitCategories(){return[...new Set(UNITS.map(e=>e.category))]}format(e){const t=this.config.precision;return Math.abs(e)<1e-10?"0":Math.abs(e)>1e10||Math.abs(e)<1e-6?e.toExponential(t):parseFloat(e.toPrecision(t)).toString()}}function createCalculatorService(e){return new CalculatorService(e)}const CalculatorContext=react.createContext(null);function useCalculator(){const e=react.useContext(CalculatorContext);if(!e)throw new Error("useCalculator must be used within CalculatorProvider");return e}const styles$1={container:{width:"400px",fontFamily:"'Inter', sans-serif",backgroundColor:"#1e1e1e",borderRadius:"12px",overflow:"hidden",boxShadow:"0 4px 20px rgba(0,0,0,0.3)"},modeSelector:{display:"flex",backgroundColor:"#2d2d2d"},modeButton:{flex:1,padding:"8px",border:"none",backgroundColor:"transparent",color:"#888",fontSize:"11px",cursor:"pointer"},display:{padding:"20px",backgroundColor:"#252525",minHeight:"80px"},displayText:{color:"#fff",fontSize:"32px",fontFamily:"'JetBrains Mono', monospace",textAlign:"right",wordBreak:"break-all"},keypad:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:"1px",backgroundColor:"#333",padding:"1px"},key:{padding:"20px",border:"none",backgroundColor:"#3c3c3c",color:"#fff",fontSize:"18px",cursor:"pointer",transition:"background-color 0.1s"},keyOperator:{backgroundColor:"#ff9f0a",color:"#000"},keyFunction:{backgroundColor:"#505050"}};function NiceCalculator({service:e,className:t,style:r}){const[n,a]=react.useState("0"),[s,o]=react.useState("standard"),[c,l]=react.useState([]),[i,p]=react.useState(!1),d=react.useCallback(m=>{i&&/[0-9.]/.test(m)?(a(m),p(!1)):(a(y=>y==="0"&&m!=="."?m:y+m),p(!1))},[i]),h=react.useCallback(()=>{a("0"),p(!1)},[]),b=react.useCallback(()=>{try{const m=e.evaluate(n),y=e.format(m);e.addHistory(n,y,s),l(e.getHistory()),a(y),p(!0)}catch{a("Error"),p(!0)}},[n,s,e]),g={service:e,display:n,setDisplay:a,mode:s,setMode:o,history:c,calculate:b,appendDigit:d,clear:h};return jsxRuntime.jsx(CalculatorContext.Provider,{value:g,children:jsxRuntime.jsxs("div",{className:t,style:{...styles$1.container,...r},children:[jsxRuntime.jsx(ModeSelector,{}),jsxRuntime.jsx(Display,{}),s==="standard"&&jsxRuntime.jsx(StandardKeypad,{}),s==="scientific"&&jsxRuntime.jsx(ScientificKeypad,{}),s==="programmer"&&jsxRuntime.jsx(ProgrammerKeypad,{}),s==="matrix"&&jsxRuntime.jsx(MatrixMode,{}),s==="calculus"&&jsxRuntime.jsx(CalculusMode,{}),s==="units"&&jsxRuntime.jsx(UnitsMode,{})]})})}function ModeSelector(){const{mode:e,setMode:t}=useCalculator(),r=[{id:"standard",label:"Standard"},{id:"scientific",label:"Scientific"},{id:"programmer",label:"Programmer"},{id:"matrix",label:"Matrix"},{id:"calculus",label:"Calculus"},{id:"units",label:"Units"}];return jsxRuntime.jsx("div",{style:styles$1.modeSelector,children:r.map(n=>jsxRuntime.jsx("button",{onClick:()=>t(n.id),style:{...styles$1.modeButton,backgroundColor:e===n.id?"#1976d2":"transparent",color:e===n.id?"#fff":"#888"},children:n.label},n.id))})}function Display(){const{display:e}=useCalculator();return jsxRuntime.jsx("div",{style:styles$1.display,children:jsxRuntime.jsx("div",{style:styles$1.displayText,children:e})})}function StandardKeypad(){const{appendDigit:e,clear:t,calculate:r,setDisplay:n,display:a}=useCalculator(),s=[{label:"AC",action:t,style:styles$1.keyFunction},{label:"±",action:()=>n(a.startsWith("-")?a.slice(1):"-"+a),style:styles$1.keyFunction},{label:"%",action:()=>e("/100"),style:styles$1.keyFunction},{label:"÷",action:()=>e("/"),style:styles$1.keyOperator},{label:"7",action:()=>e("7")},{label:"8",action:()=>e("8")},{label:"9",action:()=>e("9")},{label:"×",action:()=>e("*"),style:styles$1.keyOperator},{label:"4",action:()=>e("4")},{label:"5",action:()=>e("5")},{label:"6",action:()=>e("6")},{label:"−",action:()=>e("-"),style:styles$1.keyOperator},{label:"1",action:()=>e("1")},{label:"2",action:()=>e("2")},{label:"3",action:()=>e("3")},{label:"+",action:()=>e("+"),style:styles$1.keyOperator},{label:"0",action:()=>e("0")},{label:".",action:()=>e(".")},{label:"⌫",action:()=>n(a.length>1?a.slice(0,-1):"0")},{label:"=",action:r,style:styles$1.keyOperator}];return jsxRuntime.jsx("div",{style:styles$1.keypad,children:s.map((o,c)=>jsxRuntime.jsx("button",{onClick:o.action,style:{...styles$1.key,...o.style||{}},children:o.label},c))})}function ScientificKeypad(){const{appendDigit:e,clear:t,calculate:r,setDisplay:n,display:a}=useCalculator(),s=[{label:"sin",action:()=>e("sin(")},{label:"cos",action:()=>e("cos(")},{label:"tan",action:()=>e("tan(")},{label:"ln",action:()=>e("ln(")},{label:"log",action:()=>e("log10(")}],o=[{label:"x²",action:()=>e("^2")},{label:"x³",action:()=>e("^3")},{label:"xʸ",action:()=>e("^")},{label:"√",action:()=>e("sqrt(")},{label:"eˣ",action:()=>e("exp(")}],c=[{label:"(",action:()=>e("(")},{label:")",action:()=>e(")")},{label:"π",action:()=>e("π")},{label:"e",action:()=>e("e")},{label:"AC",action:t}];return jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("div",{style:{...styles$1.keypad,gridTemplateColumns:"repeat(5, 1fr)"},children:[...s,...o,...c].map((l,i)=>jsxRuntime.jsx("button",{onClick:l.action,style:{...styles$1.key,...styles$1.keyFunction,padding:"12px"},children:l.label},i))}),jsxRuntime.jsx(StandardKeypad,{})]})}function ProgrammerKeypad(){const{display:e,setDisplay:t,service:r}=useCalculator(),[n,a]=react.useState("DEC"),s=c=>{try{const l=r.convertBase(e,n,c);t(l),a(c)}catch{t("Error")}},o=n==="HEX"?["A","B","C","D","E","F"]:[];return jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("div",{style:{display:"flex",gap:"4px",padding:"8px",backgroundColor:"#252525"},children:["BIN","OCT","DEC","HEX"].map(c=>jsxRuntime.jsx("button",{onClick:()=>s(c),style:{flex:1,padding:"8px",border:"none",borderRadius:"4px",backgroundColor:n===c?"#1976d2":"#3c3c3c",color:"#fff",cursor:"pointer"},children:c},c))}),o.length>0&&jsxRuntime.jsx("div",{style:{...styles$1.keypad,gridTemplateColumns:"repeat(6, 1fr)"},children:o.map(c=>jsxRuntime.jsx("button",{onClick:()=>t(e==="0"?c:e+c),style:styles$1.key,children:c},c))}),jsxRuntime.jsx("div",{style:{...styles$1.keypad,gridTemplateColumns:"repeat(4, 1fr)"},children:["7","8","9","AND","4","5","6","OR","1","2","3","XOR","0","NOT","<<",">>"].map(c=>{const l=["AND","OR","XOR","NOT","<<",">>"].includes(c);return jsxRuntime.jsx("button",{onClick:()=>t(e==="0"?c:e+c),style:{...styles$1.key,...l?styles$1.keyFunction:{}},children:c},c)})})]})}function MatrixMode(){const[e,t]=react.useState(MatrixOps.create(2,2)),[r,n]=react.useState(MatrixOps.create(2,2)),[a,s]=react.useState(""),o=(l,i,p,d,h)=>{const b={...l,data:l.data.map(g=>[...g])};b.data[p][d]=parseFloat(h)||0,i(b)},c=[{label:"A + B",fn:()=>MatrixOps.toString(MatrixOps.add(e,r))},{label:"A - B",fn:()=>MatrixOps.toString(MatrixOps.subtract(e,r))},{label:"A × B",fn:()=>MatrixOps.toString(MatrixOps.multiply(e,r))},{label:"det(A)",fn:()=>MatrixOps.determinant(e).toFixed(4)},{label:"Aᵀ",fn:()=>MatrixOps.toString(MatrixOps.transpose(e))},{label:"A⁻¹",fn:()=>MatrixOps.toString(MatrixOps.inverse(e))}];return jsxRuntime.jsxs("div",{style:{padding:"12px",backgroundColor:"#252525"},children:[jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",marginBottom:"12px"},children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("div",{style:{color:"#888",marginBottom:"4px"},children:"Matrix A"}),jsxRuntime.jsx(MatrixInput,{matrix:e,onChange:(l,i,p)=>o(e,t,l,i,p)})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("div",{style:{color:"#888",marginBottom:"4px"},children:"Matrix B"}),jsxRuntime.jsx(MatrixInput,{matrix:r,onChange:(l,i,p)=>o(r,n,l,i,p)})]})]}),jsxRuntime.jsx("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginBottom:"12px"},children:c.map(l=>jsxRuntime.jsx("button",{onClick:()=>{try{s(l.fn())}catch(i){s(i.message)}},style:{padding:"8px 12px",backgroundColor:"#1976d2",color:"#fff",border:"none",borderRadius:"4px",cursor:"pointer"},children:l.label},l.label))}),a&&jsxRuntime.jsx("pre",{style:{color:"#fff",fontFamily:"monospace",whiteSpace:"pre-wrap"},children:a})]})}function MatrixInput({matrix:e,onChange:t}){return jsxRuntime.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${e.cols}, 50px)`,gap:"4px"},children:e.data.map((r,n)=>r.map((a,s)=>jsxRuntime.jsx("input",{type:"number",value:a,onChange:o=>t(n,s,o.target.value),style:{width:"100%",padding:"4px",textAlign:"center",backgroundColor:"#3c3c3c",color:"#fff",border:"1px solid #555",borderRadius:"4px"}},`${n}-${s}`)))})}function CalculusMode(){const[e,t]=react.useState("x^2"),[r,n]=react.useState("");return jsxRuntime.jsxs("div",{style:{padding:"12px",backgroundColor:"#252525"},children:[jsxRuntime.jsx("input",{type:"text",value:e,onChange:a=>t(a.target.value),placeholder:"Enter expression (e.g., x^2, sin(x))",style:{width:"100%",padding:"8px",marginBottom:"12px",backgroundColor:"#3c3c3c",color:"#fff",border:"1px solid #555",borderRadius:"4px"}}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginBottom:"12px"},children:[jsxRuntime.jsx("button",{onClick:()=>n(`d/dx(${e}) = ${CalculusOps.symbolicDerivative(e)}`),style:{padding:"8px 12px",backgroundColor:"#4caf50",color:"#fff",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Differentiate"}),jsxRuntime.jsx("button",{onClick:()=>n(`∫(${e})dx = ${CalculusOps.symbolicIntegral(e)}`),style:{padding:"8px 12px",backgroundColor:"#2196f3",color:"#fff",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Integrate"})]}),r&&jsxRuntime.jsx("div",{style:{color:"#fff",fontFamily:"monospace",padding:"8px",backgroundColor:"#1e1e1e",borderRadius:"4px"},children:r})]})}function UnitsMode(){const{service:e}=useCalculator(),[t,r]=react.useState("1"),[n,a]=react.useState("m"),[s,o]=react.useState("ft"),[c,l]=react.useState("Length"),[i,p]=react.useState(""),d=e.getUnitCategories(),h=e.getUnitsByCategory(c),b=()=>{try{const g=e.convertUnits(parseFloat(t),n,s);p(`${t} ${n} = ${e.format(g)} ${s}`)}catch(g){p(g.message)}};return jsxRuntime.jsxs("div",{style:{padding:"12px",backgroundColor:"#252525"},children:[jsxRuntime.jsx("select",{value:c,onChange:g=>{l(g.target.value);const m=e.getUnitsByCategory(g.target.value);m.length>=2&&(a(m[0].symbol),o(m[1].symbol))},style:{width:"100%",padding:"8px",marginBottom:"12px",backgroundColor:"#3c3c3c",color:"#fff",border:"1px solid #555",borderRadius:"4px"},children:d.map(g=>jsxRuntime.jsx("option",{value:g,children:g},g))}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center",marginBottom:"12px"},children:[jsxRuntime.jsx("input",{type:"number",value:t,onChange:g=>r(g.target.value),style:{flex:1,padding:"8px",backgroundColor:"#3c3c3c",color:"#fff",border:"1px solid #555",borderRadius:"4px"}}),jsxRuntime.jsx("select",{value:n,onChange:g=>a(g.target.value),style:{padding:"8px",backgroundColor:"#3c3c3c",color:"#fff",border:"1px solid #555",borderRadius:"4px"},children:h.map(g=>jsxRuntime.jsxs("option",{value:g.symbol,children:[g.name," (",g.symbol,")"]},g.symbol))})]}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center",marginBottom:"12px"},children:[jsxRuntime.jsx("span",{style:{color:"#888"},children:"→"}),jsxRuntime.jsx("select",{value:s,onChange:g=>o(g.target.value),style:{flex:1,padding:"8px",backgroundColor:"#3c3c3c",color:"#fff",border:"1px solid #555",borderRadius:"4px"},children:h.map(g=>jsxRuntime.jsxs("option",{value:g.symbol,children:[g.name," (",g.symbol,")"]},g.symbol))})]}),jsxRuntime.jsx("button",{onClick:b,style:{width:"100%",padding:"12px",backgroundColor:"#ff9f0a",color:"#000",border:"none",borderRadius:"4px",fontSize:"16px",cursor:"pointer"},children:"Convert"}),i&&jsxRuntime.jsx("div",{style:{marginTop:"12px",color:"#fff",fontSize:"18px",textAlign:"center"},children:i})]})}const GeoMath={distance(e,t){return Math.sqrt((t.x-e.x)**2+(t.y-e.y)**2)},midpoint(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}},angle(e,t,r){const n=Math.atan2(e.y-t.y,e.x-t.x);let s=Math.atan2(r.y-t.y,r.x-t.x)-n;return s<0&&(s+=2*Math.PI),s},angleDegrees(e,t,r){return this.angle(e,t,r)*180/Math.PI},closestPointOnLine(e,t,r){const n=t.x-e.x,a=t.y-e.y,s=((r.x-e.x)*n+(r.y-e.y)*a)/(n*n+a*a);return{x:e.x+s*n,y:e.y+s*a}},lineIntersection(e,t,r,n){const a=(e.x-t.x)*(r.y-n.y)-(e.y-t.y)*(r.x-n.x);if(Math.abs(a)<1e-10)return null;const s=((e.x-r.x)*(r.y-n.y)-(e.y-r.y)*(r.x-n.x))/a;return{x:e.x+s*(t.x-e.x),y:e.y+s*(t.y-e.y)}},circleLineIntersection(e,t,r,n){const a=n.x-r.x,s=n.y-r.y,o=r.x-e.x,c=r.y-e.y,l=a*a+s*s,i=2*(o*a+c*s),p=o*o+c*c-t*t,d=i*i-4*l*p;if(d<0)return[];const h=Math.sqrt(d),b=(-i-h)/(2*l),g=(-i+h)/(2*l),m=[];return b>=0&&b<=1&&m.push({x:r.x+b*a,y:r.y+b*s}),g>=0&&g<=1&&Math.abs(g-b)>1e-10&&m.push({x:r.x+g*a,y:r.y+g*s}),m},circleCircleIntersection(e,t,r,n){const a=this.distance(e,r);if(a>t+n||a<Math.abs(t-n)||a===0)return[];const s=(t*t-n*n+a*a)/(2*a),o=Math.sqrt(t*t-s*s),c=e.x+s*(r.x-e.x)/a,l=e.y+s*(r.y-e.y)/a;return[{x:c+o*(r.y-e.y)/a,y:l-o*(r.x-e.x)/a},{x:c-o*(r.y-e.y)/a,y:l+o*(r.x-e.x)/a}]},perpendicularThrough(e,t,r){this.closestPointOnLine(e,t,r);const n=t.x-e.x,a=t.y-e.y;return{p1:r,p2:{x:r.x-a,y:r.y+n}}},parallelThrough(e,t,r){const n=t.x-e.x,a=t.y-e.y;return{p1:r,p2:{x:r.x+n,y:r.y+a}}},angleBisector(e,t,r){const n=Math.atan2(e.y-t.y,e.x-t.x),a=Math.atan2(r.y-t.y,r.x-t.x);let s=(n+a)/2;return Math.abs(a-n)>Math.PI&&(s+=Math.PI),{x:t.x+Math.cos(s),y:t.y+Math.sin(s)}},reflect(e,t,r){const n=this.closestPointOnLine(t,r,e);return{x:2*n.x-e.x,y:2*n.y-e.y}},rotate(e,t,r){const n=Math.cos(r),a=Math.sin(r),s=e.x-t.x,o=e.y-t.y;return{x:t.x+s*n-o*a,y:t.y+s*a+o*n}},translate(e,t,r){return{x:e.x+t,y:e.y+r}},dilate(e,t,r){return{x:t.x+r*(e.x-t.x),y:t.y+r*(e.y-t.y)}},polygonArea(e){let t=0;const r=e.length;for(let n=0;n<r;n++){const a=(n+1)%r;t+=e[n].x*e[a].y,t-=e[a].x*e[n].y}return Math.abs(t)/2},polygonPerimeter(e){let t=0;const r=e.length;for(let n=0;n<r;n++){const a=(n+1)%r;t+=this.distance(e[n],e[a])}return t},circumcenter(e,t,r){const n=2*(e.x*(t.y-r.y)+t.x*(r.y-e.y)+r.x*(e.y-t.y)),a=((e.x**2+e.y**2)*(t.y-r.y)+(t.x**2+t.y**2)*(r.y-e.y)+(r.x**2+r.y**2)*(e.y-t.y))/n,s=((e.x**2+e.y**2)*(r.x-t.x)+(t.x**2+t.y**2)*(e.x-r.x)+(r.x**2+r.y**2)*(t.x-e.x))/n;return{x:a,y:s}},incenter(e,t,r){const n=this.distance(e,t),a=this.distance(t,r),s=this.distance(r,e),o=n+a+s;return{x:(a*e.x+s*t.x+n*r.x)/o,y:(a*e.y+s*t.y+n*r.y)/o}},centroid(e,t,r){return{x:(e.x+t.x+r.x)/3,y:(e.y+t.y+r.y)/3}}};class GeometryService{constructor(){k(this,"elements",new Map);k(this,"nextLabel",1)}addElement(t){const r=this.generateId(),n={...t,id:r};return this.elements.set(r,n),n}getElement(t){return this.elements.get(t)}getPoint(t){const r=this.elements.get(t);return(r==null?void 0:r.type)==="point"?r:void 0}updateElement(t,r){const n=this.elements.get(t);n&&this.elements.set(t,{...n,...r,id:t,type:n.type})}deleteElement(t){var r;this.elements.delete(t);for(const[n,a]of this.elements)(r=a.dependencies)!=null&&r.includes(t)&&this.deleteElement(n)}getAllElements(){return Array.from(this.elements.values())}getElementsByType(t){return Array.from(this.elements.values()).filter(r=>r.type===t)}clear(){this.elements.clear(),this.nextLabel=1}createPoint(t,r,n){return this.addElement({type:"point",x:t,y:r,label:n??this.getNextLabel(),color:{r:0,g:0,b:0},visible:!0,selected:!1,locked:!1,size:6})}createSegment(t,r){return this.addElement({type:"segment",point1Id:t,point2Id:r,label:void 0,color:{r:50,g:50,b:50},visible:!0,selected:!1,locked:!1,width:2,dependencies:[t,r]})}createLine(t,r){return this.addElement({type:"line",point1Id:t,point2Id:r,label:void 0,color:{r:50,g:50,b:200},visible:!0,selected:!1,locked:!1,width:1,dependencies:[t,r]})}createRay(t,r){return this.addElement({type:"ray",originId:t,throughId:r,label:void 0,color:{r:50,g:150,b:50},visible:!0,selected:!1,locked:!1,width:1,dependencies:[t,r]})}createCircle(t,r){return this.addElement({type:"circle",centerId:t,radius:r,label:void 0,color:{r:200,g:50,b:50},visible:!0,selected:!1,locked:!1,width:2,dependencies:[t]})}createPolygon(t){return this.addElement({type:"polygon",pointIds:t,label:void 0,color:{r:100,g:100,b:200},visible:!0,selected:!1,locked:!1,width:2,fill:{r:100,g:100,b:200,a:.2},dependencies:t})}createMidpoint(t,r){const n=this.getPoint(t),a=this.getPoint(r);if(!n||!a)return null;const s=GeoMath.midpoint(n,a),o=this.createPoint(s.x,s.y);return o.dependencies=[t,r],o.color={r:0,g:150,b:0},o}createPerpendicular(t,r,n){const a=this.getPoint(t),s=this.getPoint(r),o=this.getPoint(n);if(!a||!s||!o)return null;const c=GeoMath.perpendicularThrough(a,s,o),l=this.createPoint(c.p2.x,c.p2.y),i=this.createLine(n,l.id);return i.dependencies=[t,r,n],i}createParallel(t,r,n){const a=this.getPoint(t),s=this.getPoint(r),o=this.getPoint(n);if(!a||!s||!o)return null;const c=GeoMath.parallelThrough(a,s,o),l=this.createPoint(c.p2.x,c.p2.y),i=this.createLine(n,l.id);return i.dependencies=[t,r,n],i}createIntersection(t,r){const n=this.elements.get(t),a=this.elements.get(r);if(!n||!a)return[];const s=[],o=i=>{if(i.type==="line"||i.type==="segment"||i.type==="ray"){const p=i,d=this.getPoint(p.point1Id??p.originId),h=this.getPoint(p.point2Id??p.throughId);if(d&&h)return[d,h]}return null},c=o(n),l=o(a);if(c&&l){const i=GeoMath.lineIntersection(c[0],c[1],l[0],l[1]);if(i){const p=this.createPoint(i.x,i.y);p.dependencies=[t,r],p.color={r:255,g:0,b:0},s.push(p)}}if(n.type==="circle"&&l){const i=n,p=this.getPoint(i.centerId);if(p){const d=GeoMath.circleLineIntersection(p,i.radius,l[0],l[1]);for(const h of d){const b=this.createPoint(h.x,h.y);b.dependencies=[t,r],b.color={r:255,g:0,b:0},s.push(b)}}}if(n.type==="circle"&&a.type==="circle"){const i=n,p=a,d=this.getPoint(i.centerId),h=this.getPoint(p.centerId);if(d&&h){const b=GeoMath.circleCircleIntersection(d,i.radius,h,p.radius);for(const g of b){const m=this.createPoint(g.x,g.y);m.dependencies=[t,r],m.color={r:255,g:0,b:0},s.push(m)}}}return s}calculateMeasurement(t,r){switch(t){case"distance":{const n=this.getPoint(r[0]),a=this.getPoint(r[1]);if(n&&a)return GeoMath.distance(n,a);break}case"angle":{const n=this.getPoint(r[0]),a=this.getPoint(r[1]),s=this.getPoint(r[2]);if(n&&a&&s)return GeoMath.angleDegrees(n,a,s);break}case"area":case"perimeter":{const n=this.elements.get(r[0]);if((n==null?void 0:n.type)==="polygon"){const a=n.pointIds.map(s=>this.getPoint(s)).filter(Boolean);return t==="area"?GeoMath.polygonArea(a):GeoMath.polygonPerimeter(a)}break}}return 0}exportSVG(t,r,n){const a=[`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${r}" viewBox="0 0 ${t} ${r}">`];a.push(`<rect width="100%" height="100%" fill="rgb(${n.backgroundColor.r},${n.backgroundColor.g},${n.backgroundColor.b})"/>`);const s=(o,c)=>({x:t/2+(o-n.centerX)*n.scale,y:r/2-(c-n.centerY)*n.scale});if(n.showGrid){a.push('<g stroke="#ddd" stroke-width="0.5">');for(let o=Math.floor(-t/2/n.scale+n.centerX);o<=t/2/n.scale+n.centerX;o+=n.gridSpacing){const c=s(o,0);a.push(`<line x1="${c.x}" y1="0" x2="${c.x}" y2="${r}"/>`)}for(let o=Math.floor(-r/2/n.scale+n.centerY);o<=r/2/n.scale+n.centerY;o+=n.gridSpacing){const c=s(0,o);a.push(`<line x1="0" y1="${c.y}" x2="${t}" y2="${c.y}"/>`)}a.push("</g>")}if(n.showAxes){const o=s(0,0);a.push('<g stroke="#333" stroke-width="1">'),a.push(`<line x1="0" y1="${o.y}" x2="${t}" y2="${o.y}"/>`),a.push(`<line x1="${o.x}" y1="0" x2="${o.x}" y2="${r}"/>`),a.push("</g>")}for(const o of this.getAllElements()){if(!o.visible)continue;const c=`rgb(${o.color.r},${o.color.g},${o.color.b})`;switch(o.type){case"point":{const l=s(o.x,o.y);a.push(`<circle cx="${l.x}" cy="${l.y}" r="${o.size}" fill="${c}"/>`),o.label&&a.push(`<text x="${l.x+8}" y="${l.y-8}" font-size="12">${o.label}</text>`);break}case"segment":{const l=this.getPoint(o.point1Id),i=this.getPoint(o.point2Id);if(l&&i){const p=s(l.x,l.y),d=s(i.x,i.y);a.push(`<line x1="${p.x}" y1="${p.y}" x2="${d.x}" y2="${d.y}" stroke="${c}" stroke-width="${o.width}"/>`)}break}case"circle":{const l=this.getPoint(o.centerId);if(l){const i=s(l.x,l.y),p=o.radius*n.scale,d=o.fill?`rgba(${o.fill.r},${o.fill.g},${o.fill.b},${o.fill.a??.2})`:"none";a.push(`<circle cx="${i.x}" cy="${i.y}" r="${p}" fill="${d}" stroke="${c}" stroke-width="${o.width}"/>`)}break}case"polygon":{const l=o.pointIds.map(i=>this.getPoint(i)).filter(Boolean);if(l.length>0){const p=l.map(h=>s(h.x,h.y)).map((h,b)=>`${b===0?"M":"L"}${h.x},${h.y}`).join(" ")+" Z",d=o.fill?`rgba(${o.fill.r},${o.fill.g},${o.fill.b},${o.fill.a??.2})`:"none";a.push(`<path d="${p}" fill="${d}" stroke="${c}" stroke-width="${o.width}"/>`)}break}}}return a.push("</svg>"),a.join(`
5
- `)}generateId(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}getNextLabel(){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZ",r=this.nextLabel-1;return this.nextLabel++,r<26?t[r]:t[r%26]+Math.floor(r/26)}}function createGeometryService(){return new GeometryService}const GeometryContext=react.createContext(null);function useGeometry(){const e=react.useContext(GeometryContext);if(!e)throw new Error("useGeometry must be used within GeometryProvider");return e}const styles={container:{display:"flex",height:"100%",fontFamily:"'Inter', sans-serif",fontSize:"14px"},toolbar:{width:"50px",backgroundColor:"#f5f5f5",borderRight:"1px solid #e0e0e0",display:"flex",flexDirection:"column",padding:"8px 4px",gap:"4px"},toolButton:{width:"40px",height:"40px",border:"none",borderRadius:"4px",backgroundColor:"transparent",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"18px"},main:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},canvas:{flex:1,cursor:"crosshair"},statusBar:{height:"30px",backgroundColor:"#f5f5f5",borderTop:"1px solid #e0e0e0",padding:"0 12px",display:"flex",alignItems:"center",fontSize:"12px",color:"#666"}};function NiceGeometry({service:e,width:t=800,height:r=600,className:n,style:a}){const[s,o]=react.useState([]),[c,l]=react.useState("point"),[i,p]=react.useState([]),[d,h]=react.useState({centerX:0,centerY:0,scale:40,showGrid:!0,showAxes:!0,gridSpacing:1,snapToGrid:!0,snapToPoints:!0,backgroundColor:{r:255,g:255,b:255}}),b=react.useCallback(()=>{o(e.getAllElements())},[e]),g=react.useCallback(y=>{h(x=>({...x,...y}))},[]);react.useEffect(()=>{b()},[b]);const m={service:e,elements:s,tool:c,setTool:l,view:d,setView:g,selectedIds:i,setSelectedIds:p,refresh:b};return jsxRuntime.jsx(GeometryContext.Provider,{value:m,children:jsxRuntime.jsxs("div",{className:n,style:{...styles.container,...a},children:[jsxRuntime.jsx(Toolbar,{}),jsxRuntime.jsxs("div",{style:styles.main,children:[jsxRuntime.jsx(Canvas,{width:t,height:r}),jsxRuntime.jsx(StatusBar,{width:t,height:r})]})]})})}function Toolbar(){const{tool:e,setTool:t}=useGeometry(),r=[{id:"select",icon:"⬚",title:"Select"},{id:"point",icon:"•",title:"Point"},{id:"segment",icon:"—",title:"Segment"},{id:"line",icon:"↔",title:"Line"},{id:"ray",icon:"→",title:"Ray"},{id:"circle",icon:"○",title:"Circle"},{id:"polygon",icon:"△",title:"Polygon"},{id:"perpendicular",icon:"⊥",title:"Perpendicular"},{id:"parallel",icon:"∥",title:"Parallel"},{id:"midpoint",icon:"⊙",title:"Midpoint"},{id:"bisector",icon:"∠",title:"Angle Bisector"},{id:"intersection",icon:"✕",title:"Intersection"},{id:"reflect",icon:"⇄",title:"Reflect"},{id:"rotate",icon:"↻",title:"Rotate"},{id:"measure",icon:"📏",title:"Measure"}];return jsxRuntime.jsx("div",{style:styles.toolbar,children:r.map(n=>jsxRuntime.jsx("button",{onClick:()=>t(n.id),title:n.title,style:{...styles.toolButton,backgroundColor:e===n.id?"#1976d2":"transparent",color:e===n.id?"#fff":"#333"},children:n.icon},n.id))})}function Canvas({width:e,height:t}){const r=react.useRef(null),{service:n,elements:a,tool:s,view:o,selectedIds:c,setSelectedIds:l,refresh:i}=useGeometry(),[p,d]=react.useState([]),h=react.useCallback((y,x)=>{const u=(y-e/2)/o.scale+o.centerX,w=-(x-t/2)/o.scale+o.centerY;return o.snapToGrid?{x:Math.round(u/o.gridSpacing)*o.gridSpacing,y:Math.round(w/o.gridSpacing)*o.gridSpacing}:{x:u,y:w}},[e,t,o]),b=react.useCallback((y,x)=>({x:e/2+(y-o.centerX)*o.scale,y:t/2-(x-o.centerY)*o.scale}),[e,t,o]),g=react.useCallback(y=>{var w;const x=(w=r.current)==null?void 0:w.getBoundingClientRect();if(!x)return;const u=h(y.clientX-x.left,y.clientY-x.top);switch(s){case"point":{n.createPoint(u.x,u.y),i();break}case"segment":case"line":case"ray":{const j=m(u);if(j)d(f=>{const v=[...f,j.id];return v.length===2?(s==="segment"?n.createSegment(v[0],v[1]):s==="line"?n.createLine(v[0],v[1]):s==="ray"&&n.createRay(v[0],v[1]),i(),[]):v});else{const f=n.createPoint(u.x,u.y);d(v=>{const R=[...v,f.id];return R.length===2?(s==="segment"?n.createSegment(R[0],R[1]):s==="line"?n.createLine(R[0],R[1]):s==="ray"&&n.createRay(R[0],R[1]),i(),[]):R}),i()}break}case"circle":{const j=m(u);if(j)d(f=>{if(f.length===0)return[j.id];const v=n.getPoint(f[0]);if(v){const R=GeoMath.distance(v,u);n.createCircle(f[0],R),i()}return[]});else if(p.length===1){const f=n.getPoint(p[0]);if(f){const v=GeoMath.distance(f,u);n.createCircle(p[0],v),i(),d([])}}else{const f=n.createPoint(u.x,u.y);d([f.id]),i()}break}case"midpoint":{const j=m(u);j&&d(f=>{const v=[...f,j.id];return v.length===2?(n.createMidpoint(v[0],v[1]),i(),[]):v});break}case"select":{const j=m(u);l(j?[j.id]:[]);break}}},[s,n,i,h,p,l]),m=y=>{for(const u of a)if(u.type==="point"&&GeoMath.distance(u,y)<.5)return u};return react.useEffect(()=>{const y=r.current,x=y==null?void 0:y.getContext("2d");if(!(!y||!x)){if(x.fillStyle=`rgb(${o.backgroundColor.r},${o.backgroundColor.g},${o.backgroundColor.b})`,x.fillRect(0,0,e,t),o.showGrid){x.strokeStyle="#e0e0e0",x.lineWidth=.5;const u=o.gridSpacing*o.scale,w=(e/2-o.centerX*o.scale)%u,j=(t/2+o.centerY*o.scale)%u;for(let f=w;f<e;f+=u)x.beginPath(),x.moveTo(f,0),x.lineTo(f,t),x.stroke();for(let f=j;f<t;f+=u)x.beginPath(),x.moveTo(0,f),x.lineTo(e,f),x.stroke()}if(o.showAxes){const u=b(0,0);x.strokeStyle="#333",x.lineWidth=1,x.beginPath(),x.moveTo(0,u.y),x.lineTo(e,u.y),x.stroke(),x.beginPath(),x.moveTo(u.x,0),x.lineTo(u.x,t),x.stroke()}for(const u of a){if(!u.visible)continue;const w=`rgb(${u.color.r},${u.color.g},${u.color.b})`,j=c.includes(u.id);switch(u.type){case"point":{const f=b(u.x,u.y);x.beginPath(),x.arc(f.x,f.y,j?u.size+2:u.size,0,2*Math.PI),x.fillStyle=j?"#1976d2":w,x.fill(),u.label&&(x.fillStyle="#333",x.font="12px sans-serif",x.fillText(u.label,f.x+8,f.y-8));break}case"segment":{const f=n.getPoint(u.point1Id),v=n.getPoint(u.point2Id);if(f&&v){const R=b(f.x,f.y),C=b(v.x,v.y);x.strokeStyle=w,x.lineWidth=u.width,x.beginPath(),x.moveTo(R.x,R.y),x.lineTo(C.x,C.y),x.stroke()}break}case"line":{const f=n.getPoint(u.point1Id),v=n.getPoint(u.point2Id);if(f&&v){const R=v.x-f.x,C=v.y-f.y,M=-1e3,S=1e3,$=b(f.x+M*R,f.y+M*C),P=b(f.x+S*R,f.y+S*C);x.strokeStyle=w,x.lineWidth=u.width,x.beginPath(),x.moveTo($.x,$.y),x.lineTo(P.x,P.y),x.stroke()}break}case"circle":{const f=n.getPoint(u.centerId);if(f){const v=b(f.x,f.y),R=u.radius*o.scale;x.beginPath(),x.arc(v.x,v.y,R,0,2*Math.PI),u.fill&&(x.fillStyle=`rgba(${u.fill.r},${u.fill.g},${u.fill.b},${u.fill.a??.2})`,x.fill()),x.strokeStyle=w,x.lineWidth=u.width,x.stroke()}break}case"polygon":{const f=u.pointIds.map(v=>n.getPoint(v)).filter(Boolean);if(f.length>0){x.beginPath();const v=b(f[0].x,f[0].y);x.moveTo(v.x,v.y);for(let R=1;R<f.length;R++){const C=b(f[R].x,f[R].y);x.lineTo(C.x,C.y)}x.closePath(),u.fill&&(x.fillStyle=`rgba(${u.fill.r},${u.fill.g},${u.fill.b},${u.fill.a??.2})`,x.fill()),x.strokeStyle=w,x.lineWidth=u.width,x.stroke()}break}}}if(p.length>0){x.fillStyle="rgba(25, 118, 210, 0.3)";for(const u of p){const w=n.getPoint(u);if(w){const j=b(w.x,w.y);x.beginPath(),x.arc(j.x,j.y,12,0,2*Math.PI),x.fill()}}}}},[a,o,e,t,c,p,n,b]),jsxRuntime.jsx("canvas",{ref:r,width:e,height:t,style:styles.canvas,onClick:g})}function StatusBar({width:e,height:t}){const{tool:r,elements:n,view:a,service:s}=useGeometry(),[o,c]=react.useState(null),l={select:"Select",point:"Point",line:"Line",ray:"Ray",segment:"Segment",circle:"Circle",arc:"Arc",polygon:"Polygon",angle:"Angle",perpendicular:"Perpendicular",parallel:"Parallel",bisector:"Angle Bisector",midpoint:"Midpoint",tangent:"Tangent",intersection:"Intersection",reflect:"Reflect",rotate:"Rotate",translate:"Translate",dilate:"Dilate",measure:"Measure",text:"Text"},i=n.filter(p=>p.type==="point").length;return jsxRuntime.jsxs("div",{style:styles.statusBar,children:[jsxRuntime.jsxs("span",{children:["Tool: ",l[r]]}),jsxRuntime.jsx("span",{style:{margin:"0 16px"},children:"|"}),jsxRuntime.jsxs("span",{children:["Objects: ",n.length]}),jsxRuntime.jsx("span",{style:{margin:"0 16px"},children:"|"}),jsxRuntime.jsxs("span",{children:["Points: ",i]}),jsxRuntime.jsx("span",{style:{margin:"0 16px"},children:"|"}),jsxRuntime.jsxs("span",{children:["Scale: ",a.scale.toFixed(1),"x"]})]})}exports.CalculatorService=CalculatorService;exports.CalculusOps=CalculusOps;exports.EQUATION_TEMPLATES=EQUATION_TEMPLATES;exports.ExpressionParser=ExpressionParser;exports.FUNCTION_PRESETS=FUNCTION_PRESETS;exports.GeoMath=GeoMath;exports.GeometryService=GeometryService;exports.GraphService=GraphService;exports.MATH_SYMBOLS=MATH_SYMBOLS;exports.MathEditorService=MathEditorService;exports.MatrixOps=MatrixOps;exports.NiceCalculator=NiceCalculator;exports.NiceGeometry=NiceGeometry;exports.NiceGraphPlotter=NiceGraphPlotter;exports.NiceMathEditor=NiceMathEditor;exports.createCalculatorService=createCalculatorService;exports.createGeometryService=createGeometryService;exports.createGraphService=createGraphService;exports.createMathEditorService=createMathEditorService;exports.getSymbolsByCategory=getSymbolsByCategory;exports.recognizeHandwriting=recognizeHandwriting;exports.useCalculator=useCalculator;exports.useGeometry=useGeometry;exports.useGraph=useGraph;exports.useMathEditor=useMathEditor;
1
+ "use strict";var B=Object.defineProperty;var T=(e,t,r)=>t in e?B(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var k=(e,t,r)=>T(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const jsxRuntime=require("react/jsx-runtime"),react=require("react"),MATH_SYMBOLS=[{name:"alpha",latex:"\\alpha",category:"greek",preview:"α"},{name:"beta",latex:"\\beta",category:"greek",preview:"β"},{name:"gamma",latex:"\\gamma",category:"greek",preview:"γ"},{name:"delta",latex:"\\delta",category:"greek",preview:"δ"},{name:"epsilon",latex:"\\epsilon",category:"greek",preview:"ε"},{name:"zeta",latex:"\\zeta",category:"greek",preview:"ζ"},{name:"eta",latex:"\\eta",category:"greek",preview:"η"},{name:"theta",latex:"\\theta",category:"greek",preview:"θ"},{name:"iota",latex:"\\iota",category:"greek",preview:"ι"},{name:"kappa",latex:"\\kappa",category:"greek",preview:"κ"},{name:"lambda",latex:"\\lambda",category:"greek",preview:"λ"},{name:"mu",latex:"\\mu",category:"greek",preview:"μ"},{name:"nu",latex:"\\nu",category:"greek",preview:"ν"},{name:"xi",latex:"\\xi",category:"greek",preview:"ξ"},{name:"pi",latex:"\\pi",category:"greek",preview:"π"},{name:"rho",latex:"\\rho",category:"greek",preview:"ρ"},{name:"sigma",latex:"\\sigma",category:"greek",preview:"σ"},{name:"tau",latex:"\\tau",category:"greek",preview:"τ"},{name:"upsilon",latex:"\\upsilon",category:"greek",preview:"υ"},{name:"phi",latex:"\\phi",category:"greek",preview:"φ"},{name:"chi",latex:"\\chi",category:"greek",preview:"χ"},{name:"psi",latex:"\\psi",category:"greek",preview:"ψ"},{name:"omega",latex:"\\omega",category:"greek",preview:"ω"},{name:"Gamma",latex:"\\Gamma",category:"greek",preview:"Γ"},{name:"Delta",latex:"\\Delta",category:"greek",preview:"Δ"},{name:"Theta",latex:"\\Theta",category:"greek",preview:"Θ"},{name:"Lambda",latex:"\\Lambda",category:"greek",preview:"Λ"},{name:"Xi",latex:"\\Xi",category:"greek",preview:"Ξ"},{name:"Pi",latex:"\\Pi",category:"greek",preview:"Π"},{name:"Sigma",latex:"\\Sigma",category:"greek",preview:"Σ"},{name:"Phi",latex:"\\Phi",category:"greek",preview:"Φ"},{name:"Psi",latex:"\\Psi",category:"greek",preview:"Ψ"},{name:"Omega",latex:"\\Omega",category:"greek",preview:"Ω"},{name:"plus/minus",latex:"\\pm",category:"operators",preview:"±"},{name:"minus/plus",latex:"\\mp",category:"operators",preview:"∓"},{name:"times",latex:"\\times",category:"operators",preview:"×"},{name:"divide",latex:"\\div",category:"operators",preview:"÷"},{name:"cdot",latex:"\\cdot",category:"operators",preview:"·"},{name:"star",latex:"\\star",category:"operators",preview:"⋆"},{name:"circle",latex:"\\circ",category:"operators",preview:"∘"},{name:"bullet",latex:"\\bullet",category:"operators",preview:"•"},{name:"oplus",latex:"\\oplus",category:"operators",preview:"⊕"},{name:"otimes",latex:"\\otimes",category:"operators",preview:"⊗"},{name:"odot",latex:"\\odot",category:"operators",preview:"⊙"},{name:"less than",latex:"<",category:"relations",preview:"<"},{name:"greater than",latex:">",category:"relations",preview:">"},{name:"less or equal",latex:"\\leq",category:"relations",preview:"≤"},{name:"greater or equal",latex:"\\geq",category:"relations",preview:"≥"},{name:"not equal",latex:"\\neq",category:"relations",preview:"≠"},{name:"approximately",latex:"\\approx",category:"relations",preview:"≈"},{name:"equivalent",latex:"\\equiv",category:"relations",preview:"≡"},{name:"similar",latex:"\\sim",category:"relations",preview:"∼"},{name:"proportional",latex:"\\propto",category:"relations",preview:"∝"},{name:"perpendicular",latex:"\\perp",category:"relations",preview:"⊥"},{name:"parallel",latex:"\\parallel",category:"relations",preview:"∥"},{name:"right arrow",latex:"\\rightarrow",category:"arrows",preview:"→"},{name:"left arrow",latex:"\\leftarrow",category:"arrows",preview:"←"},{name:"double right",latex:"\\Rightarrow",category:"arrows",preview:"⇒"},{name:"double left",latex:"\\Leftarrow",category:"arrows",preview:"⇐"},{name:"iff",latex:"\\Leftrightarrow",category:"arrows",preview:"⇔"},{name:"up arrow",latex:"\\uparrow",category:"arrows",preview:"↑"},{name:"down arrow",latex:"\\downarrow",category:"arrows",preview:"↓"},{name:"maps to",latex:"\\mapsto",category:"arrows",preview:"↦"},{name:"sine",latex:"\\sin",category:"functions",preview:"sin"},{name:"cosine",latex:"\\cos",category:"functions",preview:"cos"},{name:"tangent",latex:"\\tan",category:"functions",preview:"tan"},{name:"cotangent",latex:"\\cot",category:"functions",preview:"cot"},{name:"arcsine",latex:"\\arcsin",category:"functions",preview:"arcsin"},{name:"arccosine",latex:"\\arccos",category:"functions",preview:"arccos"},{name:"arctangent",latex:"\\arctan",category:"functions",preview:"arctan"},{name:"logarithm",latex:"\\log",category:"functions",preview:"log"},{name:"natural log",latex:"\\ln",category:"functions",preview:"ln"},{name:"exponential",latex:"\\exp",category:"functions",preview:"exp"},{name:"limit",latex:"\\lim",category:"functions",preview:"lim"},{name:"supremum",latex:"\\sup",category:"functions",preview:"sup"},{name:"infimum",latex:"\\inf",category:"functions",preview:"inf"},{name:"maximum",latex:"\\max",category:"functions",preview:"max"},{name:"minimum",latex:"\\min",category:"functions",preview:"min"},{name:"hat",latex:"\\hat{x}",category:"accents",preview:"x̂"},{name:"bar",latex:"\\bar{x}",category:"accents",preview:"x̄"},{name:"vector",latex:"\\vec{x}",category:"accents",preview:"x⃗"},{name:"dot",latex:"\\dot{x}",category:"accents",preview:"ẋ"},{name:"double dot",latex:"\\ddot{x}",category:"accents",preview:"ẍ"},{name:"tilde",latex:"\\tilde{x}",category:"accents",preview:"x̃"},{name:"parentheses",latex:"\\left( \\right)",category:"delimiters",preview:"( )"},{name:"brackets",latex:"\\left[ \\right]",category:"delimiters",preview:"[ ]"},{name:"braces",latex:"\\left\\{ \\right\\}",category:"delimiters",preview:"{ }"},{name:"angle brackets",latex:"\\left\\langle \\right\\rangle",category:"delimiters",preview:"⟨ ⟩"},{name:"ceiling",latex:"\\left\\lceil \\right\\rceil",category:"delimiters",preview:"⌈ ⌉"},{name:"floor",latex:"\\left\\lfloor \\right\\rfloor",category:"delimiters",preview:"⌊ ⌋"},{name:"absolute",latex:"\\left| \\right|",category:"delimiters",preview:"| |"},{name:"norm",latex:"\\left\\| \\right\\|",category:"delimiters",preview:"‖ ‖"},{name:"element of",latex:"\\in",category:"sets",preview:"∈"},{name:"not element",latex:"\\notin",category:"sets",preview:"∉"},{name:"contains",latex:"\\ni",category:"sets",preview:"∋"},{name:"subset",latex:"\\subset",category:"sets",preview:"⊂"},{name:"superset",latex:"\\supset",category:"sets",preview:"⊃"},{name:"subset or equal",latex:"\\subseteq",category:"sets",preview:"⊆"},{name:"union",latex:"\\cup",category:"sets",preview:"∪"},{name:"intersection",latex:"\\cap",category:"sets",preview:"∩"},{name:"set minus",latex:"\\setminus",category:"sets",preview:"∖"},{name:"empty set",latex:"\\emptyset",category:"sets",preview:"∅"},{name:"naturals",latex:"\\mathbb{N}",category:"sets",preview:"ℕ"},{name:"integers",latex:"\\mathbb{Z}",category:"sets",preview:"ℤ"},{name:"rationals",latex:"\\mathbb{Q}",category:"sets",preview:"ℚ"},{name:"reals",latex:"\\mathbb{R}",category:"sets",preview:"ℝ"},{name:"complex",latex:"\\mathbb{C}",category:"sets",preview:"ℂ"},{name:"for all",latex:"\\forall",category:"logic",preview:"∀"},{name:"exists",latex:"\\exists",category:"logic",preview:"∃"},{name:"not exists",latex:"\\nexists",category:"logic",preview:"∄"},{name:"and",latex:"\\land",category:"logic",preview:"∧"},{name:"or",latex:"\\lor",category:"logic",preview:"∨"},{name:"not",latex:"\\neg",category:"logic",preview:"¬"},{name:"therefore",latex:"\\therefore",category:"logic",preview:"∴"},{name:"because",latex:"\\because",category:"logic",preview:"∵"},{name:"integral",latex:"\\int",category:"calculus",preview:"∫"},{name:"double integral",latex:"\\iint",category:"calculus",preview:"∬"},{name:"triple integral",latex:"\\iiint",category:"calculus",preview:"∭"},{name:"contour integral",latex:"\\oint",category:"calculus",preview:"∮"},{name:"partial",latex:"\\partial",category:"calculus",preview:"∂"},{name:"nabla/gradient",latex:"\\nabla",category:"calculus",preview:"∇"},{name:"summation",latex:"\\sum",category:"calculus",preview:"Σ"},{name:"product",latex:"\\prod",category:"calculus",preview:"Π"},{name:"infinity",latex:"\\infty",category:"calculus",preview:"∞"},{name:"matrix",latex:"\\begin{pmatrix} a & b \\\\ c & d \\end{pmatrix}",category:"matrices",preview:"[ ]"},{name:"determinant",latex:"\\begin{vmatrix} a & b \\\\ c & d \\end{vmatrix}",category:"matrices",preview:"| |"},{name:"bracket matrix",latex:"\\begin{bmatrix} a & b \\\\ c & d \\end{bmatrix}",category:"matrices",preview:"[[ ]]"},{name:"cases",latex:"\\begin{cases} a & \\text{if } x > 0 \\\\ b & \\text{otherwise} \\end{cases}",category:"matrices",preview:"{ }"}];function getSymbolsByCategory(e){return MATH_SYMBOLS.filter(t=>t.category===e)}const EQUATION_TEMPLATES=[{name:"Fraction",latex:"\\frac{a}{b}",category:"basic"},{name:"Square root",latex:"\\sqrt{x}",category:"basic"},{name:"Nth root",latex:"\\sqrt[n]{x}",category:"basic"},{name:"Power",latex:"x^{n}",category:"basic"},{name:"Subscript",latex:"x_{n}",category:"basic"},{name:"Both",latex:"x_{i}^{n}",category:"basic"},{name:"Derivative",latex:"\\frac{d}{dx}f(x)",category:"calculus"},{name:"Partial derivative",latex:"\\frac{\\partial f}{\\partial x}",category:"calculus"},{name:"Definite integral",latex:"\\int_{a}^{b} f(x)\\,dx",category:"calculus"},{name:"Indefinite integral",latex:"\\int f(x)\\,dx",category:"calculus"},{name:"Limit",latex:"\\lim_{x \\to a} f(x)",category:"calculus"},{name:"Summation",latex:"\\sum_{i=1}^{n} a_i",category:"calculus"},{name:"Product",latex:"\\prod_{i=1}^{n} a_i",category:"calculus"},{name:"Quadratic formula",latex:"x = \\frac{-b \\pm \\sqrt{b^2-4ac}}{2a}",category:"algebra"},{name:"Binomial",latex:"\\binom{n}{k} = \\frac{n!}{k!(n-k)!}",category:"algebra"},{name:"System of equations",latex:"\\begin{cases} ax + by = c \\\\ dx + ey = f \\end{cases}",category:"algebra"},{name:"Pythagorean",latex:"a^2 + b^2 = c^2",category:"geometry"},{name:"Circle area",latex:"A = \\pi r^2",category:"geometry"},{name:"Sphere volume",latex:"V = \\frac{4}{3}\\pi r^3",category:"geometry"},{name:"Euler's identity",latex:"e^{i\\pi} + 1 = 0",category:"geometry"},{name:"Mean",latex:"\\bar{x} = \\frac{1}{n}\\sum_{i=1}^{n} x_i",category:"statistics"},{name:"Variance",latex:"\\sigma^2 = \\frac{1}{n}\\sum_{i=1}^{n}(x_i - \\bar{x})^2",category:"statistics"},{name:"Normal distribution",latex:"f(x) = \\frac{1}{\\sigma\\sqrt{2\\pi}}e^{-\\frac{(x-\\mu)^2}{2\\sigma^2}}",category:"statistics"},{name:"Einstein mass-energy",latex:"E = mc^2",category:"physics"},{name:"Newton's second law",latex:"F = ma",category:"physics"},{name:"Schrödinger equation",latex:"i\\hbar\\frac{\\partial}{\\partial t}\\Psi = \\hat{H}\\Psi",category:"physics"},{name:"Maxwell's equations",latex:"\\nabla \\cdot \\vec{E} = \\frac{\\rho}{\\epsilon_0}",category:"physics"}];class MathEditorService{constructor(t={}){k(this,"equations",new Map);k(this,"config");k(this,"nextNumber");this.config={enableNumbering:t.enableNumbering??!0,startNumber:t.startNumber??1,renderDelay:t.renderDelay??100},this.nextNumber=this.config.startNumber}createEquation(t,r){const a={id:this.generateId(),latex:t,label:r,number:this.config.enableNumbering?this.nextNumber++:void 0,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return this.equations.set(a.id,a),a}updateEquation(t,r,a){const n=this.equations.get(t);if(!n)throw new Error(`Equation not found: ${t}`);const o={...n,latex:r,label:a??n.label,updatedAt:new Date().toISOString()};return this.equations.set(t,o),o}deleteEquation(t){this.equations.delete(t)}getEquation(t){return this.equations.get(t)}listEquations(){return Array.from(this.equations.values()).sort((t,r)=>new Date(t.createdAt).getTime()-new Date(r.createdAt).getTime())}exportToLatex(){const t=["\\documentclass{article}","\\usepackage{amsmath}","\\usepackage{amssymb}","","\\begin{document}",""];for(const r of this.listEquations())r.number!==void 0?(t.push("\\begin{equation}"),r.label&&t.push(`\\label{${r.label}}`),t.push(r.latex),t.push("\\end{equation}")):(t.push("\\["),t.push(r.latex),t.push("\\]")),t.push("");return t.push("\\end{document}"),t.join(`
2
+ `)}parseLatex(t){const r=[],a=/\\\[([\s\S]*?)\\\]/g;let n;for(;(n=a.exec(t))!==null;)r.push(this.createEquation(n[1].trim()));const o=/\\begin\{equation\}([\s\S]*?)\\end\{equation\}/g;for(;(n=o.exec(t))!==null;){const s=n[1].match(/\\label\{([^}]+)\}/),l=n[1].replace(/\\label\{[^}]+\}/,"").trim();r.push(this.createEquation(l,s==null?void 0:s[1]))}return r}generateId(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}}function createMathEditorService(e){return new MathEditorService(e)}async function recognizeHandwriting(e){return await new Promise(r=>setTimeout(r,500)),{latex:e.reduce((r,a)=>r+a.points.length,0)>50?"\\sqrt{x^2 + y^2}":"x",confidence:.85,alternatives:["x","X","\\times"]}}const MathEditorContext=react.createContext(null);function useMathEditor(){const e=react.useContext(MathEditorContext);if(!e)throw new Error("useMathEditor must be used within MathEditorProvider");return e}const styles$3={container:{display:"flex",flexDirection:"column",height:"100%",fontFamily:"'Inter', sans-serif",fontSize:"14px"},toolbar:{display:"flex",gap:"8px",padding:"8px",borderBottom:"1px solid var(--nice-border, #e0e0e0)",backgroundColor:"var(--nice-bg-secondary, #fafafa)",flexWrap:"wrap",alignItems:"center"},main:{display:"flex",flex:1,overflow:"hidden"},sidebar:{width:"200px",borderRight:"1px solid var(--nice-border, #e0e0e0)",overflow:"auto",backgroundColor:"var(--nice-bg-secondary, #f5f5f5)"},editor:{flex:1,display:"flex",flexDirection:"column",padding:"16px",overflow:"auto"},input:{width:"100%",minHeight:"100px",padding:"12px",fontFamily:"'JetBrains Mono', monospace",fontSize:"14px",border:"1px solid var(--nice-border, #ddd)",borderRadius:"4px",resize:"vertical"},preview:{marginTop:"16px",padding:"20px",backgroundColor:"var(--nice-bg, #fff)",border:"1px solid var(--nice-border, #e0e0e0)",borderRadius:"4px",minHeight:"60px",fontSize:"20px",textAlign:"center"},button:{padding:"6px 12px",backgroundColor:"var(--nice-primary-hover, #1976d2)",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"13px"},symbolGrid:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:"4px",padding:"8px"},symbolButton:{padding:"8px",border:"1px solid var(--nice-border, #ddd)",borderRadius:"4px",backgroundColor:"var(--nice-bg, #fff)",cursor:"pointer",fontSize:"16px",textAlign:"center"},categoryHeader:{padding:"8px 12px",backgroundColor:"var(--nice-border, #e0e0e0)",fontWeight:600,fontSize:"12px",textTransform:"uppercase"},canvas:{width:"100%",height:"200px",border:"1px solid var(--nice-border, #ddd)",borderRadius:"4px",backgroundColor:"var(--nice-bg, #fff)",cursor:"crosshair"}};function NiceMathEditor({service:e,initialLatex:t="",onChange:r,className:a,style:n}){const[o,s]=react.useState(t),[l,c]=react.useState("input"),i=react.useRef(null),p=react.useCallback(g=>{s(g),r==null||r(g)},[r]),d=react.useCallback(g=>{const m=i.current;if(!m){p(o+g);return}const y=m.selectionStart,x=m.selectionEnd,u=o.slice(0,y)+g+o.slice(x);p(u),setTimeout(()=>{m.focus(),m.selectionStart=m.selectionEnd=y+g.length},0)},[o,p]),h=react.useCallback(g=>{d(g.latex)},[d]),b={service:e,latex:o,setLatex:p,insertSymbol:d,insertTemplate:h,mode:l,setMode:c};return jsxRuntime.jsx(MathEditorContext.Provider,{value:b,children:jsxRuntime.jsxs("div",{className:a,style:{...styles$3.container,...n},children:[jsxRuntime.jsx(Toolbar$1,{}),jsxRuntime.jsxs("div",{style:styles$3.main,children:[jsxRuntime.jsx(SymbolPalette,{}),jsxRuntime.jsx("div",{style:styles$3.editor,children:l==="input"?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("textarea",{ref:i,value:o,onChange:g=>p(g.target.value),placeholder:"Enter LaTeX equation...",style:styles$3.input}),jsxRuntime.jsx(LatexPreview,{latex:o})]}):jsxRuntime.jsx(HandwritingCanvas,{})})]})]})})}function Toolbar$1(){const{mode:e,setMode:t,latex:r,insertTemplate:a}=useMathEditor(),[n,o]=react.useState(!1);return jsxRuntime.jsxs("div",{style:styles$3.toolbar,children:[jsxRuntime.jsx("button",{onClick:()=>t("input"),style:{...styles$3.button,backgroundColor:e==="input"?"var(--nice-primary-hover, #1976d2)":"var(--nice-text-secondary, #9e9e9e)"},children:"⌨️ LaTeX Input"}),jsxRuntime.jsx("button",{onClick:()=>t("handwriting"),style:{...styles$3.button,backgroundColor:e==="handwriting"?"var(--nice-primary-hover, #1976d2)":"var(--nice-text-secondary, #9e9e9e)"},children:"✏️ Handwriting"}),jsxRuntime.jsx("div",{style:{borderLeft:"1px solid var(--nice-border, #ccc)",height:"24px",margin:"0 8px"}}),jsxRuntime.jsxs("div",{style:{position:"relative"},children:[jsxRuntime.jsx("button",{onClick:()=>o(!n),style:styles$3.button,children:"📐 Templates ▾"}),n&&jsxRuntime.jsx("div",{style:{position:"absolute",top:"100%",left:0,backgroundColor:"var(--nice-bg, #fff)",border:"1px solid var(--nice-border, #ddd)",borderRadius:"4px",boxShadow:"0 2px 8px var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",zIndex:100,width:"300px",maxHeight:"400px",overflow:"auto"},children:["basic","calculus","algebra","geometry","statistics","physics"].map(s=>jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("div",{style:styles$3.categoryHeader,children:s}),EQUATION_TEMPLATES.filter(l=>l.category===s).map(l=>jsxRuntime.jsxs("div",{onClick:()=>{a(l),o(!1)},style:{padding:"8px 12px",cursor:"pointer",borderBottom:"1px solid var(--nice-border, #eee)"},onMouseOver:c=>c.target.style.backgroundColor="var(--nice-bg-secondary, #f5f5f5)",onMouseOut:c=>c.target.style.backgroundColor="transparent",children:[jsxRuntime.jsx("div",{style:{fontWeight:500},children:l.name}),jsxRuntime.jsxs("div",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",fontFamily:"monospace"},children:[l.latex.substring(0,40),l.latex.length>40?"...":""]})]},l.name))]},s))})]}),jsxRuntime.jsx("div",{style:{flex:1}}),jsxRuntime.jsx("button",{onClick:()=>navigator.clipboard.writeText(r),style:{...styles$3.button,backgroundColor:"var(--nice-success, #4caf50)"},children:"📋 Copy LaTeX"})]})}function SymbolPalette(){const{insertSymbol:e}=useMathEditor(),[t,r]=react.useState("greek"),a=["greek","operators","relations","arrows","functions","accents","delimiters","sets","logic","calculus","matrices"],n=getSymbolsByCategory(t);return jsxRuntime.jsxs("div",{style:styles$3.sidebar,children:[jsxRuntime.jsx("div",{style:{display:"flex",flexWrap:"wrap",padding:"8px",gap:"4px"},children:a.map(o=>jsxRuntime.jsx("button",{onClick:()=>r(o),style:{padding:"4px 8px",fontSize:"11px",border:"1px solid var(--nice-border, #ddd)",borderRadius:"4px",backgroundColor:t===o?"var(--nice-primary-hover, #1976d2)":"var(--nice-bg, #fff)",color:t===o?"var(--nice-bg, #fff)":"var(--nice-text, #333)",cursor:"pointer"},children:o},o))}),jsxRuntime.jsx("div",{style:styles$3.symbolGrid,children:n.map(o=>jsxRuntime.jsx("button",{onClick:()=>e(o.latex),style:styles$3.symbolButton,title:`${o.name}: ${o.latex}`,children:o.preview||o.latex},o.name))})]})}function LatexPreview({latex:e}){return jsxRuntime.jsxs("div",{style:styles$3.preview,children:[jsxRuntime.jsx("div",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",marginBottom:"8px"},children:"Preview (requires KaTeX/MathJax integration):"}),jsxRuntime.jsx("code",{style:{fontSize:"16px"},children:e||"(empty)"})]})}function HandwritingCanvas(){const{setLatex:e,setMode:t}=useMathEditor(),r=react.useRef(null),[a,n]=react.useState([]),[o,s]=react.useState([]),[l,c]=react.useState(!1),[i,p]=react.useState(!1),d=y=>{const x=r.current;if(!x)return;c(!0);const u=x.getBoundingClientRect();s([{x:y.clientX-u.left,y:y.clientY-u.top,pressure:y.pressure,timestamp:Date.now()}])},h=y=>{if(!l)return;const x=r.current,u=x==null?void 0:x.getContext("2d");if(!x||!u)return;const w=x.getBoundingClientRect(),j={x:y.clientX-w.left,y:y.clientY-w.top,pressure:y.pressure,timestamp:Date.now()};if(s(f=>[...f,j]),o.length>0){const f=o[o.length-1];u.beginPath(),u.moveTo(f.x,f.y),u.lineTo(j.x,j.y),u.strokeStyle="var(--nice-text, #000)",u.lineWidth=2,u.lineCap="round",u.stroke()}},b=()=>{if(l){if(c(!1),o.length>1){const y={id:Date.now().toString(),points:[...o]};n(x=>[...x,y])}s([])}},g=()=>{const y=r.current,x=y==null?void 0:y.getContext("2d");x&&y&&x.clearRect(0,0,y.width,y.height),n([])},m=async()=>{if(a.length!==0){p(!0);try{const y=await recognizeHandwriting(a);e(y.latex),t("input")}finally{p(!1)}}};return react.useEffect(()=>{const y=r.current;y&&(y.width=y.offsetWidth,y.height=200)},[]),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("canvas",{ref:r,style:styles$3.canvas,onPointerDown:d,onPointerMove:h,onPointerUp:b,onPointerLeave:b}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"8px",marginTop:"12px"},children:[jsxRuntime.jsx("button",{onClick:g,style:{...styles$3.button,backgroundColor:"var(--nice-danger, #f44336)"},children:"Clear"}),jsxRuntime.jsx("button",{onClick:m,disabled:a.length===0||i,style:styles$3.button,children:i?"Recognizing...":"Recognize"})]}),jsxRuntime.jsx("p",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",marginTop:"8px"},children:"Draw your equation above. Handwriting recognition requires external API integration."})]})}const mathConstants={pi:Math.PI,PI:Math.PI,e:Math.E,E:Math.E,phi:(1+Math.sqrt(5))/2,tau:Math.PI*2},mathFunctions={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,atan2:Math.atan2,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,sqrt:Math.sqrt,cbrt:Math.cbrt,abs:Math.abs,floor:Math.floor,ceil:Math.ceil,round:Math.round,exp:Math.exp,log:Math.log,log10:Math.log10,log2:Math.log2,pow:Math.pow,min:Math.min,max:Math.max,sign:Math.sign,hypot:Math.hypot,sec:e=>1/Math.cos(e),csc:e=>1/Math.sin(e),cot:e=>1/Math.tan(e),ln:Math.log};class ExpressionParser{constructor(){k(this,"pos",0);k(this,"expr","")}parse(t){this.expr=t.replace(/\s+/g,""),this.pos=0;const r=this.parseAddSub();return a=>this.evaluate(r,{...mathConstants,...a})}parseAddSub(){let t=this.parseMulDiv();for(;this.pos<this.expr.length;){const r=this.expr[this.pos];if(r!=="+"&&r!=="-")break;this.pos++;const a=this.parseMulDiv();t={type:"binary",op:r,left:t,right:a}}return t}parseMulDiv(){let t=this.parsePower();for(;this.pos<this.expr.length;){const r=this.expr[this.pos];if(r!=="*"&&r!=="/")break;this.pos++;const a=this.parsePower();t={type:"binary",op:r,left:t,right:a}}return t}parsePower(){let t=this.parseUnary();for(;this.pos<this.expr.length&&this.expr[this.pos]==="^";){this.pos++;const r=this.parseUnary();t={type:"binary",op:"^",left:t,right:r}}return t}parseUnary(){return this.expr[this.pos]==="-"?(this.pos++,{type:"unary",op:"-",arg:this.parseUnary()}):(this.expr[this.pos]==="+"&&this.pos++,this.parsePrimary())}parsePrimary(){if(this.expr[this.pos]==="("){this.pos++;const a=this.parseAddSub();return this.expr[this.pos]===")"&&this.pos++,a}const t=this.expr.slice(this.pos).match(/^(\d+\.?\d*)/);if(t)return this.pos+=t[1].length,{type:"number",value:parseFloat(t[1])};const r=this.expr.slice(this.pos).match(/^([a-zA-Z_][a-zA-Z0-9_]*)/);if(r){const a=r[1];if(this.pos+=a.length,this.expr[this.pos]==="("){this.pos++;const n=[];for(;this.expr[this.pos]!==")"&&this.pos<this.expr.length;)n.push(this.parseAddSub()),this.expr[this.pos]===","&&this.pos++;return this.expr[this.pos]===")"&&this.pos++,{type:"call",name:a,args:n}}return{type:"variable",name:a}}return{type:"number",value:0}}evaluate(t,r){switch(t.type){case"number":return t.value;case"variable":if(t.name in r)return r[t.name];throw new Error(`Unknown variable: ${t.name}`);case"unary":return t.op==="-"?-this.evaluate(t.arg,r):this.evaluate(t.arg,r);case"binary":{const a=this.evaluate(t.left,r),n=this.evaluate(t.right,r);switch(t.op){case"+":return a+n;case"-":return a-n;case"*":return a*n;case"/":return a/n;case"^":return Math.pow(a,n);default:return 0}}case"call":{const a=mathFunctions[t.name];if(!a)throw new Error(`Unknown function: ${t.name}`);const n=t.args.map(o=>this.evaluate(o,r));return a(...n)}default:return 0}}}class GraphService{constructor(t={}){k(this,"plots",new Map);k(this,"parser",new ExpressionParser);k(this,"config");this.config={defaultResolution:t.defaultResolution??200,maxResolution:t.maxResolution??1e3}}addPlot(t){const r={id:this.generateId(),type:t.type,expression:t.expression,expressionY:t.expressionY,expressionZ:t.expressionZ,label:t.label,color:t.color??{r:66,g:133,b:244},lineWidth:t.lineWidth??2,visible:t.visible??!0,parameterRange:t.parameterRange??{min:-Math.PI,max:Math.PI},parameterRange2:t.parameterRange2??{min:-Math.PI,max:Math.PI},resolution:t.resolution??this.config.defaultResolution};return this.plots.set(r.id,r),r}updatePlot(t,r){const a=this.plots.get(t);if(!a)throw new Error(`Plot not found: ${t}`);const n={...a,...r,id:a.id};return this.plots.set(t,n),n}removePlot(t){this.plots.delete(t)}getPlots(){return Array.from(this.plots.values())}getPlot(t){return this.plots.get(t)}compute2DFunction(t,r,a,n){const o=this.parser.parse(t),s=[],l=(r.max-r.min)/a;for(let c=0;c<=a;c++){const i=r.min+c*l;try{const p=o({x:i,...n});Number.isFinite(p)&&s.push({x:i,y:p})}catch{}}return s}compute2DParametric(t,r,a,n,o){const s=this.parser.parse(t),l=this.parser.parse(r),c=[],i=(a.max-a.min)/n;for(let p=0;p<=n;p++){const d=a.min+p*i;try{const h=s({t:d,...o}),b=l({t:d,...o});Number.isFinite(h)&&Number.isFinite(b)&&c.push({x:h,y:b})}catch{}}return c}compute2DPolar(t,r,a,n){const o=this.parser.parse(t),s=[],l=(r.max-r.min)/a;for(let c=0;c<=a;c++){const i=r.min+c*l;try{const p=o({theta:i,t:i,...n});if(Number.isFinite(p)){const d=p*Math.cos(i),h=p*Math.sin(i);s.push({x:d,y:h})}}catch{}}return s}compute3DSurface(t,r,a,n,o){const s=this.parser.parse(t),l=[],c=(r.max-r.min)/n,i=(a.max-a.min)/n;for(let p=0;p<=n;p++){const d=[],h=r.min+p*c;for(let b=0;b<=n;b++){const g=a.min+b*i;try{const m=s({x:h,y:g,...o});Number.isFinite(m)?d.push({x:h,y:g,z:m}):d.push({x:h,y:g,z:0})}catch{d.push({x:h,y:g,z:0})}}l.push(d)}return l}exportSVG(t,r,a,n){const s=a-80,l=n-40*2,c=d=>40+(d-r.xRange.min)/(r.xRange.max-r.xRange.min)*s,i=d=>n-40-(d-r.yRange.min)/(r.yRange.max-r.yRange.min)*l,p=[`<svg xmlns="http://www.w3.org/2000/svg" width="${a}" height="${n}">`,`<rect width="100%" height="100%" fill="rgb(${r.backgroundColor.r},${r.backgroundColor.g},${r.backgroundColor.b})"/>`];if(r.showGrid){p.push('<g stroke="var(--nice-border, #ddd)" stroke-width="0.5">');for(let d=Math.ceil(r.xRange.min);d<=r.xRange.max;d++){const h=c(d);p.push(`<line x1="${h}" y1="40" x2="${h}" y2="${n-40}"/>`)}for(let d=Math.ceil(r.yRange.min);d<=r.yRange.max;d++){const h=i(d);p.push(`<line x1="40" y1="${h}" x2="${a-40}" y2="${h}"/>`)}p.push("</g>")}if(r.showAxes){p.push('<g stroke="var(--nice-text, #333)" stroke-width="1">');const d=i(0),h=c(0);p.push(`<line x1="40" y1="${d}" x2="${a-40}" y2="${d}"/>`),p.push(`<line x1="${h}" y1="40" x2="${h}" y2="${n-40}"/>`),p.push("</g>")}for(const d of t.filter(h=>h.visible))if(d.type==="2d-function"){const h=this.compute2DFunction(d.expression,r.xRange,d.resolution||200);if(h.length>0){const b=h.map((g,m)=>`${m===0?"M":"L"}${c(g.x)},${i(g.y)}`).join(" ");p.push(`<path d="${b}" fill="none" stroke="rgb(${d.color.r},${d.color.g},${d.color.b})" stroke-width="${d.lineWidth}"/>`)}}return r.showLabels&&(p.push(`<text x="${a/2}" y="${n-10}" text-anchor="middle" font-size="12">x</text>`),p.push(`<text x="10" y="${n/2}" text-anchor="middle" font-size="12" transform="rotate(-90,10,${n/2})">y</text>`)),p.push("</svg>"),p.join(`
3
+ `)}async exportPNG(t,r,a,n){const o=this.exportSVG(t,r,a,n);return new Promise((s,l)=>{const c=new Image;c.onload=()=>{const i=document.createElement("canvas");i.width=a,i.height=n;const p=i.getContext("2d");if(!p){l(new Error("Could not get canvas context"));return}p.drawImage(c,0,0),s(i.toDataURL("image/png"))},c.onerror=l,c.src="data:image/svg+xml;base64,"+btoa(o)})}generateId(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}}function createGraphService(e){return new GraphService(e)}const FUNCTION_PRESETS=[{name:"Linear",expression:"x",type:"2d-function",category:"basic"},{name:"Quadratic",expression:"x^2",type:"2d-function",category:"basic"},{name:"Cubic",expression:"x^3",type:"2d-function",category:"basic"},{name:"Square root",expression:"sqrt(x)",type:"2d-function",category:"basic"},{name:"Absolute",expression:"abs(x)",type:"2d-function",category:"basic"},{name:"Reciprocal",expression:"1/x",type:"2d-function",category:"basic"},{name:"Sine",expression:"sin(x)",type:"2d-function",category:"trigonometric"},{name:"Cosine",expression:"cos(x)",type:"2d-function",category:"trigonometric"},{name:"Tangent",expression:"tan(x)",type:"2d-function",category:"trigonometric"},{name:"Sine wave",expression:"sin(2*x)",type:"2d-function",category:"trigonometric"},{name:"Damped oscillation",expression:"exp(-x/5)*sin(x*3)",type:"2d-function",category:"trigonometric"},{name:"Exponential",expression:"exp(x)",type:"2d-function",category:"exponential"},{name:"Natural log",expression:"ln(x)",type:"2d-function",category:"exponential"},{name:"Gaussian",expression:"exp(-x^2)",type:"2d-function",category:"exponential"},{name:"Sigmoid",expression:"1/(1+exp(-x))",type:"2d-function",category:"exponential"},{name:"Circle",expression:"cos(t)",expressionY:"sin(t)",type:"2d-parametric",category:"parametric"},{name:"Ellipse",expression:"2*cos(t)",expressionY:"sin(t)",type:"2d-parametric",category:"parametric"},{name:"Lissajous",expression:"sin(3*t)",expressionY:"sin(2*t)",type:"2d-parametric",category:"parametric"},{name:"Spiral",expression:"t*cos(t)",expressionY:"t*sin(t)",type:"2d-parametric",category:"parametric"},{name:"Cardioid",expression:"(1-cos(t))*cos(t)",expressionY:"(1-cos(t))*sin(t)",type:"2d-parametric",category:"parametric"},{name:"Rose curve",expression:"cos(3*t)*cos(t)",expressionY:"cos(3*t)*sin(t)",type:"2d-parametric",category:"parametric"},{name:"Polar rose 3",expression:"cos(3*theta)",type:"2d-polar",category:"polar"},{name:"Polar rose 5",expression:"cos(5*theta)",type:"2d-polar",category:"polar"},{name:"Archimedean spiral",expression:"theta",type:"2d-polar",category:"polar"},{name:"Logarithmic spiral",expression:"exp(theta/10)",type:"2d-polar",category:"polar"},{name:"Paraboloid",expression:"x^2 + y^2",type:"3d-surface",category:"3d"},{name:"Saddle",expression:"x^2 - y^2",type:"3d-surface",category:"3d"},{name:"Ripple",expression:"sin(sqrt(x^2 + y^2))",type:"3d-surface",category:"3d"},{name:"Torus slice",expression:"cos(x)*sin(y)",type:"3d-surface",category:"3d"},{name:"Peaks",expression:"3*(1-x)^2*exp(-x^2-(y+1)^2) - 10*(x/5-x^3-y^5)*exp(-x^2-y^2) - 1/3*exp(-(x+1)^2-y^2)",type:"3d-surface",category:"3d"}],GraphContext=react.createContext(null);function useGraph(){const e=react.useContext(GraphContext);if(!e)throw new Error("useGraph must be used within GraphProvider");return e}const styles$2={container:{display:"flex",height:"100%",fontFamily:"'Inter', sans-serif",fontSize:"14px"},sidebar:{width:"280px",borderRight:"1px solid var(--nice-border, #e0e0e0)",display:"flex",flexDirection:"column",overflow:"hidden"},plotList:{flex:1,overflow:"auto",padding:"8px"},main:{flex:1,display:"flex",flexDirection:"column",backgroundColor:"var(--nice-bg, #fff)"},canvas:{flex:1,backgroundColor:"var(--nice-bg, #fff)"},toolbar:{display:"flex",gap:"8px",padding:"8px",borderBottom:"1px solid var(--nice-border, #e0e0e0)",alignItems:"center"},button:{padding:"6px 12px",backgroundColor:"var(--nice-primary-hover, #1976d2)",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"13px"},input:{padding:"6px 8px",border:"1px solid var(--nice-border, #ddd)",borderRadius:"4px",fontSize:"13px"},plotItem:{padding:"8px",marginBottom:"8px",border:"1px solid var(--nice-border, #e0e0e0)",borderRadius:"4px",backgroundColor:"var(--nice-bg-secondary, #fafafa)"}};function NiceGraphPlotter({service:e,width:t=800,height:r=600,className:a,style:n}){const[o,s]=react.useState([]),[l,c]=react.useState({xRange:{min:-10,max:10},yRange:{min:-10,max:10},zRange:{min:-5,max:5},showGrid:!0,showAxes:!0,showLabels:!0,backgroundColor:{r:255,g:255,b:255},cameraRotationX:30,cameraRotationY:45,cameraDistance:5}),[i,p]=react.useState({isPlaying:!1,parameter:"a",currentValue:0,minValue:-5,maxValue:5,speed:1}),d=react.useCallback(()=>{s(e.getPlots())},[e]),h=react.useCallback(u=>{c(w=>({...w,...u}))},[]),b=react.useCallback(u=>{p(w=>({...w,...u}))},[]),g=react.useCallback(u=>{e.addPlot(u),d()},[e,d]),m=react.useCallback(u=>{e.removePlot(u),d()},[e,d]),y=react.useCallback((u,w)=>{e.updatePlot(u,w),d()},[e,d]),x={service:e,plots:o,view:l,setView:h,addPlot:g,removePlot:m,updatePlot:y,animation:i,setAnimation:b,refresh:d};return jsxRuntime.jsx(GraphContext.Provider,{value:x,children:jsxRuntime.jsxs("div",{className:a,style:{...styles$2.container,...n},children:[jsxRuntime.jsxs("div",{style:styles$2.sidebar,children:[jsxRuntime.jsx(PlotControls,{}),jsxRuntime.jsx(PlotList,{})]}),jsxRuntime.jsxs("div",{style:styles$2.main,children:[jsxRuntime.jsx(GraphToolbar,{width:t,height:r}),jsxRuntime.jsx(Canvas2D,{width:t,height:r})]})]})})}function PlotControls(){const{addPlot:e}=useGraph(),[t,r]=react.useState("sin(x)"),[a,n]=react.useState("2d-function"),[o,s]=react.useState("cos(x)"),l=()=>{e({type:a,expression:t,expressionY:a==="2d-parametric"?o:void 0,color:{r:Math.floor(Math.random()*200),g:Math.floor(Math.random()*200),b:Math.floor(Math.random()*200)}})};return jsxRuntime.jsxs("div",{style:{padding:"12px",borderBottom:"1px solid var(--nice-border, #e0e0e0)"},children:[jsxRuntime.jsx("div",{style:{marginBottom:"8px"},children:jsxRuntime.jsxs("select",{value:a,onChange:c=>n(c.target.value),style:{...styles$2.input,width:"100%"},children:[jsxRuntime.jsx("option",{value:"2d-function",children:"y = f(x)"}),jsxRuntime.jsx("option",{value:"2d-parametric",children:"Parametric (x(t), y(t))"}),jsxRuntime.jsx("option",{value:"2d-polar",children:"Polar r = f(θ)"}),jsxRuntime.jsx("option",{value:"3d-surface",children:"3D Surface z = f(x,y)"})]})}),jsxRuntime.jsx("div",{style:{marginBottom:"8px"},children:jsxRuntime.jsx("input",{type:"text",value:t,onChange:c=>r(c.target.value),placeholder:a==="2d-parametric"?"x(t) = ...":"Expression...",style:{...styles$2.input,width:"100%"}})}),a==="2d-parametric"&&jsxRuntime.jsx("div",{style:{marginBottom:"8px"},children:jsxRuntime.jsx("input",{type:"text",value:o,onChange:c=>s(c.target.value),placeholder:"y(t) = ...",style:{...styles$2.input,width:"100%"}})}),jsxRuntime.jsx("button",{onClick:l,style:{...styles$2.button,width:"100%"},children:"+ Add Plot"}),jsxRuntime.jsxs("select",{onChange:c=>{const i=FUNCTION_PRESETS.find(p=>p.name===c.target.value);i&&e({type:i.type,expression:i.expression,expressionY:i.expressionY,label:i.name,color:{r:Math.floor(Math.random()*200),g:Math.floor(Math.random()*200),b:Math.floor(Math.random()*200)}})},style:{...styles$2.input,width:"100%",marginTop:"8px"},value:"",children:[jsxRuntime.jsx("option",{value:"",disabled:!0,children:"Quick add preset..."}),["basic","trigonometric","exponential","parametric","polar","3d"].map(c=>jsxRuntime.jsx("optgroup",{label:c.charAt(0).toUpperCase()+c.slice(1),children:FUNCTION_PRESETS.filter(i=>i.category===c).map(i=>jsxRuntime.jsxs("option",{value:i.name,children:[i.name,": ",i.expression]},i.name))},c))]})]})}function PlotList(){const{plots:e,removePlot:t,updatePlot:r}=useGraph();return jsxRuntime.jsxs("div",{style:styles$2.plotList,children:[e.length===0&&jsxRuntime.jsx("div",{style:{color:"var(--nice-text-secondary, #666)",textAlign:"center",padding:"16px"},children:"No plots added yet"}),e.map(a=>jsxRuntime.jsxs("div",{style:styles$2.plotItem,children:[jsxRuntime.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[jsxRuntime.jsx("input",{type:"checkbox",checked:a.visible,onChange:n=>r(a.id,{visible:n.target.checked})}),jsxRuntime.jsx("div",{style:{width:"16px",height:"16px",borderRadius:"3px",backgroundColor:`rgb(${a.color.r},${a.color.g},${a.color.b})`}}),jsxRuntime.jsx("span",{style:{flex:1,fontWeight:500},children:a.label||a.expression}),jsxRuntime.jsx("button",{onClick:()=>t(a.id),style:{padding:"2px 6px",backgroundColor:"var(--nice-danger, #f44336)",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"12px"},children:"×"})]}),jsxRuntime.jsx("div",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",fontFamily:"monospace"},children:a.type==="2d-parametric"?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:["x(t) = ",a.expression,jsxRuntime.jsx("br",{}),"y(t) = ",a.expressionY]}):a.expression})]},a.id))]})}function GraphToolbar({width:e,height:t}){const{service:r,plots:a,view:n,setView:o}=useGraph(),s=()=>{const c=r.exportSVG(a,n,e,t),i=new Blob([c],{type:"image/svg+xml"}),p=URL.createObjectURL(i),d=document.createElement("a");d.href=p,d.download="graph.svg",d.click(),URL.revokeObjectURL(p)},l=async()=>{const c=await r.exportPNG(a,n,e,t),i=document.createElement("a");i.href=c,i.download="graph.png",i.click()};return jsxRuntime.jsxs("div",{style:styles$2.toolbar,children:[jsxRuntime.jsxs("label",{style:{fontSize:"12px"},children:["X: ["," ",jsxRuntime.jsx("input",{type:"number",value:n.xRange.min,onChange:c=>o({xRange:{...n.xRange,min:Number(c.target.value)}}),style:{...styles$2.input,width:"50px"}}),","," ",jsxRuntime.jsx("input",{type:"number",value:n.xRange.max,onChange:c=>o({xRange:{...n.xRange,max:Number(c.target.value)}}),style:{...styles$2.input,width:"50px"}}),"]"]}),jsxRuntime.jsxs("label",{style:{fontSize:"12px"},children:["Y: ["," ",jsxRuntime.jsx("input",{type:"number",value:n.yRange.min,onChange:c=>o({yRange:{...n.yRange,min:Number(c.target.value)}}),style:{...styles$2.input,width:"50px"}}),","," ",jsxRuntime.jsx("input",{type:"number",value:n.yRange.max,onChange:c=>o({yRange:{...n.yRange,max:Number(c.target.value)}}),style:{...styles$2.input,width:"50px"}}),"]"]}),jsxRuntime.jsxs("label",{style:{fontSize:"12px"},children:[jsxRuntime.jsx("input",{type:"checkbox",checked:n.showGrid,onChange:c=>o({showGrid:c.target.checked})}),"Grid"]}),jsxRuntime.jsxs("label",{style:{fontSize:"12px"},children:[jsxRuntime.jsx("input",{type:"checkbox",checked:n.showAxes,onChange:c=>o({showAxes:c.target.checked})}),"Axes"]}),jsxRuntime.jsx("div",{style:{flex:1}}),jsxRuntime.jsx("button",{onClick:s,style:{...styles$2.button,backgroundColor:"var(--nice-success, #4caf50)"},children:"📥 SVG"}),jsxRuntime.jsx("button",{onClick:l,style:{...styles$2.button,backgroundColor:"var(--nice-warning, #ff9800)"},children:"📥 PNG"})]})}function Canvas2D({width:e,height:t}){const r=react.useRef(null),{service:a,plots:n,view:o,animation:s}=useGraph(),l=40;return react.useEffect(()=>{const c=r.current,i=c==null?void 0:c.getContext("2d");if(!c||!i)return;i.fillStyle=`rgb(${o.backgroundColor.r},${o.backgroundColor.g},${o.backgroundColor.b})`,i.fillRect(0,0,e,t);const p=e-l*2,d=t-l*2,h=m=>l+(m-o.xRange.min)/(o.xRange.max-o.xRange.min)*p,b=m=>t-l-(m-o.yRange.min)/(o.yRange.max-o.yRange.min)*d;if(o.showGrid){i.strokeStyle="var(--nice-border, #e0e0e0)",i.lineWidth=.5;for(let m=Math.ceil(o.xRange.min);m<=o.xRange.max;m++){const y=h(m);i.beginPath(),i.moveTo(y,l),i.lineTo(y,t-l),i.stroke()}for(let m=Math.ceil(o.yRange.min);m<=o.yRange.max;m++){const y=b(m);i.beginPath(),i.moveTo(l,y),i.lineTo(e-l,y),i.stroke()}}if(o.showAxes){i.strokeStyle="var(--nice-text, #333)",i.lineWidth=1;const m=b(0);i.beginPath(),i.moveTo(l,m),i.lineTo(e-l,m),i.stroke();const y=h(0);if(i.beginPath(),i.moveTo(y,l),i.lineTo(y,t-l),i.stroke(),o.showLabels){i.fillStyle="var(--nice-text, #333)",i.font="12px sans-serif",i.textAlign="center",i.fillText("x",e-l+15,m+4),i.fillText("y",y,l-10),i.font="10px sans-serif";for(let x=Math.ceil(o.xRange.min);x<=o.xRange.max;x++)x!==0&&i.fillText(String(x),h(x),m+15);for(let x=Math.ceil(o.yRange.min);x<=o.yRange.max;x++)x!==0&&(i.textAlign="right",i.fillText(String(x),y-5,b(x)+4))}}const g=s.isPlaying?{[s.parameter]:s.currentValue}:{};for(const m of n.filter(y=>y.visible)){const y=`rgb(${m.color.r},${m.color.g},${m.color.b})`;i.strokeStyle=y,i.lineWidth=m.lineWidth||2;let x=[];switch(m.type){case"2d-function":x=a.compute2DFunction(m.expression,o.xRange,m.resolution||200,g);break;case"2d-parametric":x=a.compute2DParametric(m.expression,m.expressionY||"sin(t)",m.parameterRange||{min:0,max:2*Math.PI},m.resolution||200,g);break;case"2d-polar":x=a.compute2DPolar(m.expression,m.parameterRange||{min:0,max:2*Math.PI},m.resolution||200,g);break}if(x.length>0){i.beginPath();let u=!1;for(const w of x){const j=h(w.x),f=b(w.y);if(f<0||f>t){u=!1;continue}u?i.lineTo(j,f):(i.moveTo(j,f),u=!0)}i.stroke()}}},[n,o,s,a,e,t]),jsxRuntime.jsx("canvas",{ref:r,width:e,height:t,style:styles$2.canvas})}const UNITS=[{name:"Meter",symbol:"m",category:"Length",toBase:e=>e,fromBase:e=>e},{name:"Kilometer",symbol:"km",category:"Length",toBase:e=>e*1e3,fromBase:e=>e/1e3},{name:"Centimeter",symbol:"cm",category:"Length",toBase:e=>e/100,fromBase:e=>e*100},{name:"Millimeter",symbol:"mm",category:"Length",toBase:e=>e/1e3,fromBase:e=>e*1e3},{name:"Mile",symbol:"mi",category:"Length",toBase:e=>e*1609.344,fromBase:e=>e/1609.344},{name:"Yard",symbol:"yd",category:"Length",toBase:e=>e*.9144,fromBase:e=>e/.9144},{name:"Foot",symbol:"ft",category:"Length",toBase:e=>e*.3048,fromBase:e=>e/.3048},{name:"Inch",symbol:"in",category:"Length",toBase:e=>e*.0254,fromBase:e=>e/.0254},{name:"Kilogram",symbol:"kg",category:"Mass",toBase:e=>e,fromBase:e=>e},{name:"Gram",symbol:"g",category:"Mass",toBase:e=>e/1e3,fromBase:e=>e*1e3},{name:"Milligram",symbol:"mg",category:"Mass",toBase:e=>e/1e6,fromBase:e=>e*1e6},{name:"Pound",symbol:"lb",category:"Mass",toBase:e=>e*.453592,fromBase:e=>e/.453592},{name:"Ounce",symbol:"oz",category:"Mass",toBase:e=>e*.0283495,fromBase:e=>e/.0283495},{name:"Ton",symbol:"t",category:"Mass",toBase:e=>e*1e3,fromBase:e=>e/1e3},{name:"Celsius",symbol:"°C",category:"Temperature",toBase:e=>e,fromBase:e=>e},{name:"Fahrenheit",symbol:"°F",category:"Temperature",toBase:e=>(e-32)*5/9,fromBase:e=>e*9/5+32},{name:"Kelvin",symbol:"K",category:"Temperature",toBase:e=>e-273.15,fromBase:e=>e+273.15},{name:"Second",symbol:"s",category:"Time",toBase:e=>e,fromBase:e=>e},{name:"Millisecond",symbol:"ms",category:"Time",toBase:e=>e/1e3,fromBase:e=>e*1e3},{name:"Minute",symbol:"min",category:"Time",toBase:e=>e*60,fromBase:e=>e/60},{name:"Hour",symbol:"hr",category:"Time",toBase:e=>e*3600,fromBase:e=>e/3600},{name:"Day",symbol:"d",category:"Time",toBase:e=>e*86400,fromBase:e=>e/86400},{name:"Week",symbol:"wk",category:"Time",toBase:e=>e*604800,fromBase:e=>e/604800},{name:"Square meter",symbol:"m²",category:"Area",toBase:e=>e,fromBase:e=>e},{name:"Square kilometer",symbol:"km²",category:"Area",toBase:e=>e*1e6,fromBase:e=>e/1e6},{name:"Hectare",symbol:"ha",category:"Area",toBase:e=>e*1e4,fromBase:e=>e/1e4},{name:"Acre",symbol:"ac",category:"Area",toBase:e=>e*4046.86,fromBase:e=>e/4046.86},{name:"Square foot",symbol:"ft²",category:"Area",toBase:e=>e*.092903,fromBase:e=>e/.092903},{name:"Liter",symbol:"L",category:"Volume",toBase:e=>e,fromBase:e=>e},{name:"Milliliter",symbol:"mL",category:"Volume",toBase:e=>e/1e3,fromBase:e=>e*1e3},{name:"Cubic meter",symbol:"m³",category:"Volume",toBase:e=>e*1e3,fromBase:e=>e/1e3},{name:"Gallon (US)",symbol:"gal",category:"Volume",toBase:e=>e*3.78541,fromBase:e=>e/3.78541},{name:"Quart",symbol:"qt",category:"Volume",toBase:e=>e*.946353,fromBase:e=>e/.946353},{name:"Pint",symbol:"pt",category:"Volume",toBase:e=>e*.473176,fromBase:e=>e/.473176},{name:"Cup",symbol:"cup",category:"Volume",toBase:e=>e*.236588,fromBase:e=>e/.236588},{name:"Meters/second",symbol:"m/s",category:"Speed",toBase:e=>e,fromBase:e=>e},{name:"Kilometers/hour",symbol:"km/h",category:"Speed",toBase:e=>e/3.6,fromBase:e=>e*3.6},{name:"Miles/hour",symbol:"mph",category:"Speed",toBase:e=>e*.44704,fromBase:e=>e/.44704},{name:"Knots",symbol:"kn",category:"Speed",toBase:e=>e*.514444,fromBase:e=>e/.514444},{name:"Byte",symbol:"B",category:"Data",toBase:e=>e,fromBase:e=>e},{name:"Kilobyte",symbol:"KB",category:"Data",toBase:e=>e*1024,fromBase:e=>e/1024},{name:"Megabyte",symbol:"MB",category:"Data",toBase:e=>e*1048576,fromBase:e=>e/1048576},{name:"Gigabyte",symbol:"GB",category:"Data",toBase:e=>e*1073741824,fromBase:e=>e/1073741824},{name:"Terabyte",symbol:"TB",category:"Data",toBase:e=>e*1099511627776,fromBase:e=>e/1099511627776},{name:"Bit",symbol:"bit",category:"Data",toBase:e=>e/8,fromBase:e=>e*8}],MatrixOps={create(e,t,r=0){const a=[];for(let n=0;n<e;n++)a.push(new Array(t).fill(r));return{rows:e,cols:t,data:a}},identity(e){const t=this.create(e,e);for(let r=0;r<e;r++)t.data[r][r]=1;return t},add(e,t){if(e.rows!==t.rows||e.cols!==t.cols)throw new Error("Matrix dimensions must match for addition");const r=this.create(e.rows,e.cols);for(let a=0;a<e.rows;a++)for(let n=0;n<e.cols;n++)r.data[a][n]=e.data[a][n]+t.data[a][n];return r},subtract(e,t){if(e.rows!==t.rows||e.cols!==t.cols)throw new Error("Matrix dimensions must match for subtraction");const r=this.create(e.rows,e.cols);for(let a=0;a<e.rows;a++)for(let n=0;n<e.cols;n++)r.data[a][n]=e.data[a][n]-t.data[a][n];return r},multiply(e,t){if(e.cols!==t.rows)throw new Error("Matrix A columns must equal Matrix B rows for multiplication");const r=this.create(e.rows,t.cols);for(let a=0;a<e.rows;a++)for(let n=0;n<t.cols;n++){let o=0;for(let s=0;s<e.cols;s++)o+=e.data[a][s]*t.data[s][n];r.data[a][n]=o}return r},scalar(e,t){const r=this.create(e.rows,e.cols);for(let a=0;a<e.rows;a++)for(let n=0;n<e.cols;n++)r.data[a][n]=e.data[a][n]*t;return r},transpose(e){const t=this.create(e.cols,e.rows);for(let r=0;r<e.rows;r++)for(let a=0;a<e.cols;a++)t.data[a][r]=e.data[r][a];return t},determinant(e){if(e.rows!==e.cols)throw new Error("Determinant requires square matrix");if(e.rows===1)return e.data[0][0];if(e.rows===2)return e.data[0][0]*e.data[1][1]-e.data[0][1]*e.data[1][0];let t=0;for(let r=0;r<e.cols;r++)t+=Math.pow(-1,r)*e.data[0][r]*this.determinant(this.minor(e,0,r));return t},minor(e,t,r){const a=this.create(e.rows-1,e.cols-1);let n=0;for(let o=0;o<e.rows;o++){if(o===t)continue;let s=0;for(let l=0;l<e.cols;l++)l!==r&&(a.data[n][s]=e.data[o][l],s++);n++}return a},inverse(e){const t=this.determinant(e);if(t===0)throw new Error("Matrix is singular, cannot compute inverse");const r=e.rows,a=this.create(r,r);for(let n=0;n<r;n++)for(let o=0;o<r;o++){const s=Math.pow(-1,n+o),l=this.determinant(this.minor(e,n,o));a.data[o][n]=s*l}return this.scalar(a,1/t)},trace(e){if(e.rows!==e.cols)throw new Error("Trace requires square matrix");let t=0;for(let r=0;r<e.rows;r++)t+=e.data[r][r];return t},eigenvalues2x2(e){if(e.rows!==2||e.cols!==2)throw new Error("Only 2x2 matrices supported for eigenvalues");const t=e.data[0][0],r=e.data[0][1],a=e.data[1][0],n=e.data[1][1],o=t+n,s=t*n-r*a,l=o*o-4*s;if(l<0)throw new Error("Complex eigenvalues not supported");const c=Math.sqrt(l);return[(o+c)/2,(o-c)/2]},toString(e,t=4){return e.data.map(r=>"[ "+r.map(a=>a.toFixed(t).padStart(10)).join(" ")+" ]").join(`
4
+ `)}},CalculusOps={derivative(e,t,r=1e-7){return(e(t+r)-e(t-r))/(2*r)},secondDerivative(e,t,r=1e-5){return(e(t+r)-2*e(t)+e(t-r))/(r*r)},integrate(e,t,r,a=1e3){a%2!==0&&a++;const n=(r-t)/a;let o=e(t)+e(r);for(let s=1;s<a;s++){const l=t+s*n;o+=s%2===0?2*e(l):4*e(l)}return n/3*o},findRoot(e,t,r=1e-10,a=100){let n=t;for(let o=0;o<a;o++){const s=e(n);if(Math.abs(s)<r)return n;const l=this.derivative(e,n);if(l===0)throw new Error("Derivative is zero, Newton-Raphson failed");n=n-s/l}throw new Error("Newton-Raphson did not converge")},symbolicDerivative(e){if(e=e.trim(),/^-?\d+\.?\d*$/.test(e))return"0";if(e==="x")return"1";const t=e.match(/^x\^(\d+)$/);if(t){const a=parseInt(t[1],10);return a===1?"1":a===2?"2*x":`${a}*x^${a-1}`}const r=e.match(/^(-?\d+\.?\d*)\*x\^(\d+)$/);if(r){const a=parseFloat(r[1]),n=parseInt(r[2],10),o=a*n;return n===1?String(o):n===2?`${o}*x`:`${o}*x^${n-1}`}return e==="sin(x)"?"cos(x)":e==="cos(x)"?"-sin(x)":e==="e^x"||e==="exp(x)"?"e^x":e==="ln(x)"?"1/x":`d/dx(${e})`},symbolicIntegral(e){if(e=e.trim(),/^-?\d+\.?\d*$/.test(e))return`${e}*x + C`;if(e==="x")return"x^2/2 + C";const t=e.match(/^x\^(\d+)$/);if(t){const r=parseInt(t[1],10);return`x^${r+1}/${r+1} + C`}return e==="sin(x)"?"-cos(x) + C":e==="cos(x)"?"sin(x) + C":e==="e^x"||e==="exp(x)"?"e^x + C":e==="1/x"?"ln|x| + C":`∫(${e})dx + C`},solveQuadratic(e,t,r){const a=t*t-4*e*r;if(a<0)throw new Error("No real solutions (complex roots)");if(a===0)return[-t/(2*e)];const n=Math.sqrt(a);return[(-t+n)/(2*e),(-t-n)/(2*e)]}};class CalculatorService{constructor(e={}){k(this,"history",[]);k(this,"memory",0);k(this,"variables",new Map);k(this,"config");this.config={precision:e.precision??12,angleUnit:e.angleUnit??"rad"}}evaluate(expression){let expr=expression.replace(/π|pi/gi,String(Math.PI)).replace(/e(?![xp])/gi,String(Math.E)).replace(/\^/g,"**").replace(/√/g,"Math.sqrt").replace(/sin/gi,"Math.sin").replace(/cos/gi,"Math.cos").replace(/tan/gi,"Math.tan").replace(/asin/gi,"Math.asin").replace(/acos/gi,"Math.acos").replace(/atan/gi,"Math.atan").replace(/sinh/gi,"Math.sinh").replace(/cosh/gi,"Math.cosh").replace(/tanh/gi,"Math.tanh").replace(/log10/gi,"Math.log10").replace(/log2/gi,"Math.log2").replace(/ln/gi,"Math.log").replace(/log\b/gi,"Math.log10").replace(/exp/gi,"Math.exp").replace(/sqrt/gi,"Math.sqrt").replace(/cbrt/gi,"Math.cbrt").replace(/abs/gi,"Math.abs").replace(/floor/gi,"Math.floor").replace(/ceil/gi,"Math.ceil").replace(/round/gi,"Math.round").replace(/pow/gi,"Math.pow").replace(/min/gi,"Math.min").replace(/max/gi,"Math.max");for(const[e,t]of this.variables)expr=expr.replace(new RegExp(`\\b${e}\\b`,"g"),String(t));try{const result=eval(expr);if(typeof result!="number"||!Number.isFinite(result))throw new Error("Invalid result");return result}catch(e){throw new Error(`Invalid expression: ${e.message}`)}}addHistory(e,t,r){this.history.unshift({id:Date.now().toString(36),expression:e,result:t,timestamp:new Date().toISOString(),mode:r}),this.history.length>100&&this.history.pop()}getHistory(){return this.history}clearHistory(){this.history=[]}memoryStore(e){this.memory=e}memoryRecall(){return this.memory}memoryAdd(e){this.memory+=e}memoryClear(){this.memory=0}setVariable(e,t){this.variables.set(e,t)}getVariable(e){return this.variables.get(e)}convertBase(e,t,r){const a={BIN:2,OCT:8,DEC:10,HEX:16},n=parseInt(e,a[t]);if(isNaN(n))throw new Error("Invalid number for base conversion");return n.toString(a[r]).toUpperCase()}convertUnits(e,t,r){const a=UNITS.find(s=>s.symbol===t),n=UNITS.find(s=>s.symbol===r);if(!a||!n)throw new Error("Unknown unit");if(a.category!==n.category)throw new Error("Cannot convert between different unit categories");const o=a.toBase(e);return n.fromBase(o)}getUnitsByCategory(e){return UNITS.filter(t=>t.category===e)}getUnitCategories(){return[...new Set(UNITS.map(e=>e.category))]}format(e){const t=this.config.precision;return Math.abs(e)<1e-10?"0":Math.abs(e)>1e10||Math.abs(e)<1e-6?e.toExponential(t):parseFloat(e.toPrecision(t)).toString()}}function createCalculatorService(e){return new CalculatorService(e)}const CalculatorContext=react.createContext(null);function useCalculator(){const e=react.useContext(CalculatorContext);if(!e)throw new Error("useCalculator must be used within CalculatorProvider");return e}const styles$1={container:{width:"400px",fontFamily:"'Inter', sans-serif",backgroundColor:"var(--nice-bg, #1e1e1e)",borderRadius:"12px",overflow:"hidden",boxShadow:"0 4px 20px var(--nice-overlay-30, rgba(0, 0, 0, 0.3))"},modeSelector:{display:"flex",backgroundColor:"var(--nice-bg-secondary, #2d2d2d)"},modeButton:{flex:1,padding:"8px",border:"none",backgroundColor:"transparent",color:"var(--nice-text-secondary, #888)",fontSize:"11px",cursor:"pointer"},display:{padding:"20px",backgroundColor:"var(--nice-bg-secondary, #252525)",minHeight:"80px"},displayText:{color:"var(--nice-bg, #fff)",fontSize:"32px",fontFamily:"'JetBrains Mono', monospace",textAlign:"right",wordBreak:"break-all"},keypad:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:"1px",backgroundColor:"var(--nice-text, #333)",padding:"1px"},key:{padding:"20px",border:"none",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-bg, #fff)",fontSize:"18px",cursor:"pointer",transition:"background-color 0.1s"},keyOperator:{backgroundColor:"var(--nice-warning, #ff9f0a)",color:"var(--nice-text, #000)"},keyFunction:{backgroundColor:"#505050"}};function NiceCalculator({service:e,className:t,style:r}){const[a,n]=react.useState("0"),[o,s]=react.useState("standard"),[l,c]=react.useState([]),[i,p]=react.useState(!1),d=react.useCallback(m=>{i&&/[0-9.]/.test(m)?(n(m),p(!1)):(n(y=>y==="0"&&m!=="."?m:y+m),p(!1))},[i]),h=react.useCallback(()=>{n("0"),p(!1)},[]),b=react.useCallback(()=>{try{const m=e.evaluate(a),y=e.format(m);e.addHistory(a,y,o),c(e.getHistory()),n(y),p(!0)}catch{n("Error"),p(!0)}},[a,o,e]),g={service:e,display:a,setDisplay:n,mode:o,setMode:s,history:l,calculate:b,appendDigit:d,clear:h};return jsxRuntime.jsx(CalculatorContext.Provider,{value:g,children:jsxRuntime.jsxs("div",{className:t,style:{...styles$1.container,...r},children:[jsxRuntime.jsx(ModeSelector,{}),jsxRuntime.jsx(Display,{}),o==="standard"&&jsxRuntime.jsx(StandardKeypad,{}),o==="scientific"&&jsxRuntime.jsx(ScientificKeypad,{}),o==="programmer"&&jsxRuntime.jsx(ProgrammerKeypad,{}),o==="matrix"&&jsxRuntime.jsx(MatrixMode,{}),o==="calculus"&&jsxRuntime.jsx(CalculusMode,{}),o==="units"&&jsxRuntime.jsx(UnitsMode,{})]})})}function ModeSelector(){const{mode:e,setMode:t}=useCalculator(),r=[{id:"standard",label:"Standard"},{id:"scientific",label:"Scientific"},{id:"programmer",label:"Programmer"},{id:"matrix",label:"Matrix"},{id:"calculus",label:"Calculus"},{id:"units",label:"Units"}];return jsxRuntime.jsx("div",{style:styles$1.modeSelector,children:r.map(a=>jsxRuntime.jsx("button",{onClick:()=>t(a.id),style:{...styles$1.modeButton,backgroundColor:e===a.id?"var(--nice-primary-hover, #1976d2)":"transparent",color:e===a.id?"var(--nice-bg, #fff)":"var(--nice-text-secondary, #888)"},children:a.label},a.id))})}function Display(){const{display:e}=useCalculator();return jsxRuntime.jsx("div",{style:styles$1.display,children:jsxRuntime.jsx("div",{style:styles$1.displayText,children:e})})}function StandardKeypad(){const{appendDigit:e,clear:t,calculate:r,setDisplay:a,display:n}=useCalculator(),o=[{label:"AC",action:t,style:styles$1.keyFunction},{label:"±",action:()=>a(n.startsWith("-")?n.slice(1):"-"+n),style:styles$1.keyFunction},{label:"%",action:()=>e("/100"),style:styles$1.keyFunction},{label:"÷",action:()=>e("/"),style:styles$1.keyOperator},{label:"7",action:()=>e("7")},{label:"8",action:()=>e("8")},{label:"9",action:()=>e("9")},{label:"×",action:()=>e("*"),style:styles$1.keyOperator},{label:"4",action:()=>e("4")},{label:"5",action:()=>e("5")},{label:"6",action:()=>e("6")},{label:"−",action:()=>e("-"),style:styles$1.keyOperator},{label:"1",action:()=>e("1")},{label:"2",action:()=>e("2")},{label:"3",action:()=>e("3")},{label:"+",action:()=>e("+"),style:styles$1.keyOperator},{label:"0",action:()=>e("0")},{label:".",action:()=>e(".")},{label:"⌫",action:()=>a(n.length>1?n.slice(0,-1):"0")},{label:"=",action:r,style:styles$1.keyOperator}];return jsxRuntime.jsx("div",{style:styles$1.keypad,children:o.map((s,l)=>jsxRuntime.jsx("button",{onClick:s.action,style:{...styles$1.key,...s.style||{}},children:s.label},l))})}function ScientificKeypad(){const{appendDigit:e,clear:t,calculate:r,setDisplay:a,display:n}=useCalculator(),o=[{label:"sin",action:()=>e("sin(")},{label:"cos",action:()=>e("cos(")},{label:"tan",action:()=>e("tan(")},{label:"ln",action:()=>e("ln(")},{label:"log",action:()=>e("log10(")}],s=[{label:"x²",action:()=>e("^2")},{label:"x³",action:()=>e("^3")},{label:"xʸ",action:()=>e("^")},{label:"√",action:()=>e("sqrt(")},{label:"eˣ",action:()=>e("exp(")}],l=[{label:"(",action:()=>e("(")},{label:")",action:()=>e(")")},{label:"π",action:()=>e("π")},{label:"e",action:()=>e("e")},{label:"AC",action:t}];return jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("div",{style:{...styles$1.keypad,gridTemplateColumns:"repeat(5, 1fr)"},children:[...o,...s,...l].map((c,i)=>jsxRuntime.jsx("button",{onClick:c.action,style:{...styles$1.key,...styles$1.keyFunction,padding:"12px"},children:c.label},i))}),jsxRuntime.jsx(StandardKeypad,{})]})}function ProgrammerKeypad(){const{display:e,setDisplay:t,service:r}=useCalculator(),[a,n]=react.useState("DEC"),o=l=>{try{const c=r.convertBase(e,a,l);t(c),n(l)}catch{t("Error")}},s=a==="HEX"?["A","B","C","D","E","F"]:[];return jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("div",{style:{display:"flex",gap:"4px",padding:"8px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:["BIN","OCT","DEC","HEX"].map(l=>jsxRuntime.jsx("button",{onClick:()=>o(l),style:{flex:1,padding:"8px",border:"none",borderRadius:"4px",backgroundColor:a===l?"var(--nice-primary-hover, #1976d2)":"var(--nice-border, #3c3c3c)",color:"var(--nice-bg, #fff)",cursor:"pointer"},children:l},l))}),s.length>0&&jsxRuntime.jsx("div",{style:{...styles$1.keypad,gridTemplateColumns:"repeat(6, 1fr)"},children:s.map(l=>jsxRuntime.jsx("button",{onClick:()=>t(e==="0"?l:e+l),style:styles$1.key,children:l},l))}),jsxRuntime.jsx("div",{style:{...styles$1.keypad,gridTemplateColumns:"repeat(4, 1fr)"},children:["7","8","9","AND","4","5","6","OR","1","2","3","XOR","0","NOT","<<",">>"].map(l=>{const c=["AND","OR","XOR","NOT","<<",">>"].includes(l);return jsxRuntime.jsx("button",{onClick:()=>t(e==="0"?l:e+l),style:{...styles$1.key,...c?styles$1.keyFunction:{}},children:l},l)})})]})}function MatrixMode(){const[e,t]=react.useState(MatrixOps.create(2,2)),[r,a]=react.useState(MatrixOps.create(2,2)),[n,o]=react.useState(""),s=(c,i,p,d,h)=>{const b={...c,data:c.data.map(g=>[...g])};b.data[p][d]=parseFloat(h)||0,i(b)},l=[{label:"A + B",fn:()=>MatrixOps.toString(MatrixOps.add(e,r))},{label:"A - B",fn:()=>MatrixOps.toString(MatrixOps.subtract(e,r))},{label:"A × B",fn:()=>MatrixOps.toString(MatrixOps.multiply(e,r))},{label:"det(A)",fn:()=>MatrixOps.determinant(e).toFixed(4)},{label:"Aᵀ",fn:()=>MatrixOps.toString(MatrixOps.transpose(e))},{label:"A⁻¹",fn:()=>MatrixOps.toString(MatrixOps.inverse(e))}];return jsxRuntime.jsxs("div",{style:{padding:"12px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:[jsxRuntime.jsxs("div",{style:{display:"flex",gap:"12px",marginBottom:"12px"},children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("div",{style:{color:"var(--nice-text-secondary, #888)",marginBottom:"4px"},children:"Matrix A"}),jsxRuntime.jsx(MatrixInput,{matrix:e,onChange:(c,i,p)=>s(e,t,c,i,p)})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("div",{style:{color:"var(--nice-text-secondary, #888)",marginBottom:"4px"},children:"Matrix B"}),jsxRuntime.jsx(MatrixInput,{matrix:r,onChange:(c,i,p)=>s(r,a,c,i,p)})]})]}),jsxRuntime.jsx("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginBottom:"12px"},children:l.map(c=>jsxRuntime.jsx("button",{onClick:()=>{try{o(c.fn())}catch(i){o(i.message)}},style:{padding:"8px 12px",backgroundColor:"var(--nice-primary-hover, #1976d2)",color:"var(--nice-bg, #fff)",border:"none",borderRadius:"4px",cursor:"pointer"},children:c.label},c.label))}),n&&jsxRuntime.jsx("pre",{style:{color:"var(--nice-bg, #fff)",fontFamily:"monospace",whiteSpace:"pre-wrap"},children:n})]})}function MatrixInput({matrix:e,onChange:t}){return jsxRuntime.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${e.cols}, 50px)`,gap:"4px"},children:e.data.map((r,a)=>r.map((n,o)=>jsxRuntime.jsx("input",{type:"number",value:n,onChange:s=>t(a,o,s.target.value),style:{width:"100%",padding:"4px",textAlign:"center",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-bg, #fff)",border:"1px solid var(--nice-text-secondary, #555)",borderRadius:"4px"}},`${a}-${o}`)))})}function CalculusMode(){const[e,t]=react.useState("x^2"),[r,a]=react.useState("");return jsxRuntime.jsxs("div",{style:{padding:"12px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:[jsxRuntime.jsx("input",{type:"text",value:e,onChange:n=>t(n.target.value),placeholder:"Enter expression (e.g., x^2, sin(x))",style:{width:"100%",padding:"8px",marginBottom:"12px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-bg, #fff)",border:"1px solid var(--nice-text-secondary, #555)",borderRadius:"4px"}}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginBottom:"12px"},children:[jsxRuntime.jsx("button",{onClick:()=>a(`d/dx(${e}) = ${CalculusOps.symbolicDerivative(e)}`),style:{padding:"8px 12px",backgroundColor:"var(--nice-success, #4caf50)",color:"var(--nice-bg, #fff)",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Differentiate"}),jsxRuntime.jsx("button",{onClick:()=>a(`∫(${e})dx = ${CalculusOps.symbolicIntegral(e)}`),style:{padding:"8px 12px",backgroundColor:"var(--nice-primary, #2196f3)",color:"var(--nice-bg, #fff)",border:"none",borderRadius:"4px",cursor:"pointer"},children:"Integrate"})]}),r&&jsxRuntime.jsx("div",{style:{color:"var(--nice-bg, #fff)",fontFamily:"monospace",padding:"8px",backgroundColor:"var(--nice-bg, #1e1e1e)",borderRadius:"4px"},children:r})]})}function UnitsMode(){const{service:e}=useCalculator(),[t,r]=react.useState("1"),[a,n]=react.useState("m"),[o,s]=react.useState("ft"),[l,c]=react.useState("Length"),[i,p]=react.useState(""),d=e.getUnitCategories(),h=e.getUnitsByCategory(l),b=()=>{try{const g=e.convertUnits(parseFloat(t),a,o);p(`${t} ${a} = ${e.format(g)} ${o}`)}catch(g){p(g.message)}};return jsxRuntime.jsxs("div",{style:{padding:"12px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:[jsxRuntime.jsx("select",{value:l,onChange:g=>{c(g.target.value);const m=e.getUnitsByCategory(g.target.value);m.length>=2&&(n(m[0].symbol),s(m[1].symbol))},style:{width:"100%",padding:"8px",marginBottom:"12px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-bg, #fff)",border:"1px solid var(--nice-text-secondary, #555)",borderRadius:"4px"},children:d.map(g=>jsxRuntime.jsx("option",{value:g,children:g},g))}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center",marginBottom:"12px"},children:[jsxRuntime.jsx("input",{type:"number",value:t,onChange:g=>r(g.target.value),style:{flex:1,padding:"8px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-bg, #fff)",border:"1px solid var(--nice-text-secondary, #555)",borderRadius:"4px"}}),jsxRuntime.jsx("select",{value:a,onChange:g=>n(g.target.value),style:{padding:"8px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-bg, #fff)",border:"1px solid var(--nice-text-secondary, #555)",borderRadius:"4px"},children:h.map(g=>jsxRuntime.jsxs("option",{value:g.symbol,children:[g.name," (",g.symbol,")"]},g.symbol))})]}),jsxRuntime.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center",marginBottom:"12px"},children:[jsxRuntime.jsx("span",{style:{color:"var(--nice-text-secondary, #888)"},children:"→"}),jsxRuntime.jsx("select",{value:o,onChange:g=>s(g.target.value),style:{flex:1,padding:"8px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-bg, #fff)",border:"1px solid var(--nice-text-secondary, #555)",borderRadius:"4px"},children:h.map(g=>jsxRuntime.jsxs("option",{value:g.symbol,children:[g.name," (",g.symbol,")"]},g.symbol))})]}),jsxRuntime.jsx("button",{onClick:b,style:{width:"100%",padding:"12px",backgroundColor:"var(--nice-warning, #ff9f0a)",color:"var(--nice-text, #000)",border:"none",borderRadius:"4px",fontSize:"16px",cursor:"pointer"},children:"Convert"}),i&&jsxRuntime.jsx("div",{style:{marginTop:"12px",color:"var(--nice-bg, #fff)",fontSize:"18px",textAlign:"center"},children:i})]})}const GeoMath={distance(e,t){return Math.sqrt((t.x-e.x)**2+(t.y-e.y)**2)},midpoint(e,t){return{x:(e.x+t.x)/2,y:(e.y+t.y)/2}},angle(e,t,r){const a=Math.atan2(e.y-t.y,e.x-t.x);let o=Math.atan2(r.y-t.y,r.x-t.x)-a;return o<0&&(o+=2*Math.PI),o},angleDegrees(e,t,r){return this.angle(e,t,r)*180/Math.PI},closestPointOnLine(e,t,r){const a=t.x-e.x,n=t.y-e.y,o=((r.x-e.x)*a+(r.y-e.y)*n)/(a*a+n*n);return{x:e.x+o*a,y:e.y+o*n}},lineIntersection(e,t,r,a){const n=(e.x-t.x)*(r.y-a.y)-(e.y-t.y)*(r.x-a.x);if(Math.abs(n)<1e-10)return null;const o=((e.x-r.x)*(r.y-a.y)-(e.y-r.y)*(r.x-a.x))/n;return{x:e.x+o*(t.x-e.x),y:e.y+o*(t.y-e.y)}},circleLineIntersection(e,t,r,a){const n=a.x-r.x,o=a.y-r.y,s=r.x-e.x,l=r.y-e.y,c=n*n+o*o,i=2*(s*n+l*o),p=s*s+l*l-t*t,d=i*i-4*c*p;if(d<0)return[];const h=Math.sqrt(d),b=(-i-h)/(2*c),g=(-i+h)/(2*c),m=[];return b>=0&&b<=1&&m.push({x:r.x+b*n,y:r.y+b*o}),g>=0&&g<=1&&Math.abs(g-b)>1e-10&&m.push({x:r.x+g*n,y:r.y+g*o}),m},circleCircleIntersection(e,t,r,a){const n=this.distance(e,r);if(n>t+a||n<Math.abs(t-a)||n===0)return[];const o=(t*t-a*a+n*n)/(2*n),s=Math.sqrt(t*t-o*o),l=e.x+o*(r.x-e.x)/n,c=e.y+o*(r.y-e.y)/n;return[{x:l+s*(r.y-e.y)/n,y:c-s*(r.x-e.x)/n},{x:l-s*(r.y-e.y)/n,y:c+s*(r.x-e.x)/n}]},perpendicularThrough(e,t,r){this.closestPointOnLine(e,t,r);const a=t.x-e.x,n=t.y-e.y;return{p1:r,p2:{x:r.x-n,y:r.y+a}}},parallelThrough(e,t,r){const a=t.x-e.x,n=t.y-e.y;return{p1:r,p2:{x:r.x+a,y:r.y+n}}},angleBisector(e,t,r){const a=Math.atan2(e.y-t.y,e.x-t.x),n=Math.atan2(r.y-t.y,r.x-t.x);let o=(a+n)/2;return Math.abs(n-a)>Math.PI&&(o+=Math.PI),{x:t.x+Math.cos(o),y:t.y+Math.sin(o)}},reflect(e,t,r){const a=this.closestPointOnLine(t,r,e);return{x:2*a.x-e.x,y:2*a.y-e.y}},rotate(e,t,r){const a=Math.cos(r),n=Math.sin(r),o=e.x-t.x,s=e.y-t.y;return{x:t.x+o*a-s*n,y:t.y+o*n+s*a}},translate(e,t,r){return{x:e.x+t,y:e.y+r}},dilate(e,t,r){return{x:t.x+r*(e.x-t.x),y:t.y+r*(e.y-t.y)}},polygonArea(e){let t=0;const r=e.length;for(let a=0;a<r;a++){const n=(a+1)%r;t+=e[a].x*e[n].y,t-=e[n].x*e[a].y}return Math.abs(t)/2},polygonPerimeter(e){let t=0;const r=e.length;for(let a=0;a<r;a++){const n=(a+1)%r;t+=this.distance(e[a],e[n])}return t},circumcenter(e,t,r){const a=2*(e.x*(t.y-r.y)+t.x*(r.y-e.y)+r.x*(e.y-t.y)),n=((e.x**2+e.y**2)*(t.y-r.y)+(t.x**2+t.y**2)*(r.y-e.y)+(r.x**2+r.y**2)*(e.y-t.y))/a,o=((e.x**2+e.y**2)*(r.x-t.x)+(t.x**2+t.y**2)*(e.x-r.x)+(r.x**2+r.y**2)*(t.x-e.x))/a;return{x:n,y:o}},incenter(e,t,r){const a=this.distance(e,t),n=this.distance(t,r),o=this.distance(r,e),s=a+n+o;return{x:(n*e.x+o*t.x+a*r.x)/s,y:(n*e.y+o*t.y+a*r.y)/s}},centroid(e,t,r){return{x:(e.x+t.x+r.x)/3,y:(e.y+t.y+r.y)/3}}};class GeometryService{constructor(){k(this,"elements",new Map);k(this,"nextLabel",1)}addElement(t){const r=this.generateId(),a={...t,id:r};return this.elements.set(r,a),a}getElement(t){return this.elements.get(t)}getPoint(t){const r=this.elements.get(t);return(r==null?void 0:r.type)==="point"?r:void 0}updateElement(t,r){const a=this.elements.get(t);a&&this.elements.set(t,{...a,...r,id:t,type:a.type})}deleteElement(t){var r;this.elements.delete(t);for(const[a,n]of this.elements)(r=n.dependencies)!=null&&r.includes(t)&&this.deleteElement(a)}getAllElements(){return Array.from(this.elements.values())}getElementsByType(t){return Array.from(this.elements.values()).filter(r=>r.type===t)}clear(){this.elements.clear(),this.nextLabel=1}createPoint(t,r,a){return this.addElement({type:"point",x:t,y:r,label:a??this.getNextLabel(),color:{r:0,g:0,b:0},visible:!0,selected:!1,locked:!1,size:6})}createSegment(t,r){return this.addElement({type:"segment",point1Id:t,point2Id:r,label:void 0,color:{r:50,g:50,b:50},visible:!0,selected:!1,locked:!1,width:2,dependencies:[t,r]})}createLine(t,r){return this.addElement({type:"line",point1Id:t,point2Id:r,label:void 0,color:{r:50,g:50,b:200},visible:!0,selected:!1,locked:!1,width:1,dependencies:[t,r]})}createRay(t,r){return this.addElement({type:"ray",originId:t,throughId:r,label:void 0,color:{r:50,g:150,b:50},visible:!0,selected:!1,locked:!1,width:1,dependencies:[t,r]})}createCircle(t,r){return this.addElement({type:"circle",centerId:t,radius:r,label:void 0,color:{r:200,g:50,b:50},visible:!0,selected:!1,locked:!1,width:2,dependencies:[t]})}createPolygon(t){return this.addElement({type:"polygon",pointIds:t,label:void 0,color:{r:100,g:100,b:200},visible:!0,selected:!1,locked:!1,width:2,fill:{r:100,g:100,b:200,a:.2},dependencies:t})}createMidpoint(t,r){const a=this.getPoint(t),n=this.getPoint(r);if(!a||!n)return null;const o=GeoMath.midpoint(a,n),s=this.createPoint(o.x,o.y);return s.dependencies=[t,r],s.color={r:0,g:150,b:0},s}createPerpendicular(t,r,a){const n=this.getPoint(t),o=this.getPoint(r),s=this.getPoint(a);if(!n||!o||!s)return null;const l=GeoMath.perpendicularThrough(n,o,s),c=this.createPoint(l.p2.x,l.p2.y),i=this.createLine(a,c.id);return i.dependencies=[t,r,a],i}createParallel(t,r,a){const n=this.getPoint(t),o=this.getPoint(r),s=this.getPoint(a);if(!n||!o||!s)return null;const l=GeoMath.parallelThrough(n,o,s),c=this.createPoint(l.p2.x,l.p2.y),i=this.createLine(a,c.id);return i.dependencies=[t,r,a],i}createIntersection(t,r){const a=this.elements.get(t),n=this.elements.get(r);if(!a||!n)return[];const o=[],s=i=>{if(i.type==="line"||i.type==="segment"||i.type==="ray"){const p=i,d=this.getPoint(p.point1Id??p.originId),h=this.getPoint(p.point2Id??p.throughId);if(d&&h)return[d,h]}return null},l=s(a),c=s(n);if(l&&c){const i=GeoMath.lineIntersection(l[0],l[1],c[0],c[1]);if(i){const p=this.createPoint(i.x,i.y);p.dependencies=[t,r],p.color={r:255,g:0,b:0},o.push(p)}}if(a.type==="circle"&&c){const i=a,p=this.getPoint(i.centerId);if(p){const d=GeoMath.circleLineIntersection(p,i.radius,c[0],c[1]);for(const h of d){const b=this.createPoint(h.x,h.y);b.dependencies=[t,r],b.color={r:255,g:0,b:0},o.push(b)}}}if(a.type==="circle"&&n.type==="circle"){const i=a,p=n,d=this.getPoint(i.centerId),h=this.getPoint(p.centerId);if(d&&h){const b=GeoMath.circleCircleIntersection(d,i.radius,h,p.radius);for(const g of b){const m=this.createPoint(g.x,g.y);m.dependencies=[t,r],m.color={r:255,g:0,b:0},o.push(m)}}}return o}calculateMeasurement(t,r){switch(t){case"distance":{const a=this.getPoint(r[0]),n=this.getPoint(r[1]);if(a&&n)return GeoMath.distance(a,n);break}case"angle":{const a=this.getPoint(r[0]),n=this.getPoint(r[1]),o=this.getPoint(r[2]);if(a&&n&&o)return GeoMath.angleDegrees(a,n,o);break}case"area":case"perimeter":{const a=this.elements.get(r[0]);if((a==null?void 0:a.type)==="polygon"){const n=a.pointIds.map(o=>this.getPoint(o)).filter(Boolean);return t==="area"?GeoMath.polygonArea(n):GeoMath.polygonPerimeter(n)}break}}return 0}exportSVG(t,r,a){const n=[`<svg xmlns="http://www.w3.org/2000/svg" width="${t}" height="${r}" viewBox="0 0 ${t} ${r}">`];n.push(`<rect width="100%" height="100%" fill="rgb(${a.backgroundColor.r},${a.backgroundColor.g},${a.backgroundColor.b})"/>`);const o=(s,l)=>({x:t/2+(s-a.centerX)*a.scale,y:r/2-(l-a.centerY)*a.scale});if(a.showGrid){n.push('<g stroke="var(--nice-border, #ddd)" stroke-width="0.5">');for(let s=Math.floor(-t/2/a.scale+a.centerX);s<=t/2/a.scale+a.centerX;s+=a.gridSpacing){const l=o(s,0);n.push(`<line x1="${l.x}" y1="0" x2="${l.x}" y2="${r}"/>`)}for(let s=Math.floor(-r/2/a.scale+a.centerY);s<=r/2/a.scale+a.centerY;s+=a.gridSpacing){const l=o(0,s);n.push(`<line x1="0" y1="${l.y}" x2="${t}" y2="${l.y}"/>`)}n.push("</g>")}if(a.showAxes){const s=o(0,0);n.push('<g stroke="var(--nice-text, #333)" stroke-width="1">'),n.push(`<line x1="0" y1="${s.y}" x2="${t}" y2="${s.y}"/>`),n.push(`<line x1="${s.x}" y1="0" x2="${s.x}" y2="${r}"/>`),n.push("</g>")}for(const s of this.getAllElements()){if(!s.visible)continue;const l=`rgb(${s.color.r},${s.color.g},${s.color.b})`;switch(s.type){case"point":{const c=o(s.x,s.y);n.push(`<circle cx="${c.x}" cy="${c.y}" r="${s.size}" fill="${l}"/>`),s.label&&n.push(`<text x="${c.x+8}" y="${c.y-8}" font-size="12">${s.label}</text>`);break}case"segment":{const c=this.getPoint(s.point1Id),i=this.getPoint(s.point2Id);if(c&&i){const p=o(c.x,c.y),d=o(i.x,i.y);n.push(`<line x1="${p.x}" y1="${p.y}" x2="${d.x}" y2="${d.y}" stroke="${l}" stroke-width="${s.width}"/>`)}break}case"circle":{const c=this.getPoint(s.centerId);if(c){const i=o(c.x,c.y),p=s.radius*a.scale,d=s.fill?`rgba(${s.fill.r},${s.fill.g},${s.fill.b},${s.fill.a??.2})`:"none";n.push(`<circle cx="${i.x}" cy="${i.y}" r="${p}" fill="${d}" stroke="${l}" stroke-width="${s.width}"/>`)}break}case"polygon":{const c=s.pointIds.map(i=>this.getPoint(i)).filter(Boolean);if(c.length>0){const p=c.map(h=>o(h.x,h.y)).map((h,b)=>`${b===0?"M":"L"}${h.x},${h.y}`).join(" ")+" Z",d=s.fill?`rgba(${s.fill.r},${s.fill.g},${s.fill.b},${s.fill.a??.2})`:"none";n.push(`<path d="${p}" fill="${d}" stroke="${l}" stroke-width="${s.width}"/>`)}break}}}return n.push("</svg>"),n.join(`
5
+ `)}generateId(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}getNextLabel(){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZ",r=this.nextLabel-1;return this.nextLabel++,r<26?t[r]:t[r%26]+Math.floor(r/26)}}function createGeometryService(){return new GeometryService}const GeometryContext=react.createContext(null);function useGeometry(){const e=react.useContext(GeometryContext);if(!e)throw new Error("useGeometry must be used within GeometryProvider");return e}const styles={container:{display:"flex",height:"100%",fontFamily:"'Inter', sans-serif",fontSize:"14px"},toolbar:{width:"50px",backgroundColor:"var(--nice-bg-secondary, #f5f5f5)",borderRight:"1px solid var(--nice-border, #e0e0e0)",display:"flex",flexDirection:"column",padding:"8px 4px",gap:"4px"},toolButton:{width:"40px",height:"40px",border:"none",borderRadius:"4px",backgroundColor:"transparent",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"18px"},main:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},canvas:{flex:1,cursor:"crosshair"},statusBar:{height:"30px",backgroundColor:"var(--nice-bg-secondary, #f5f5f5)",borderTop:"1px solid var(--nice-border, #e0e0e0)",padding:"0 12px",display:"flex",alignItems:"center",fontSize:"12px",color:"var(--nice-text-secondary, #666)"}};function NiceGeometry({service:e,width:t=800,height:r=600,className:a,style:n}){const[o,s]=react.useState([]),[l,c]=react.useState("point"),[i,p]=react.useState([]),[d,h]=react.useState({centerX:0,centerY:0,scale:40,showGrid:!0,showAxes:!0,gridSpacing:1,snapToGrid:!0,snapToPoints:!0,backgroundColor:{r:255,g:255,b:255}}),b=react.useCallback(()=>{s(e.getAllElements())},[e]),g=react.useCallback(y=>{h(x=>({...x,...y}))},[]);react.useEffect(()=>{b()},[b]);const m={service:e,elements:o,tool:l,setTool:c,view:d,setView:g,selectedIds:i,setSelectedIds:p,refresh:b};return jsxRuntime.jsx(GeometryContext.Provider,{value:m,children:jsxRuntime.jsxs("div",{className:a,style:{...styles.container,...n},children:[jsxRuntime.jsx(Toolbar,{}),jsxRuntime.jsxs("div",{style:styles.main,children:[jsxRuntime.jsx(Canvas,{width:t,height:r}),jsxRuntime.jsx(StatusBar,{width:t,height:r})]})]})})}function Toolbar(){const{tool:e,setTool:t}=useGeometry(),r=[{id:"select",icon:"⬚",title:"Select"},{id:"point",icon:"•",title:"Point"},{id:"segment",icon:"—",title:"Segment"},{id:"line",icon:"↔",title:"Line"},{id:"ray",icon:"→",title:"Ray"},{id:"circle",icon:"○",title:"Circle"},{id:"polygon",icon:"△",title:"Polygon"},{id:"perpendicular",icon:"⊥",title:"Perpendicular"},{id:"parallel",icon:"∥",title:"Parallel"},{id:"midpoint",icon:"⊙",title:"Midpoint"},{id:"bisector",icon:"∠",title:"Angle Bisector"},{id:"intersection",icon:"✕",title:"Intersection"},{id:"reflect",icon:"⇄",title:"Reflect"},{id:"rotate",icon:"↻",title:"Rotate"},{id:"measure",icon:"📏",title:"Measure"}];return jsxRuntime.jsx("div",{style:styles.toolbar,children:r.map(a=>jsxRuntime.jsx("button",{onClick:()=>t(a.id),title:a.title,style:{...styles.toolButton,backgroundColor:e===a.id?"var(--nice-primary-hover, #1976d2)":"transparent",color:e===a.id?"var(--nice-bg, #fff)":"var(--nice-text, #333)"},children:a.icon},a.id))})}function Canvas({width:e,height:t}){const r=react.useRef(null),{service:a,elements:n,tool:o,view:s,selectedIds:l,setSelectedIds:c,refresh:i}=useGeometry(),[p,d]=react.useState([]),h=react.useCallback((y,x)=>{const u=(y-e/2)/s.scale+s.centerX,w=-(x-t/2)/s.scale+s.centerY;return s.snapToGrid?{x:Math.round(u/s.gridSpacing)*s.gridSpacing,y:Math.round(w/s.gridSpacing)*s.gridSpacing}:{x:u,y:w}},[e,t,s]),b=react.useCallback((y,x)=>({x:e/2+(y-s.centerX)*s.scale,y:t/2-(x-s.centerY)*s.scale}),[e,t,s]),g=react.useCallback(y=>{var w;const x=(w=r.current)==null?void 0:w.getBoundingClientRect();if(!x)return;const u=h(y.clientX-x.left,y.clientY-x.top);switch(o){case"point":{a.createPoint(u.x,u.y),i();break}case"segment":case"line":case"ray":{const j=m(u);if(j)d(f=>{const v=[...f,j.id];return v.length===2?(o==="segment"?a.createSegment(v[0],v[1]):o==="line"?a.createLine(v[0],v[1]):o==="ray"&&a.createRay(v[0],v[1]),i(),[]):v});else{const f=a.createPoint(u.x,u.y);d(v=>{const R=[...v,f.id];return R.length===2?(o==="segment"?a.createSegment(R[0],R[1]):o==="line"?a.createLine(R[0],R[1]):o==="ray"&&a.createRay(R[0],R[1]),i(),[]):R}),i()}break}case"circle":{const j=m(u);if(j)d(f=>{if(f.length===0)return[j.id];const v=a.getPoint(f[0]);if(v){const R=GeoMath.distance(v,u);a.createCircle(f[0],R),i()}return[]});else if(p.length===1){const f=a.getPoint(p[0]);if(f){const v=GeoMath.distance(f,u);a.createCircle(p[0],v),i(),d([])}}else{const f=a.createPoint(u.x,u.y);d([f.id]),i()}break}case"midpoint":{const j=m(u);j&&d(f=>{const v=[...f,j.id];return v.length===2?(a.createMidpoint(v[0],v[1]),i(),[]):v});break}case"select":{const j=m(u);c(j?[j.id]:[]);break}}},[o,a,i,h,p,c]),m=y=>{for(const u of n)if(u.type==="point"&&GeoMath.distance(u,y)<.5)return u};return react.useEffect(()=>{const y=r.current,x=y==null?void 0:y.getContext("2d");if(!(!y||!x)){if(x.fillStyle=`rgb(${s.backgroundColor.r},${s.backgroundColor.g},${s.backgroundColor.b})`,x.fillRect(0,0,e,t),s.showGrid){x.strokeStyle="var(--nice-border, #e0e0e0)",x.lineWidth=.5;const u=s.gridSpacing*s.scale,w=(e/2-s.centerX*s.scale)%u,j=(t/2+s.centerY*s.scale)%u;for(let f=w;f<e;f+=u)x.beginPath(),x.moveTo(f,0),x.lineTo(f,t),x.stroke();for(let f=j;f<t;f+=u)x.beginPath(),x.moveTo(0,f),x.lineTo(e,f),x.stroke()}if(s.showAxes){const u=b(0,0);x.strokeStyle="var(--nice-text, #333)",x.lineWidth=1,x.beginPath(),x.moveTo(0,u.y),x.lineTo(e,u.y),x.stroke(),x.beginPath(),x.moveTo(u.x,0),x.lineTo(u.x,t),x.stroke()}for(const u of n){if(!u.visible)continue;const w=`rgb(${u.color.r},${u.color.g},${u.color.b})`,j=l.includes(u.id);switch(u.type){case"point":{const f=b(u.x,u.y);x.beginPath(),x.arc(f.x,f.y,j?u.size+2:u.size,0,2*Math.PI),x.fillStyle=j?"var(--nice-primary-hover, #1976d2)":w,x.fill(),u.label&&(x.fillStyle="var(--nice-text, #333)",x.font="12px sans-serif",x.fillText(u.label,f.x+8,f.y-8));break}case"segment":{const f=a.getPoint(u.point1Id),v=a.getPoint(u.point2Id);if(f&&v){const R=b(f.x,f.y),C=b(v.x,v.y);x.strokeStyle=w,x.lineWidth=u.width,x.beginPath(),x.moveTo(R.x,R.y),x.lineTo(C.x,C.y),x.stroke()}break}case"line":{const f=a.getPoint(u.point1Id),v=a.getPoint(u.point2Id);if(f&&v){const R=v.x-f.x,C=v.y-f.y,M=-1e3,S=1e3,$=b(f.x+M*R,f.y+M*C),P=b(f.x+S*R,f.y+S*C);x.strokeStyle=w,x.lineWidth=u.width,x.beginPath(),x.moveTo($.x,$.y),x.lineTo(P.x,P.y),x.stroke()}break}case"circle":{const f=a.getPoint(u.centerId);if(f){const v=b(f.x,f.y),R=u.radius*s.scale;x.beginPath(),x.arc(v.x,v.y,R,0,2*Math.PI),u.fill&&(x.fillStyle=`rgba(${u.fill.r},${u.fill.g},${u.fill.b},${u.fill.a??.2})`,x.fill()),x.strokeStyle=w,x.lineWidth=u.width,x.stroke()}break}case"polygon":{const f=u.pointIds.map(v=>a.getPoint(v)).filter(Boolean);if(f.length>0){x.beginPath();const v=b(f[0].x,f[0].y);x.moveTo(v.x,v.y);for(let R=1;R<f.length;R++){const C=b(f[R].x,f[R].y);x.lineTo(C.x,C.y)}x.closePath(),u.fill&&(x.fillStyle=`rgba(${u.fill.r},${u.fill.g},${u.fill.b},${u.fill.a??.2})`,x.fill()),x.strokeStyle=w,x.lineWidth=u.width,x.stroke()}break}}}if(p.length>0){x.fillStyle="rgba(25, 118, 210, 0.3)";for(const u of p){const w=a.getPoint(u);if(w){const j=b(w.x,w.y);x.beginPath(),x.arc(j.x,j.y,12,0,2*Math.PI),x.fill()}}}}},[n,s,e,t,l,p,a,b]),jsxRuntime.jsx("canvas",{ref:r,width:e,height:t,style:styles.canvas,onClick:g})}function StatusBar({width:e,height:t}){const{tool:r,elements:a,view:n,service:o}=useGeometry(),[s,l]=react.useState(null),c={select:"Select",point:"Point",line:"Line",ray:"Ray",segment:"Segment",circle:"Circle",arc:"Arc",polygon:"Polygon",angle:"Angle",perpendicular:"Perpendicular",parallel:"Parallel",bisector:"Angle Bisector",midpoint:"Midpoint",tangent:"Tangent",intersection:"Intersection",reflect:"Reflect",rotate:"Rotate",translate:"Translate",dilate:"Dilate",measure:"Measure",text:"Text"},i=a.filter(p=>p.type==="point").length;return jsxRuntime.jsxs("div",{style:styles.statusBar,children:[jsxRuntime.jsxs("span",{children:["Tool: ",c[r]]}),jsxRuntime.jsx("span",{style:{margin:"0 16px"},children:"|"}),jsxRuntime.jsxs("span",{children:["Objects: ",a.length]}),jsxRuntime.jsx("span",{style:{margin:"0 16px"},children:"|"}),jsxRuntime.jsxs("span",{children:["Points: ",i]}),jsxRuntime.jsx("span",{style:{margin:"0 16px"},children:"|"}),jsxRuntime.jsxs("span",{children:["Scale: ",n.scale.toFixed(1),"x"]})]})}exports.CalculatorService=CalculatorService;exports.CalculusOps=CalculusOps;exports.EQUATION_TEMPLATES=EQUATION_TEMPLATES;exports.ExpressionParser=ExpressionParser;exports.FUNCTION_PRESETS=FUNCTION_PRESETS;exports.GeoMath=GeoMath;exports.GeometryService=GeometryService;exports.GraphService=GraphService;exports.MATH_SYMBOLS=MATH_SYMBOLS;exports.MathEditorService=MathEditorService;exports.MatrixOps=MatrixOps;exports.NiceCalculator=NiceCalculator;exports.NiceGeometry=NiceGeometry;exports.NiceGraphPlotter=NiceGraphPlotter;exports.NiceMathEditor=NiceMathEditor;exports.createCalculatorService=createCalculatorService;exports.createGeometryService=createGeometryService;exports.createGraphService=createGraphService;exports.createMathEditorService=createMathEditorService;exports.getSymbolsByCategory=getSymbolsByCategory;exports.recognizeHandwriting=recognizeHandwriting;exports.useCalculator=useCalculator;exports.useGeometry=useGeometry;exports.useGraph=useGraph;exports.useMathEditor=useMathEditor;