@nice2dev/ui-math 1.2.1 → 1.2.2

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 pe=Object.defineProperty;var ue=(e,t,r)=>t in e?pe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var B=(e,t,r)=>ue(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),L=require("@nice2dev/ui"),$=require("@nice2dev/ui-core"),y=require("react"),_={en:{"calculator.matrixA":"Matrix A","calculator.matrixB":"Matrix B","calculator.exprPlaceholder":"Enter expression (e.g., x^2, sin(x))","calculator.differentiate":"Differentiate","calculator.integrate":"Integrate","calculator.convert":"Convert","plotter.quickAdd":"Quick add preset...","plotter.noPlots":"No plots added yet","plotter.grid":"Grid","plotter.axes":"Axes","editor.latexPlaceholder":"Enter LaTeX equation...","editor.clear":"Clear","editor.recognize":"Recognize","editor.recognizing":"Recognizing...","editor.latexInput":"LaTeX Input","editor.handwriting":"Handwriting","editor.handwritingNote":"Draw your equation above. Handwriting recognition requires external API integration.","editor.templates":"Templates","editor.copyLatex":"Copy LaTeX","plotter.close":"Close"},pl:{"calculator.matrixA":"Macierz A","calculator.matrixB":"Macierz B","calculator.exprPlaceholder":"Wprowadź wyrażenie (np. x^2, sin(x))","calculator.differentiate":"Różniczkuj","calculator.integrate":"Całkuj","calculator.convert":"Przelicz","plotter.quickAdd":"Szybko dodaj ustawienie...","plotter.noPlots":"Nie dodano jeszcze żadnych wykresów","plotter.grid":"Siatka","plotter.axes":"Osie","editor.latexPlaceholder":"Wprowadź równanie LaTeX...","editor.clear":"Wyczyść","editor.recognize":"Rozpoznaj","editor.recognizing":"Rozpoznawanie...","editor.latexInput":"Wpis LaTeX","editor.handwriting":"Pismo odręczne","editor.handwritingNote":"Narysuj równanie powyżej. Rozpoznawanie pisma wymaga zewnętrznej integracji API.","editor.templates":"Szablony","editor.copyLatex":"Kopiuj LaTeX","plotter.close":"Zamknij"},de:{"calculator.matrixA":"Matrix A","calculator.matrixB":"Matrix B","calculator.exprPlaceholder":"Ausdruck eingeben (z. B. x^2, sin(x))","calculator.differentiate":"Ableiten","calculator.integrate":"Integrieren","calculator.convert":"Umrechnen","plotter.quickAdd":"Voreinstellung schnell hinzufügen...","plotter.noPlots":"Noch keine Diagramme hinzugefügt","plotter.grid":"Raster","plotter.axes":"Achsen","editor.latexPlaceholder":"LaTeX-Gleichung eingeben...","editor.clear":"Löschen","editor.recognize":"Erkennen","editor.recognizing":"Erkennung läuft...","editor.latexInput":"LaTeX-Eingabe","editor.handwriting":"Handschrift","editor.handwritingNote":"Zeichnen Sie Ihre Gleichung oben. Die Handschrifterkennung erfordert eine externe API-Integration.","editor.templates":"Vorlagen","editor.copyLatex":"LaTeX kopieren","plotter.close":"Schließen"},fr:{"calculator.matrixA":"Matrice A","calculator.matrixB":"Matrice B","calculator.exprPlaceholder":"Saisir une expression (ex. x^2, sin(x))","calculator.differentiate":"Dériver","calculator.integrate":"Intégrer","calculator.convert":"Convertir","plotter.quickAdd":"Ajouter un préréglage rapide...","plotter.noPlots":"Aucun tracé ajouté pour le moment","plotter.grid":"Grille","plotter.axes":"Axes","editor.latexPlaceholder":"Saisir une équation LaTeX...","editor.clear":"Effacer","editor.recognize":"Reconnaître","editor.recognizing":"Reconnaissance...","editor.latexInput":"Saisie LaTeX","editor.handwriting":"Écriture manuscrite","editor.handwritingNote":"Dessinez votre équation ci-dessus. La reconnaissance d'écriture nécessite une intégration API externe.","editor.templates":"Modèles","editor.copyLatex":"Copier le LaTeX","plotter.close":"Fermer"},es:{"calculator.matrixA":"Matriz A","calculator.matrixB":"Matriz B","calculator.exprPlaceholder":"Introduce una expresión (p. ej. x^2, sin(x))","calculator.differentiate":"Derivar","calculator.integrate":"Integrar","calculator.convert":"Convertir","plotter.quickAdd":"Añadir preajuste rápido...","plotter.noPlots":"Aún no se ha añadido ningún gráfico","plotter.grid":"Cuadrícula","plotter.axes":"Ejes","editor.latexPlaceholder":"Introduce una ecuación LaTeX...","editor.clear":"Borrar","editor.recognize":"Reconocer","editor.recognizing":"Reconociendo...","editor.latexInput":"Entrada LaTeX","editor.handwriting":"Escritura a mano","editor.handwritingNote":"Dibuja tu ecuación arriba. El reconocimiento de escritura requiere integración con una API externa.","editor.templates":"Plantillas","editor.copyLatex":"Copiar LaTeX","plotter.close":"Cerrar"},it:{"calculator.matrixA":"Matrice A","calculator.matrixB":"Matrice B","calculator.exprPlaceholder":"Inserisci un’espressione (es. x^2, sin(x))","calculator.differentiate":"Derivare","calculator.integrate":"Integrare","calculator.convert":"Converti","plotter.quickAdd":"Aggiungi un preset rapido...","plotter.noPlots":"Nessun grafico aggiunto","plotter.grid":"Griglia","plotter.axes":"Assi","editor.latexPlaceholder":"Inserisci un’equazione LaTeX...","editor.clear":"Cancella","editor.recognize":"Riconosci","editor.recognizing":"Riconoscimento...","editor.latexInput":"Input LaTeX","editor.handwriting":"Scrittura a mano","editor.handwritingNote":"Disegna la tua equazione qui sopra. Il riconoscimento della scrittura richiede un’integrazione API esterna.","editor.templates":"Modelli","editor.copyLatex":"Copia LaTeX","plotter.close":"Chiudi"},pt:{"calculator.matrixA":"Matriz A","calculator.matrixB":"Matriz B","calculator.exprPlaceholder":"Introduza uma expressão (p. ex. x^2, sin(x))","calculator.differentiate":"Derivar","calculator.integrate":"Integrar","calculator.convert":"Converter","plotter.quickAdd":"Adicionar predefinição rápida...","plotter.noPlots":"Ainda não foram adicionados gráficos","plotter.grid":"Grelha","plotter.axes":"Eixos","editor.latexPlaceholder":"Introduza uma equação LaTeX...","editor.clear":"Limpar","editor.recognize":"Reconhecer","editor.recognizing":"A reconhecer...","editor.latexInput":"Entrada LaTeX","editor.handwriting":"Escrita à mão","editor.handwritingNote":"Desenhe a sua equação acima. O reconhecimento de escrita requer integração com uma API externa.","editor.templates":"Modelos","editor.copyLatex":"Copiar LaTeX","plotter.close":"Fechar"},cs:{"calculator.matrixA":"Matice A","calculator.matrixB":"Matice B","calculator.exprPlaceholder":"Zadejte výraz (např. x^2, sin(x))","calculator.differentiate":"Derivovat","calculator.integrate":"Integrovat","calculator.convert":"Převést","plotter.quickAdd":"Rychle přidat předvolbu...","plotter.noPlots":"Zatím nebyl přidán žádný graf","plotter.grid":"Mřížka","plotter.axes":"Osy","editor.latexPlaceholder":"Zadejte rovnici v LaTeXu...","editor.clear":"Vymazat","editor.recognize":"Rozpoznat","editor.recognizing":"Rozpoznávání...","editor.latexInput":"Zadání LaTeX","editor.handwriting":"Rukopis","editor.handwritingNote":"Nakreslete svou rovnici výše. Rozpoznávání rukopisu vyžaduje externí integraci API.","editor.templates":"Šablony","editor.copyLatex":"Kopírovat LaTeX","plotter.close":"Zavřít"},uk:{"calculator.matrixA":"Матриця A","calculator.matrixB":"Матриця B","calculator.exprPlaceholder":"Введіть вираз (напр. x^2, sin(x))","calculator.differentiate":"Диференціювати","calculator.integrate":"Інтегрувати","calculator.convert":"Перетворити","plotter.quickAdd":"Швидко додати пресет...","plotter.noPlots":"Поки що не додано жодного графіка","plotter.grid":"Сітка","plotter.axes":"Осі","editor.latexPlaceholder":"Введіть рівняння в LaTeX...","editor.clear":"Очистити","editor.recognize":"Розпізнати","editor.recognizing":"Розпізнавання...","editor.latexInput":"Введення LaTeX","editor.handwriting":"Рукопис","editor.handwritingNote":"Намалюйте своє рівняння вище. Розпізнавання рукопису потребує зовнішньої інтеграції з API.","editor.templates":"Шаблони","editor.copyLatex":"Копіювати LaTeX","plotter.close":"Закрити"}},Z=y.createContext({locale:"en",t:(e,t)=>t??e});function xe({locale:e="en",overrides:t,children:r}){const o=y.useMemo(()=>{const a={..._.en,..._[e],...t};return{locale:e,t:(i,l)=>a[i]??l??i}},[e,t]);return y.createElement(Z.Provider,{value:o},r)}function E(){return y.useContext(Z)}const ge=[{target:".nice-math-editor",titleKey:"tutorial.mathEditor.intro.title",title:"Math editor",contentKey:"tutorial.mathEditor.intro.content",content:"Write equations as LaTeX or insert symbols from the palette; switch to handwriting input, and preview the rendered formula live.",placement:"auto"}],Q=[{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 J(e){return Q.filter(t=>t.category===e)}const ee=[{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 te{constructor(t={}){B(this,"equations",new Map);B(this,"config");B(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 o={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(o.id,o),o}updateEquation(t,r,o){const a=this.equations.get(t);if(!a)throw new Error(`Equation not found: ${t}`);const n={...a,latex:r,label:o??a.label,updatedAt:new Date().toISOString()};return this.equations.set(t,n),n}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=[],o=/\\\[([\s\S]*?)\\\]/g;let a;for(;(a=o.exec(t))!==null;)r.push(this.createEquation(a[1].trim()));const n=/\\begin\{equation\}([\s\S]*?)\\end\{equation\}/g;for(;(a=n.exec(t))!==null;){const i=a[1].match(/\\label\{([^}]+)\}/),l=a[1].replace(/\\label\{[^}]+\}/,"").trim();r.push(this.createEquation(l,i==null?void 0:i[1]))}return r}generateId(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}}function me(e){return new te(e)}async function re(e){return await new Promise(r=>setTimeout(r,500)),{latex:e.reduce((r,o)=>r+o.points.length,0)>50?"\\sqrt{x^2 + y^2}":"x",confidence:.85,alternatives:["x","X","\\times"]}}const oe=y.createContext(null);function G(){const e=y.useContext(oe);if(!e)throw new Error("useMathEditor must be used within MathEditorProvider");return e}const T={toolbar:{display:"flex",gap:"8px",padding:"8px",borderBottom:"1px solid var(--nice-border, #e0e0e0)",backgroundColor:"var(--nice-bg-secondary, #fafafa)",flexWrap:"wrap",alignItems:"center"},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 ye({service:e,initialLatex:t="",onChange:r,className:o,style:a,tutorial:n}){const{t:i}=E(),[l,u]=y.useState(t),[c,p]=y.useState("input"),m=y.useRef(null),h=y.useCallback(v=>{u(v),r==null||r(v)},[r]),b=y.useCallback(v=>{const d=m.current;if(!d){h(l+v);return}const x=d.selectionStart,w=d.selectionEnd,S=l.slice(0,x)+v+l.slice(w);h(S),setTimeout(()=>{d.focus(),d.selectionStart=d.selectionEnd=x+v.length},0)},[l,h]),C=y.useCallback(v=>{b(v.latex)},[b]),g={service:e,latex:l,setLatex:h,insertSymbol:b,insertTemplate:C,mode:c,setMode:p};return s.jsx(oe.Provider,{value:g,children:s.jsxs(L.NiceAppShell,{flush:!0,className:`nice-math-editor ${o??""}`,style:{position:"relative",...a},toolbar:s.jsx(he,{}),sidebar:s.jsx(fe,{}),children:[s.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:s.jsx($.NiceTutorialButton,{steps:$.resolveTutorial(n,ge)})}),s.jsx("div",{style:T.editor,children:c==="input"?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{ref:m,value:l,onChange:v=>h(v.target.value),placeholder:i("editor.latexPlaceholder","Enter LaTeX equation..."),style:T.input}),s.jsx(be,{latex:l})]}):s.jsx(ve,{})})]})})}function he(){const{t:e}=E(),{mode:t,setMode:r,latex:o,insertTemplate:a}=G(),[n,i]=y.useState(!1);return s.jsxs("div",{style:T.toolbar,children:[s.jsxs("button",{onClick:()=>r("input"),style:{...T.button,backgroundColor:t==="input"?"var(--nice-primary-hover, #1976d2)":"var(--nice-bg-tertiary, #9e9e9e)",color:t==="input"?"var(--nice-color-white, #fff)":"var(--nice-text-primary, #fff)"},children:[s.jsx(L.NiceIcon,{name:"keyboard",size:14})," ",e("editor.latexInput","LaTeX Input")]}),s.jsxs("button",{onClick:()=>r("handwriting"),style:{...T.button,backgroundColor:t==="handwriting"?"var(--nice-primary-hover, #1976d2)":"var(--nice-bg-tertiary, #9e9e9e)",color:t==="handwriting"?"var(--nice-color-white, #fff)":"var(--nice-text-primary, #fff)"},children:[s.jsx(L.NiceIcon,{name:"pen",size:14})," ",e("editor.handwriting","Handwriting")]}),s.jsx("div",{style:{borderLeft:"1px solid var(--nice-border, #ccc)",height:"24px",margin:"0 8px"}}),s.jsxs("div",{style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>i(!n),style:T.button,children:[s.jsx(L.NiceIcon,{name:"ruler",size:14})," ",e("editor.templates","Templates")," ",s.jsx(L.NiceIcon,{name:"chevron-down",size:12})]}),n&&s.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(l=>s.jsxs("div",{children:[s.jsx("div",{style:T.categoryHeader,children:l}),ee.filter(u=>u.category===l).map(u=>s.jsxs("div",{onClick:()=>{a(u),i(!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:[s.jsx("div",{style:{fontWeight:500},children:u.name}),s.jsxs("div",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",fontFamily:"monospace"},children:[u.latex.substring(0,40),u.latex.length>40?"...":""]})]},u.name))]},l))})]}),s.jsx("div",{style:{flex:1}}),s.jsxs("button",{onClick:()=>navigator.clipboard.writeText(o),style:{...T.button,backgroundColor:"var(--nice-success, #4caf50)"},children:[s.jsx(L.NiceIcon,{name:"copy",size:14})," ",e("editor.copyLatex","Copy LaTeX")]})]})}function fe(){const{insertSymbol:e}=G(),[t,r]=y.useState("greek"),o=["greek","operators","relations","arrows","functions","accents","delimiters","sets","logic","calculus","matrices"],a=J(t);return s.jsxs("div",{style:T.sidebar,children:[s.jsx("div",{style:{display:"flex",flexWrap:"wrap",padding:"8px",gap:"4px"},children:o.map(n=>s.jsx("button",{onClick:()=>r(n),style:{padding:"4px 8px",fontSize:"11px",border:"1px solid var(--nice-border, #ddd)",borderRadius:"4px",backgroundColor:t===n?"var(--nice-primary-hover, #1976d2)":"var(--nice-bg, #fff)",color:t===n?"var(--nice-color-white, #fff)":"var(--nice-text, #333)",cursor:"pointer"},children:n},n))}),s.jsx("div",{style:T.symbolGrid,children:a.map(n=>s.jsx("button",{onClick:()=>e(n.latex),style:T.symbolButton,title:`${n.name}: ${n.latex}`,children:n.preview||n.latex},n.name))})]})}function be({latex:e}){return s.jsxs("div",{style:T.preview,children:[s.jsx("div",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",marginBottom:"8px"},children:"Preview (requires KaTeX/MathJax integration):"}),s.jsx("code",{style:{fontSize:"16px"},children:e||"(empty)"})]})}function ve(){const{t:e}=E(),{setLatex:t,setMode:r}=G(),o=y.useRef(null),[a,n]=y.useState([]),[i,l]=y.useState([]),[u,c]=y.useState(!1),[p,m]=y.useState(!1),h=d=>{const x=o.current;if(!x)return;c(!0);const w=x.getBoundingClientRect();l([{x:d.clientX-w.left,y:d.clientY-w.top,pressure:d.pressure,timestamp:Date.now()}])},b=d=>{if(!u)return;const x=o.current,w=x==null?void 0:x.getContext("2d");if(!x||!w)return;const S=x.getBoundingClientRect(),f={x:d.clientX-S.left,y:d.clientY-S.top,pressure:d.pressure,timestamp:Date.now()};if(l(k=>[...k,f]),i.length>0){const k=i[i.length-1];w.beginPath(),w.moveTo(k.x,k.y),w.lineTo(f.x,f.y),w.strokeStyle=$.resolveCssColor("var(--nice-text, #000)",w.canvas),w.lineWidth=2,w.lineCap="round",w.stroke()}},C=()=>{if(u){if(c(!1),i.length>1){const d={id:Date.now().toString(),points:[...i]};n(x=>[...x,d])}l([])}},g=()=>{const d=o.current,x=d==null?void 0:d.getContext("2d");x&&d&&x.clearRect(0,0,d.width,d.height),n([])},v=async()=>{if(a.length!==0){m(!0);try{const d=await re(a);t(d.latex),r("input")}finally{m(!1)}}};return y.useEffect(()=>{const d=o.current;d&&(d.width=d.offsetWidth,d.height=200)},[]),s.jsxs("div",{children:[s.jsx("canvas",{ref:o,style:T.canvas,onPointerDown:h,onPointerMove:b,onPointerUp:C,onPointerLeave:C}),s.jsxs("div",{style:{display:"flex",gap:"8px",marginTop:"12px"},children:[s.jsx("button",{onClick:g,style:{...T.button,backgroundColor:"var(--nice-danger, #f44336)"},children:e("editor.clear","Clear")}),s.jsx("button",{onClick:v,disabled:a.length===0||p,style:T.button,children:p?e("editor.recognizing","Recognizing..."):e("editor.recognize","Recognize")})]}),s.jsx("p",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",marginTop:"8px"},children:e("editor.handwritingNote","Draw your equation above. Handwriting recognition requires external API integration.")})]})}const we={pi:Math.PI,PI:Math.PI,e:Math.E,E:Math.E,phi:(1+Math.sqrt(5))/2,tau:Math.PI*2},ke={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 U{constructor(t={}){B(this,"pos",0);B(this,"expr","");B(this,"options");this.options=t}parse(t){this.expr=t.replace(/\s+/g,"").replace(/×/g,"*").replace(/÷/g,"/").replace(/−/g,"-").replace(/π/g,"pi").replace(/√(\d+(?:\.\d+)?)/g,"sqrt($1)").replace(/√/g,"sqrt"),this.pos=0;const r=this.parseAddSub();if(this.options.strict&&this.pos<this.expr.length)throw new Error(`Unexpected "${this.expr.slice(this.pos)}"`);return o=>this.evaluate(r,o)}parseAddSub(){let t=this.parseMulDiv();for(;this.pos<this.expr.length;){const r=this.expr[this.pos];if(r!=="+"&&r!=="-")break;this.pos++;const o=this.parseMulDiv();t={type:"binary",op:r,left:t,right:o}}return t}parseMulDiv(){let t=this.parseUnary();for(;this.pos<this.expr.length;){const r=this.expr[this.pos];if(r==="*"||r==="/")this.pos++,t={type:"binary",op:r,left:t,right:this.parseUnary()};else if(/[0-9a-zA-Z_(]/.test(r))t={type:"binary",op:"*",left:t,right:this.parsePower()};else break}return t}parseUnary(){return this.expr[this.pos]==="-"?(this.pos++,{type:"unary",arg:this.parseUnary()}):this.expr[this.pos]==="+"?(this.pos++,this.parseUnary()):this.parsePower()}parsePower(){const t=this.parsePrimary();return this.expr[this.pos]==="^"?(this.pos++,{type:"binary",op:"^",left:t,right:this.parseUnary()}):t}parsePrimary(){if(this.expr[this.pos]==="("){this.pos++;const o=this.parseAddSub();if(this.expr[this.pos]===")")this.pos++;else if(this.options.strict)throw new Error('Missing ")"');return o}const t=this.expr.slice(this.pos).match(/^(\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/);if(t)return this.pos+=t[0].length,{type:"number",value:parseFloat(t[0])};const r=this.expr.slice(this.pos).match(/^([a-zA-Z_][a-zA-Z0-9_]*)/);if(r){const o=r[1];if(this.pos+=o.length,this.expr[this.pos]==="("){this.pos++;const a=[];for(;this.expr[this.pos]!==")"&&this.pos<this.expr.length;)if(a.push(this.parseAddSub()),this.expr[this.pos]===",")this.pos++;else if(this.expr[this.pos]!==")")break;if(this.expr[this.pos]===")")this.pos++;else if(this.options.strict)throw new Error('Missing ")"');return{type:"call",name:o,args:a}}return{type:"variable",name:o}}if(this.options.strict)throw new Error(this.pos<this.expr.length?`Unexpected "${this.expr[this.pos]}"`:"Unexpected end");return{type:"number",value:0}}lookup(t,r){if(r in t)return t[r];if(this.options.ignoreCase){const o=r.toLowerCase(),a=Object.keys(t).find(n=>n.toLowerCase()===o);return a===void 0?void 0:t[a]}}evaluate(t,r){switch(t.type){case"number":return t.value;case"variable":{if(t.name in r)return r[t.name];const o=this.lookup({...we,...this.options.constants},t.name);if(o!==void 0)return o;throw new Error(`Unknown variable: ${t.name}`)}case"unary":return-this.evaluate(t.arg,r);case"binary":{const o=this.evaluate(t.left,r),a=this.evaluate(t.right,r);switch(t.op){case"+":return o+a;case"-":return o-a;case"*":return o*a;case"/":return o/a;case"^":return Math.pow(o,a);default:return 0}}case"call":{const o=this.lookup({...ke,...this.options.functions},t.name);if(!o)throw new Error(`Unknown function: ${t.name}`);const a=t.args.map(n=>this.evaluate(n,r));return o(...a)}default:return 0}}}class ae{constructor(t={}){B(this,"plots",new Map);B(this,"parser",new U);B(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 o=this.plots.get(t);if(!o)throw new Error(`Plot not found: ${t}`);const a={...o,...r,id:o.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,o,a){const n=this.parser.parse(t),i=[],l=(r.max-r.min)/o;for(let u=0;u<=o;u++){const c=r.min+u*l;try{const p=n({x:c,...a});Number.isFinite(p)&&i.push({x:c,y:p})}catch{}}return i}compute2DParametric(t,r,o,a,n){const i=this.parser.parse(t),l=this.parser.parse(r),u=[],c=(o.max-o.min)/a;for(let p=0;p<=a;p++){const m=o.min+p*c;try{const h=i({t:m,...n}),b=l({t:m,...n});Number.isFinite(h)&&Number.isFinite(b)&&u.push({x:h,y:b})}catch{}}return u}compute2DPolar(t,r,o,a){const n=this.parser.parse(t),i=[],l=(r.max-r.min)/o;for(let u=0;u<=o;u++){const c=r.min+u*l;try{const p=n({theta:c,t:c,...a});if(Number.isFinite(p)){const m=p*Math.cos(c),h=p*Math.sin(c);i.push({x:m,y:h})}}catch{}}return i}compute3DSurface(t,r,o,a,n){const i=this.parser.parse(t),l=[],u=(r.max-r.min)/a,c=(o.max-o.min)/a;for(let p=0;p<=a;p++){const m=[],h=r.min+p*u;for(let b=0;b<=a;b++){const C=o.min+b*c;try{const g=i({x:h,y:C,...n});Number.isFinite(g)?m.push({x:h,y:C,z:g}):m.push({x:h,y:C,z:0})}catch{m.push({x:h,y:C,z:0})}}l.push(m)}return l}exportSVG(t,r,o,a){const i=o-80,l=a-80,u=m=>40+(m-r.xRange.min)/(r.xRange.max-r.xRange.min)*i,c=m=>a-40-(m-r.yRange.min)/(r.yRange.max-r.yRange.min)*l,p=[`<svg xmlns="http://www.w3.org/2000/svg" width="${o}" 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="var(--nice-border, #ddd)" stroke-width="0.5">');for(let m=Math.ceil(r.xRange.min);m<=r.xRange.max;m++){const h=u(m);p.push(`<line x1="${h}" y1="40" x2="${h}" y2="${a-40}"/>`)}for(let m=Math.ceil(r.yRange.min);m<=r.yRange.max;m++){const h=c(m);p.push(`<line x1="40" y1="${h}" x2="${o-40}" y2="${h}"/>`)}p.push("</g>")}if(r.showAxes){p.push('<g stroke="var(--nice-text, #333)" stroke-width="1">');const m=c(0),h=u(0);p.push(`<line x1="40" y1="${m}" x2="${o-40}" y2="${m}"/>`),p.push(`<line x1="${h}" y1="40" x2="${h}" y2="${a-40}"/>`),p.push("</g>")}for(const m of t.filter(h=>h.visible))if(m.type==="2d-function"){const h=this.compute2DFunction(m.expression,r.xRange,m.resolution||200);if(h.length>0){const b=h.map((C,g)=>`${g===0?"M":"L"}${u(C.x)},${c(C.y)}`).join(" ");p.push(`<path d="${b}" fill="none" stroke="rgb(${m.color.r},${m.color.g},${m.color.b})" stroke-width="${m.lineWidth}"/>`)}}return r.showLabels&&(p.push(`<text x="${o/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,o,a){const n=this.exportSVG(t,r,o,a);return new Promise((i,l)=>{const u=new Image;u.onload=()=>{const c=document.createElement("canvas");c.width=o,c.height=a;const p=c.getContext("2d");if(!p){l(new Error("Could not get canvas context"));return}p.drawImage(u,0,0),i(c.toDataURL("image/png"))},u.onerror=l,u.src="data:image/svg+xml;base64,"+btoa(n)})}generateId(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}}function Ce(e){return new ae(e)}const O=[{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"}],ne=y.createContext(null);function D(){const e=y.useContext(ne);if(!e)throw new Error("useGraph must be used within GraphProvider");return e}const j={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 Se({service:e,width:t=800,height:r=600,className:o,style:a}){const[n,i]=y.useState([]),[l,u]=y.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}),[c,p]=y.useState({isPlaying:!1,parameter:"a",currentValue:0,minValue:-5,maxValue:5,speed:1}),m=y.useCallback(()=>{i(e.getPlots())},[e]),h=y.useCallback(x=>{u(w=>({...w,...x}))},[]),b=y.useCallback(x=>{p(w=>({...w,...x}))},[]),C=y.useCallback(x=>{e.addPlot(x),m()},[e,m]),g=y.useCallback(x=>{e.removePlot(x),m()},[e,m]),v=y.useCallback((x,w)=>{e.updatePlot(x,w),m()},[e,m]),d={service:e,plots:n,view:l,setView:h,addPlot:C,removePlot:g,updatePlot:v,animation:c,setAnimation:b,refresh:m};return s.jsx(ne.Provider,{value:d,children:s.jsxs("div",{className:o,style:{...j.container,...a},children:[s.jsxs("div",{style:j.sidebar,children:[s.jsx(Me,{}),s.jsx(Pe,{})]}),s.jsxs("div",{style:j.main,children:[s.jsx(je,{width:t,height:r}),s.jsx(Be,{width:t,height:r})]})]})})}function Me(){const{t:e}=E(),{addPlot:t}=D(),[r,o]=y.useState("sin(x)"),[a,n]=y.useState("2d-function"),[i,l]=y.useState("cos(x)"),u=()=>{t({type:a,expression:r,expressionY:a==="2d-parametric"?i:void 0,color:{r:Math.floor(Math.random()*200),g:Math.floor(Math.random()*200),b:Math.floor(Math.random()*200)}})};return s.jsxs("div",{style:{padding:"12px",borderBottom:"1px solid var(--nice-border, #e0e0e0)"},children:[s.jsx("div",{style:{marginBottom:"8px"},children:s.jsxs("select",{value:a,onChange:c=>n(c.target.value),style:{...j.input,width:"100%"},children:[s.jsx("option",{value:"2d-function",children:"y = f(x)"}),s.jsx("option",{value:"2d-parametric",children:"Parametric (x(t), y(t))"}),s.jsx("option",{value:"2d-polar",children:"Polar r = f(θ)"}),s.jsx("option",{value:"3d-surface",children:"3D Surface z = f(x,y)"})]})}),s.jsx("div",{style:{marginBottom:"8px"},children:s.jsx("input",{type:"text",value:r,onChange:c=>o(c.target.value),placeholder:a==="2d-parametric"?"x(t) = ...":"Expression...",style:{...j.input,width:"100%"}})}),a==="2d-parametric"&&s.jsx("div",{style:{marginBottom:"8px"},children:s.jsx("input",{type:"text",value:i,onChange:c=>l(c.target.value),placeholder:"y(t) = ...",style:{...j.input,width:"100%"}})}),s.jsx("button",{onClick:u,style:{...j.button,width:"100%"},children:"+ Add Plot"}),s.jsxs("select",{onChange:c=>{const p=O.find(m=>m.name===c.target.value);p&&t({type:p.type,expression:p.expression,expressionY:p.expressionY,label:p.name,color:{r:Math.floor(Math.random()*200),g:Math.floor(Math.random()*200),b:Math.floor(Math.random()*200)}})},style:{...j.input,width:"100%",marginTop:"8px"},value:"",children:[s.jsx("option",{value:"",disabled:!0,children:e("plotter.quickAdd","Quick add preset...")}),["basic","trigonometric","exponential","parametric","polar","3d"].map(c=>s.jsx("optgroup",{label:c.charAt(0).toUpperCase()+c.slice(1),children:O.filter(p=>p.category===c).map(p=>s.jsxs("option",{value:p.name,children:[p.name,": ",p.expression]},p.name))},c))]})]})}function Pe(){const{t:e}=E(),{plots:t,removePlot:r,updatePlot:o}=D();return s.jsxs("div",{style:j.plotList,children:[t.length===0&&s.jsx("div",{style:{color:"var(--nice-text-secondary, #666)",textAlign:"center",padding:"16px"},children:e("plotter.noPlots","No plots added yet")}),t.map(a=>s.jsxs("div",{style:j.plotItem,children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[s.jsx("input",{type:"checkbox",checked:a.visible,onChange:n=>o(a.id,{visible:n.target.checked})}),s.jsx("div",{style:{width:"16px",height:"16px",borderRadius:"3px",backgroundColor:`rgb(${a.color.r},${a.color.g},${a.color.b})`}}),s.jsx("span",{style:{flex:1,fontWeight:500},children:a.label||a.expression}),s.jsx("button",{"aria-label":e("plotter.close","Close"),onClick:()=>r(a.id),style:{padding:"2px 6px",backgroundColor:"var(--nice-danger, #f44336)",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"12px"},children:s.jsx($.NiceIcon,{name:"close",size:14})})]}),s.jsx("div",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",fontFamily:"monospace"},children:a.type==="2d-parametric"?s.jsxs(s.Fragment,{children:["x(t) = ",a.expression,s.jsx("br",{}),"y(t) = ",a.expressionY]}):a.expression})]},a.id))]})}function je({width:e,height:t}){const{t:r}=E(),{service:o,plots:a,view:n,setView:i}=D(),l=()=>{const c=o.exportSVG(a,n,e,t),p=new Blob([c],{type:"image/svg+xml"}),m=URL.createObjectURL(p),h=document.createElement("a");h.href=m,h.download="graph.svg",h.click(),URL.revokeObjectURL(m)},u=async()=>{const c=await o.exportPNG(a,n,e,t),p=document.createElement("a");p.href=c,p.download="graph.png",p.click()};return s.jsxs("div",{style:j.toolbar,children:[s.jsxs("label",{style:{fontSize:"12px"},children:["X: ["," ",s.jsx("input",{type:"number",value:n.xRange.min,onChange:c=>i({xRange:{...n.xRange,min:Number(c.target.value)}}),style:{...j.input,width:"50px"}}),","," ",s.jsx("input",{type:"number",value:n.xRange.max,onChange:c=>i({xRange:{...n.xRange,max:Number(c.target.value)}}),style:{...j.input,width:"50px"}}),"]"]}),s.jsxs("label",{style:{fontSize:"12px"},children:["Y: ["," ",s.jsx("input",{type:"number",value:n.yRange.min,onChange:c=>i({yRange:{...n.yRange,min:Number(c.target.value)}}),style:{...j.input,width:"50px"}}),","," ",s.jsx("input",{type:"number",value:n.yRange.max,onChange:c=>i({yRange:{...n.yRange,max:Number(c.target.value)}}),style:{...j.input,width:"50px"}}),"]"]}),s.jsxs("label",{style:{fontSize:"12px"},children:[s.jsx("input",{type:"checkbox",checked:n.showGrid,onChange:c=>i({showGrid:c.target.checked})}),r("plotter.grid","Grid")]}),s.jsxs("label",{style:{fontSize:"12px"},children:[s.jsx("input",{type:"checkbox",checked:n.showAxes,onChange:c=>i({showAxes:c.target.checked})}),r("plotter.axes","Axes")]}),s.jsx("div",{style:{flex:1}}),s.jsxs("button",{onClick:l,style:{...j.button,backgroundColor:"var(--nice-success, #4caf50)"},children:[s.jsx($.NiceIcon,{name:"download",size:14})," SVG"]}),s.jsxs("button",{onClick:u,style:{...j.button,backgroundColor:"var(--nice-warning, #ff9800)"},children:[s.jsx($.NiceIcon,{name:"download",size:14})," PNG"]})]})}function Be({width:e,height:t}){const r=y.useRef(null),{service:o,plots:a,view:n,animation:i}=D(),l=40;return y.useEffect(()=>{const u=r.current,c=u==null?void 0:u.getContext("2d");if(!u||!c)return;c.fillStyle=`rgb(${n.backgroundColor.r},${n.backgroundColor.g},${n.backgroundColor.b})`,c.fillRect(0,0,e,t);const p=e-l*2,m=t-l*2,h=g=>l+(g-n.xRange.min)/(n.xRange.max-n.xRange.min)*p,b=g=>t-l-(g-n.yRange.min)/(n.yRange.max-n.yRange.min)*m;if(n.showGrid){c.strokeStyle=$.resolveCssColor("var(--nice-border, #e0e0e0)",c.canvas),c.lineWidth=.5;for(let g=Math.ceil(n.xRange.min);g<=n.xRange.max;g++){const v=h(g);c.beginPath(),c.moveTo(v,l),c.lineTo(v,t-l),c.stroke()}for(let g=Math.ceil(n.yRange.min);g<=n.yRange.max;g++){const v=b(g);c.beginPath(),c.moveTo(l,v),c.lineTo(e-l,v),c.stroke()}}if(n.showAxes){c.strokeStyle=$.resolveCssColor("var(--nice-text, #333)",c.canvas),c.lineWidth=1;const g=b(0);c.beginPath(),c.moveTo(l,g),c.lineTo(e-l,g),c.stroke();const v=h(0);if(c.beginPath(),c.moveTo(v,l),c.lineTo(v,t-l),c.stroke(),n.showLabels){c.fillStyle=$.resolveCssColor("var(--nice-text, #333)",c.canvas),c.font="12px sans-serif",c.textAlign="center",c.fillText("x",e-l+15,g+4),c.fillText("y",v,l-10),c.font="10px sans-serif";for(let d=Math.ceil(n.xRange.min);d<=n.xRange.max;d++)d!==0&&c.fillText(String(d),h(d),g+15);for(let d=Math.ceil(n.yRange.min);d<=n.yRange.max;d++)d!==0&&(c.textAlign="right",c.fillText(String(d),v-5,b(d)+4))}}const C=i.isPlaying?{[i.parameter]:i.currentValue}:{};for(const g of a.filter(v=>v.visible)){const v=`rgb(${g.color.r},${g.color.g},${g.color.b})`;c.strokeStyle=v,c.lineWidth=g.lineWidth||2;let d=[];switch(g.type){case"2d-function":d=o.compute2DFunction(g.expression,n.xRange,g.resolution||200,C);break;case"2d-parametric":d=o.compute2DParametric(g.expression,g.expressionY||"sin(t)",g.parameterRange||{min:0,max:2*Math.PI},g.resolution||200,C);break;case"2d-polar":d=o.compute2DPolar(g.expression,g.parameterRange||{min:0,max:2*Math.PI},g.resolution||200,C);break}if(d.length>0){c.beginPath();let x=!1;for(const w of d){const S=h(w.x),f=b(w.y);if(f<0||f>t){x=!1;continue}x?c.lineTo(S,f):(c.moveTo(S,f),x=!0)}c.stroke()}}},[a,n,i,o,e,t]),s.jsx("canvas",{ref:r,width:e,height:t,style:j.canvas})}const N=[{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}],R={create(e,t,r=0){const o=[];for(let a=0;a<e;a++)o.push(new Array(t).fill(r));return{rows:e,cols:t,data:o}},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 o=0;o<e.rows;o++)for(let a=0;a<e.cols;a++)r.data[o][a]=e.data[o][a]+t.data[o][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 o=0;o<e.rows;o++)for(let a=0;a<e.cols;a++)r.data[o][a]=e.data[o][a]-t.data[o][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 o=0;o<e.rows;o++)for(let a=0;a<t.cols;a++){let n=0;for(let i=0;i<e.cols;i++)n+=e.data[o][i]*t.data[i][a];r.data[o][a]=n}return r},scalar(e,t){const r=this.create(e.rows,e.cols);for(let o=0;o<e.rows;o++)for(let a=0;a<e.cols;a++)r.data[o][a]=e.data[o][a]*t;return r},transpose(e){const t=this.create(e.cols,e.rows);for(let r=0;r<e.rows;r++)for(let o=0;o<e.cols;o++)t.data[o][r]=e.data[r][o];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 o=this.create(e.rows-1,e.cols-1);let a=0;for(let n=0;n<e.rows;n++){if(n===t)continue;let i=0;for(let l=0;l<e.cols;l++)l!==r&&(o.data[a][i]=e.data[n][l],i++);a++}return o},inverse(e){const t=this.determinant(e);if(t===0)throw new Error("Matrix is singular, cannot compute inverse");const r=e.rows,o=this.create(r,r);for(let a=0;a<r;a++)for(let n=0;n<r;n++){const i=Math.pow(-1,a+n),l=this.determinant(this.minor(e,a,n));o.data[n][a]=i*l}return this.scalar(o,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],o=e.data[1][0],a=e.data[1][1],n=t+a,i=t*a-r*o,l=n*n-4*i;if(l<0)throw new Error("Complex eigenvalues not supported");const u=Math.sqrt(l);return[(n+u)/2,(n-u)/2]},toString(e,t=4){return e.data.map(r=>"[ "+r.map(o=>o.toFixed(t).padStart(10)).join(" ")+" ]").join(`
4
- `)}},F={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,o=1e3){o%2!==0&&o++;const a=(r-t)/o;let n=e(t)+e(r);for(let i=1;i<o;i++){const l=t+i*a;n+=i%2===0?2*e(l):4*e(l)}return a/3*n},findRoot(e,t,r=1e-10,o=100){let a=t;for(let n=0;n<o;n++){const i=e(a);if(Math.abs(i)<r)return a;const l=this.derivative(e,a);if(l===0)throw new Error("Derivative is zero, Newton-Raphson failed");a=a-i/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 o=parseInt(t[1],10);return o===1?"1":o===2?"2*x":`${o}*x^${o-1}`}const r=e.match(/^(-?\d+\.?\d*)\*x\^(\d+)$/);if(r){const o=parseFloat(r[1]),a=parseInt(r[2],10),n=o*a;return a===1?String(n):a===2?`${n}*x`:`${n}*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 o=t*t-4*e*r;if(o<0)throw new Error("No real solutions (complex roots)");if(o===0)return[-t/(2*e)];const a=Math.sqrt(o);return[(-t+a)/(2*e),(-t-a)/(2*e)]}};class ie{constructor(t={}){B(this,"history",[]);B(this,"memory",0);B(this,"variables",new Map);B(this,"config");this.config={precision:t.precision??12,angleUnit:t.angleUnit??"rad"}}evaluate(t){const r=this.config.angleUnit==="deg",o=l=>r?l*Math.PI/180:l,a=l=>r?l*180/Math.PI:l,n=new U({strict:!0,ignoreCase:!0,functions:{log:Math.log10,sin:l=>Math.sin(o(l)),cos:l=>Math.cos(o(l)),tan:l=>Math.tan(o(l)),asin:l=>a(Math.asin(l)),acos:l=>a(Math.acos(l)),atan:l=>a(Math.atan(l))}});let i;try{i=n.parse(t)(Object.fromEntries(this.variables))}catch(l){throw new Error(`Invalid expression: ${l.message}`)}if(!Number.isFinite(i))throw new Error("Invalid expression: Invalid result");return i}addHistory(t,r,o){this.history.unshift({id:Date.now().toString(36),expression:t,result:r,timestamp:new Date().toISOString(),mode:o}),this.history.length>100&&this.history.pop()}getHistory(){return this.history}clearHistory(){this.history=[]}memoryStore(t){this.memory=t}memoryRecall(){return this.memory}memoryAdd(t){this.memory+=t}memoryClear(){this.memory=0}setVariable(t,r){this.variables.set(t,r)}getVariable(t){return this.variables.get(t)}convertBase(t,r,o){const a={BIN:2,OCT:8,DEC:10,HEX:16},n=parseInt(t,a[r]);if(isNaN(n))throw new Error("Invalid number for base conversion");return n.toString(a[o]).toUpperCase()}convertUnits(t,r,o){const a=N.find(l=>l.symbol===r),n=N.find(l=>l.symbol===o);if(!a||!n)throw new Error("Unknown unit");if(a.category!==n.category)throw new Error("Cannot convert between different unit categories");const i=a.toBase(t);return n.fromBase(i)}getUnitsByCategory(t){return N.filter(r=>r.category===t)}getUnitCategories(){return[...new Set(N.map(t=>t.category))]}format(t){const r=this.config.precision;return Math.abs(t)<1e-10?"0":Math.abs(t)>1e10||Math.abs(t)<1e-6?t.toExponential(r):parseFloat(t.toPrecision(r)).toString()}}function $e(e){return new ie(e)}const se=y.createContext(null);function I(){const e=y.useContext(se);if(!e)throw new Error("useCalculator must be used within CalculatorProvider");return e}const P={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-text-primary, #fff)",fontSize:"32px",fontFamily:"'JetBrains Mono', monospace",textAlign:"right",wordBreak:"break-all"},keypad:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:"1px",backgroundColor:"var(--nice-bg-tertiary, #333)",padding:"1px"},key:{padding:"20px",border:"none",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",fontSize:"18px",cursor:"pointer",transition:"background-color 0.1s"},keyOperator:{backgroundColor:"var(--nice-warning, #ff9f0a)",color:"var(--nice-text, #000)"},keyFunction:{backgroundColor:"var(--nice-bg-tertiary, #505050)"}};function Te({service:e,className:t,style:r}){const[o,a]=y.useState("0"),[n,i]=y.useState("standard"),[l,u]=y.useState([]),[c,p]=y.useState(!1),m=y.useCallback(g=>{c&&/[0-9.]/.test(g)?(a(g),p(!1)):(a(v=>v==="0"&&g!=="."?g:v+g),p(!1))},[c]),h=y.useCallback(()=>{a("0"),p(!1)},[]),b=y.useCallback(()=>{try{const g=e.evaluate(o),v=e.format(g);e.addHistory(o,v,n),u(e.getHistory()),a(v),p(!0)}catch{a("Error"),p(!0)}},[o,n,e]),C={service:e,display:o,setDisplay:a,mode:n,setMode:i,history:l,calculate:b,appendDigit:m,clear:h};return s.jsx(se.Provider,{value:C,children:s.jsxs("div",{className:t,style:{...P.container,...r},children:[s.jsx(Re,{}),s.jsx(Ae,{}),n==="standard"&&s.jsx(ce,{}),n==="scientific"&&s.jsx(Ee,{}),n==="programmer"&&s.jsx(ze,{}),n==="matrix"&&s.jsx(Ie,{}),n==="calculus"&&s.jsx(Le,{}),n==="units"&&s.jsx(qe,{})]})})}function Re(){const{mode:e,setMode:t}=I(),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 s.jsx("div",{style:P.modeSelector,children:r.map(o=>s.jsx("button",{onClick:()=>t(o.id),style:{...P.modeButton,backgroundColor:e===o.id?"var(--nice-primary-hover, #1976d2)":"transparent",color:e===o.id?"var(--nice-color-white, #fff)":"var(--nice-text-secondary, #888)"},children:o.label},o.id))})}function Ae(){const{display:e}=I();return s.jsx("div",{style:P.display,children:s.jsx("div",{style:P.displayText,children:e})})}function ce(){const{appendDigit:e,clear:t,calculate:r,setDisplay:o,display:a}=I(),n=[{label:"AC",action:t,style:P.keyFunction},{label:"±",action:()=>o(a.startsWith("-")?a.slice(1):"-"+a),style:P.keyFunction},{label:"%",action:()=>e("/100"),style:P.keyFunction},{label:"÷",action:()=>e("/"),style:P.keyOperator},{label:"7",action:()=>e("7")},{label:"8",action:()=>e("8")},{label:"9",action:()=>e("9")},{label:"×",action:()=>e("*"),style:P.keyOperator},{label:"4",action:()=>e("4")},{label:"5",action:()=>e("5")},{label:"6",action:()=>e("6")},{label:"−",action:()=>e("-"),style:P.keyOperator},{label:"1",action:()=>e("1")},{label:"2",action:()=>e("2")},{label:"3",action:()=>e("3")},{label:"+",action:()=>e("+"),style:P.keyOperator},{label:"0",action:()=>e("0")},{label:".",action:()=>e(".")},{label:"⌫",action:()=>o(a.length>1?a.slice(0,-1):"0")},{label:"=",action:r,style:P.keyOperator}];return s.jsx("div",{style:P.keypad,children:n.map((i,l)=>s.jsx("button",{onClick:i.action,style:{...P.key,...i.style||{}},children:i.label},l))})}function Ee(){const{appendDigit:e,clear:t,calculate:r,setDisplay:o,display:a}=I(),n=[{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(")}],i=[{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 s.jsxs("div",{children:[s.jsx("div",{style:{...P.keypad,gridTemplateColumns:"repeat(5, 1fr)"},children:[...n,...i,...l].map((u,c)=>s.jsx("button",{onClick:u.action,style:{...P.key,...P.keyFunction,padding:"12px"},children:u.label},c))}),s.jsx(ce,{})]})}function ze(){const{display:e,setDisplay:t,service:r}=I(),[o,a]=y.useState("DEC"),n=l=>{try{const u=r.convertBase(e,o,l);t(u),a(l)}catch{t("Error")}},i=o==="HEX"?["A","B","C","D","E","F"]:[];return s.jsxs("div",{children:[s.jsx("div",{style:{display:"flex",gap:"4px",padding:"8px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:["BIN","OCT","DEC","HEX"].map(l=>s.jsx("button",{onClick:()=>n(l),style:{flex:1,padding:"8px",border:"none",borderRadius:"4px",backgroundColor:o===l?"var(--nice-primary-hover, #1976d2)":"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",cursor:"pointer"},children:l},l))}),i.length>0&&s.jsx("div",{style:{...P.keypad,gridTemplateColumns:"repeat(6, 1fr)"},children:i.map(l=>s.jsx("button",{onClick:()=>t(e==="0"?l:e+l),style:P.key,children:l},l))}),s.jsx("div",{style:{...P.keypad,gridTemplateColumns:"repeat(4, 1fr)"},children:["7","8","9","AND","4","5","6","OR","1","2","3","XOR","0","NOT","<<",">>"].map(l=>{const u=["AND","OR","XOR","NOT","<<",">>"].includes(l);return s.jsx("button",{onClick:()=>t(e==="0"?l:e+l),style:{...P.key,...u?P.keyFunction:{}},children:l},l)})})]})}function Ie(){const{t:e}=E(),[t,r]=y.useState(R.create(2,2)),[o,a]=y.useState(R.create(2,2)),[n,i]=y.useState(""),l=(c,p,m,h,b)=>{const C={...c,data:c.data.map(g=>[...g])};C.data[m][h]=parseFloat(b)||0,p(C)},u=[{label:"A + B",fn:()=>R.toString(R.add(t,o))},{label:"A - B",fn:()=>R.toString(R.subtract(t,o))},{label:"A × B",fn:()=>R.toString(R.multiply(t,o))},{label:"det(A)",fn:()=>R.determinant(t).toFixed(4)},{label:"Aᵀ",fn:()=>R.toString(R.transpose(t))},{label:"A⁻¹",fn:()=>R.toString(R.inverse(t))}];return s.jsxs("div",{style:{padding:"12px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:[s.jsxs("div",{style:{display:"flex",gap:"12px",marginBottom:"12px"},children:[s.jsxs("div",{children:[s.jsx("div",{style:{color:"var(--nice-text-secondary, #888)",marginBottom:"4px"},children:e("calculator.matrixA","Matrix A")}),s.jsx(K,{matrix:t,onChange:(c,p,m)=>l(t,r,c,p,m)})]}),s.jsxs("div",{children:[s.jsx("div",{style:{color:"var(--nice-text-secondary, #888)",marginBottom:"4px"},children:e("calculator.matrixB","Matrix B")}),s.jsx(K,{matrix:o,onChange:(c,p,m)=>l(o,a,c,p,m)})]})]}),s.jsx("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginBottom:"12px"},children:u.map(c=>s.jsx("button",{onClick:()=>{try{i(c.fn())}catch(p){i(p.message)}},style:{padding:"8px 12px",backgroundColor:"var(--nice-primary-hover, #1976d2)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:"4px",cursor:"pointer"},children:c.label},c.label))}),n&&s.jsx("pre",{style:{color:"var(--nice-text-primary, #fff)",fontFamily:"monospace",whiteSpace:"pre-wrap"},children:n})]})}function K({matrix:e,onChange:t}){return s.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${e.cols}, 50px)`,gap:"4px"},children:e.data.map((r,o)=>r.map((a,n)=>s.jsx("input",{type:"number",value:a,onChange:i=>t(o,n,i.target.value),style:{width:"100%",padding:"4px",textAlign:"center",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"}},`${o}-${n}`)))})}function Le(){const{t:e}=E(),[t,r]=y.useState("x^2"),[o,a]=y.useState("");return s.jsxs("div",{style:{padding:"12px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:[s.jsx("input",{type:"text",value:t,onChange:n=>r(n.target.value),placeholder:e("calculator.exprPlaceholder","Enter expression (e.g., x^2, sin(x))"),style:{width:"100%",padding:"8px",marginBottom:"12px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"}}),s.jsxs("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginBottom:"12px"},children:[s.jsx("button",{onClick:()=>a(`d/dx(${t}) = ${F.symbolicDerivative(t)}`),style:{padding:"8px 12px",backgroundColor:"var(--nice-success, #4caf50)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:"4px",cursor:"pointer"},children:e("calculator.differentiate","Differentiate")}),s.jsx("button",{onClick:()=>a(`∫(${t})dx = ${F.symbolicIntegral(t)}`),style:{padding:"8px 12px",backgroundColor:"var(--nice-primary, #2196f3)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:"4px",cursor:"pointer"},children:e("calculator.integrate","Integrate")})]}),o&&s.jsx("div",{style:{color:"var(--nice-text-primary, #fff)",fontFamily:"monospace",padding:"8px",backgroundColor:"var(--nice-bg, #1e1e1e)",borderRadius:"4px"},children:o})]})}function qe(){const{t:e}=E(),{service:t}=I(),[r,o]=y.useState("1"),[a,n]=y.useState("m"),[i,l]=y.useState("ft"),[u,c]=y.useState("Length"),[p,m]=y.useState(""),h=t.getUnitCategories(),b=t.getUnitsByCategory(u),C=()=>{try{const g=t.convertUnits(parseFloat(r),a,i);m(`${r} ${a} = ${t.format(g)} ${i}`)}catch(g){m(g.message)}};return s.jsxs("div",{style:{padding:"12px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:[s.jsx("select",{value:u,onChange:g=>{c(g.target.value);const v=t.getUnitsByCategory(g.target.value);v.length>=2&&(n(v[0].symbol),l(v[1].symbol))},style:{width:"100%",padding:"8px",marginBottom:"12px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"},children:h.map(g=>s.jsx("option",{value:g,children:g},g))}),s.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center",marginBottom:"12px"},children:[s.jsx("input",{type:"number",value:r,onChange:g=>o(g.target.value),style:{flex:1,padding:"8px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"}}),s.jsx("select",{value:a,onChange:g=>n(g.target.value),style:{padding:"8px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"},children:b.map(g=>s.jsxs("option",{value:g.symbol,children:[g.name," (",g.symbol,")"]},g.symbol))})]}),s.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center",marginBottom:"12px"},children:[s.jsx("span",{style:{color:"var(--nice-text-secondary, #888)"},children:s.jsx($.NiceIcon,{name:"arrow-right",size:12})}),s.jsx("select",{value:i,onChange:g=>l(g.target.value),style:{flex:1,padding:"8px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"},children:b.map(g=>s.jsxs("option",{value:g.symbol,children:[g.name," (",g.symbol,")"]},g.symbol))})]}),s.jsx("button",{onClick:C,style:{width:"100%",padding:"12px",backgroundColor:"var(--nice-warning, #ff9f0a)",color:"var(--nice-text, #000)",border:"none",borderRadius:"4px",fontSize:"16px",cursor:"pointer"},children:e("calculator.convert","Convert")}),p&&s.jsx("div",{style:{marginTop:"12px",color:"var(--nice-text-primary, #fff)",fontSize:"18px",textAlign:"center"},children:p})]})}const A={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 o=Math.atan2(e.y-t.y,e.x-t.x);let n=Math.atan2(r.y-t.y,r.x-t.x)-o;return n<0&&(n+=2*Math.PI),n},angleDegrees(e,t,r){return this.angle(e,t,r)*180/Math.PI},closestPointOnLine(e,t,r){const o=t.x-e.x,a=t.y-e.y,n=((r.x-e.x)*o+(r.y-e.y)*a)/(o*o+a*a);return{x:e.x+n*o,y:e.y+n*a}},lineIntersection(e,t,r,o){const a=(e.x-t.x)*(r.y-o.y)-(e.y-t.y)*(r.x-o.x);if(Math.abs(a)<1e-10)return null;const n=((e.x-r.x)*(r.y-o.y)-(e.y-r.y)*(r.x-o.x))/a;return{x:e.x+n*(t.x-e.x),y:e.y+n*(t.y-e.y)}},circleLineIntersection(e,t,r,o){const a=o.x-r.x,n=o.y-r.y,i=r.x-e.x,l=r.y-e.y,u=a*a+n*n,c=2*(i*a+l*n),p=i*i+l*l-t*t,m=c*c-4*u*p;if(m<0)return[];const h=Math.sqrt(m),b=(-c-h)/(2*u),C=(-c+h)/(2*u),g=[];return b>=0&&b<=1&&g.push({x:r.x+b*a,y:r.y+b*n}),C>=0&&C<=1&&Math.abs(C-b)>1e-10&&g.push({x:r.x+C*a,y:r.y+C*n}),g},circleCircleIntersection(e,t,r,o){const a=this.distance(e,r);if(a>t+o||a<Math.abs(t-o)||a===0)return[];const n=(t*t-o*o+a*a)/(2*a),i=Math.sqrt(t*t-n*n),l=e.x+n*(r.x-e.x)/a,u=e.y+n*(r.y-e.y)/a;return[{x:l+i*(r.y-e.y)/a,y:u-i*(r.x-e.x)/a},{x:l-i*(r.y-e.y)/a,y:u+i*(r.x-e.x)/a}]},perpendicularThrough(e,t,r){this.closestPointOnLine(e,t,r);const o=t.x-e.x,a=t.y-e.y;return{p1:r,p2:{x:r.x-a,y:r.y+o}}},parallelThrough(e,t,r){const o=t.x-e.x,a=t.y-e.y;return{p1:r,p2:{x:r.x+o,y:r.y+a}}},angleBisector(e,t,r){const o=Math.atan2(e.y-t.y,e.x-t.x),a=Math.atan2(r.y-t.y,r.x-t.x);let n=(o+a)/2;return Math.abs(a-o)>Math.PI&&(n+=Math.PI),{x:t.x+Math.cos(n),y:t.y+Math.sin(n)}},reflect(e,t,r){const o=this.closestPointOnLine(t,r,e);return{x:2*o.x-e.x,y:2*o.y-e.y}},rotate(e,t,r){const o=Math.cos(r),a=Math.sin(r),n=e.x-t.x,i=e.y-t.y;return{x:t.x+n*o-i*a,y:t.y+n*a+i*o}},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 o=0;o<r;o++){const a=(o+1)%r;t+=e[o].x*e[a].y,t-=e[a].x*e[o].y}return Math.abs(t)/2},polygonPerimeter(e){let t=0;const r=e.length;for(let o=0;o<r;o++){const a=(o+1)%r;t+=this.distance(e[o],e[a])}return t},circumcenter(e,t,r){const o=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))/o,n=((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))/o;return{x:a,y:n}},incenter(e,t,r){const o=this.distance(e,t),a=this.distance(t,r),n=this.distance(r,e),i=o+a+n;return{x:(a*e.x+n*t.x+o*r.x)/i,y:(a*e.y+n*t.y+o*r.y)/i}},centroid(e,t,r){return{x:(e.x+t.x+r.x)/3,y:(e.y+t.y+r.y)/3}}};class le{constructor(){B(this,"elements",new Map);B(this,"nextLabel",1)}addElement(t){const r=this.generateId(),o={...t,id:r};return this.elements.set(r,o),o}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 o=this.elements.get(t);o&&this.elements.set(t,{...o,...r,id:t,type:o.type})}deleteElement(t){var r;this.elements.delete(t);for(const[o,a]of this.elements)(r=a.dependencies)!=null&&r.includes(t)&&this.deleteElement(o)}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,o){return this.addElement({type:"point",x:t,y:r,label:o??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 o=this.getPoint(t),a=this.getPoint(r);if(!o||!a)return null;const n=A.midpoint(o,a),i=this.createPoint(n.x,n.y);return i.dependencies=[t,r],i.color={r:0,g:150,b:0},i}createPerpendicular(t,r,o){const a=this.getPoint(t),n=this.getPoint(r),i=this.getPoint(o);if(!a||!n||!i)return null;const l=A.perpendicularThrough(a,n,i),u=this.createPoint(l.p2.x,l.p2.y),c=this.createLine(o,u.id);return c.dependencies=[t,r,o],c}createParallel(t,r,o){const a=this.getPoint(t),n=this.getPoint(r),i=this.getPoint(o);if(!a||!n||!i)return null;const l=A.parallelThrough(a,n,i),u=this.createPoint(l.p2.x,l.p2.y),c=this.createLine(o,u.id);return c.dependencies=[t,r,o],c}createIntersection(t,r){const o=this.elements.get(t),a=this.elements.get(r);if(!o||!a)return[];const n=[],i=c=>{if(c.type==="line"||c.type==="segment"||c.type==="ray"){const p=c,m=this.getPoint(p.point1Id??p.originId),h=this.getPoint(p.point2Id??p.throughId);if(m&&h)return[m,h]}return null},l=i(o),u=i(a);if(l&&u){const c=A.lineIntersection(l[0],l[1],u[0],u[1]);if(c){const p=this.createPoint(c.x,c.y);p.dependencies=[t,r],p.color={r:255,g:0,b:0},n.push(p)}}if(o.type==="circle"&&u){const c=o,p=this.getPoint(c.centerId);if(p){const m=A.circleLineIntersection(p,c.radius,u[0],u[1]);for(const h of m){const b=this.createPoint(h.x,h.y);b.dependencies=[t,r],b.color={r:255,g:0,b:0},n.push(b)}}}if(o.type==="circle"&&a.type==="circle"){const c=o,p=a,m=this.getPoint(c.centerId),h=this.getPoint(p.centerId);if(m&&h){const b=A.circleCircleIntersection(m,c.radius,h,p.radius);for(const C of b){const g=this.createPoint(C.x,C.y);g.dependencies=[t,r],g.color={r:255,g:0,b:0},n.push(g)}}}return n}calculateMeasurement(t,r){switch(t){case"distance":{const o=this.getPoint(r[0]),a=this.getPoint(r[1]);if(o&&a)return A.distance(o,a);break}case"angle":{const o=this.getPoint(r[0]),a=this.getPoint(r[1]),n=this.getPoint(r[2]);if(o&&a&&n)return A.angleDegrees(o,a,n);break}case"area":case"perimeter":{const o=this.elements.get(r[0]);if((o==null?void 0:o.type)==="polygon"){const a=o.pointIds.map(n=>this.getPoint(n)).filter(Boolean);return t==="area"?A.polygonArea(a):A.polygonPerimeter(a)}break}}return 0}exportSVG(t,r,o){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(${o.backgroundColor.r},${o.backgroundColor.g},${o.backgroundColor.b})"/>`);const n=(i,l)=>({x:t/2+(i-o.centerX)*o.scale,y:r/2-(l-o.centerY)*o.scale});if(o.showGrid){a.push('<g stroke="var(--nice-border, #ddd)" stroke-width="0.5">');for(let i=Math.floor(-t/2/o.scale+o.centerX);i<=t/2/o.scale+o.centerX;i+=o.gridSpacing){const l=n(i,0);a.push(`<line x1="${l.x}" y1="0" x2="${l.x}" y2="${r}"/>`)}for(let i=Math.floor(-r/2/o.scale+o.centerY);i<=r/2/o.scale+o.centerY;i+=o.gridSpacing){const l=n(0,i);a.push(`<line x1="0" y1="${l.y}" x2="${t}" y2="${l.y}"/>`)}a.push("</g>")}if(o.showAxes){const i=n(0,0);a.push('<g stroke="var(--nice-text, #333)" stroke-width="1">'),a.push(`<line x1="0" y1="${i.y}" x2="${t}" y2="${i.y}"/>`),a.push(`<line x1="${i.x}" y1="0" x2="${i.x}" y2="${r}"/>`),a.push("</g>")}for(const i of this.getAllElements()){if(!i.visible)continue;const l=`rgb(${i.color.r},${i.color.g},${i.color.b})`;switch(i.type){case"point":{const u=n(i.x,i.y);a.push(`<circle cx="${u.x}" cy="${u.y}" r="${i.size}" fill="${l}"/>`),i.label&&a.push(`<text x="${u.x+8}" y="${u.y-8}" font-size="12">${i.label}</text>`);break}case"segment":{const u=this.getPoint(i.point1Id),c=this.getPoint(i.point2Id);if(u&&c){const p=n(u.x,u.y),m=n(c.x,c.y);a.push(`<line x1="${p.x}" y1="${p.y}" x2="${m.x}" y2="${m.y}" stroke="${l}" stroke-width="${i.width}"/>`)}break}case"circle":{const u=this.getPoint(i.centerId);if(u){const c=n(u.x,u.y),p=i.radius*o.scale,m=i.fill?`rgba(${i.fill.r},${i.fill.g},${i.fill.b},${i.fill.a??.2})`:"none";a.push(`<circle cx="${c.x}" cy="${c.y}" r="${p}" fill="${m}" stroke="${l}" stroke-width="${i.width}"/>`)}break}case"polygon":{const u=i.pointIds.map(c=>this.getPoint(c)).filter(Boolean);if(u.length>0){const p=u.map(h=>n(h.x,h.y)).map((h,b)=>`${b===0?"M":"L"}${h.x},${h.y}`).join(" ")+" Z",m=i.fill?`rgba(${i.fill.r},${i.fill.g},${i.fill.b},${i.fill.a??.2})`:"none";a.push(`<path d="${p}" fill="${m}" stroke="${l}" stroke-width="${i.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 De(){return new le}const de=y.createContext(null);function X(){const e=y.useContext(de);if(!e)throw new Error("useGeometry must be used within GeometryProvider");return e}const q={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 Ne({service:e,width:t=800,height:r=600,className:o,style:a}){const[n,i]=y.useState([]),[l,u]=y.useState("point"),[c,p]=y.useState([]),[m,h]=y.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=y.useCallback(()=>{i(e.getAllElements())},[e]),C=y.useCallback(v=>{h(d=>({...d,...v}))},[]);y.useEffect(()=>{b()},[b]);const g={service:e,elements:n,tool:l,setTool:u,view:m,setView:C,selectedIds:c,setSelectedIds:p,refresh:b};return s.jsx(de.Provider,{value:g,children:s.jsxs("div",{className:o,style:{...q.container,...a},children:[s.jsx(Ge,{}),s.jsxs("div",{style:q.main,children:[s.jsx(Xe,{width:t,height:r}),s.jsx(Oe,{width:t,height:r})]})]})})}function Ge(){const{tool:e,setTool:t}=X(),r=[{id:"select",icon:"cursor",title:"Select"},{id:"point",icon:"•",title:"Point"},{id:"segment",icon:"—",title:"Segment"},{id:"line",icon:"line",title:"Line"},{id:"ray",icon:"arrow-right",title:"Ray"},{id:"circle",icon:"circle",title:"Circle"},{id:"polygon",icon:"triangle",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:"close",title:"Intersection"},{id:"reflect",icon:"shuffle",title:"Reflect"},{id:"rotate",icon:"refresh",title:"Rotate"},{id:"measure",icon:"ruler",title:"Measure"}];return s.jsx("div",{style:q.toolbar,children:r.map(o=>s.jsx("button",{onClick:()=>t(o.id),title:o.title,style:{...q.toolButton,backgroundColor:e===o.id?"var(--nice-primary-hover, #1976d2)":"transparent",color:e===o.id?"var(--nice-color-white, #fff)":"var(--nice-text, #333)"},children:/^[a-z][a-z0-9-]*$/.test(o.icon)?s.jsx($.NiceIcon,{name:o.icon,size:16}):o.icon},o.id))})}function Xe({width:e,height:t}){const r=y.useRef(null),{service:o,elements:a,tool:n,view:i,selectedIds:l,setSelectedIds:u,refresh:c}=X(),[p,m]=y.useState([]),h=y.useCallback((v,d)=>{const x=(v-e/2)/i.scale+i.centerX,w=-(d-t/2)/i.scale+i.centerY;return i.snapToGrid?{x:Math.round(x/i.gridSpacing)*i.gridSpacing,y:Math.round(w/i.gridSpacing)*i.gridSpacing}:{x,y:w}},[e,t,i]),b=y.useCallback((v,d)=>({x:e/2+(v-i.centerX)*i.scale,y:t/2-(d-i.centerY)*i.scale}),[e,t,i]),C=y.useCallback(v=>{var w;const d=(w=r.current)==null?void 0:w.getBoundingClientRect();if(!d)return;const x=h(v.clientX-d.left,v.clientY-d.top);switch(n){case"point":{o.createPoint(x.x,x.y),c();break}case"segment":case"line":case"ray":{const S=g(x);if(S)m(f=>{const k=[...f,S.id];return k.length===2?(n==="segment"?o.createSegment(k[0],k[1]):n==="line"?o.createLine(k[0],k[1]):n==="ray"&&o.createRay(k[0],k[1]),c(),[]):k});else{const f=o.createPoint(x.x,x.y);m(k=>{const M=[...k,f.id];return M.length===2?(n==="segment"?o.createSegment(M[0],M[1]):n==="line"?o.createLine(M[0],M[1]):n==="ray"&&o.createRay(M[0],M[1]),c(),[]):M}),c()}break}case"circle":{const S=g(x);if(S)m(f=>{if(f.length===0)return[S.id];const k=o.getPoint(f[0]);if(k){const M=A.distance(k,x);o.createCircle(f[0],M),c()}return[]});else if(p.length===1){const f=o.getPoint(p[0]);if(f){const k=A.distance(f,x);o.createCircle(p[0],k),c(),m([])}}else{const f=o.createPoint(x.x,x.y);m([f.id]),c()}break}case"midpoint":{const S=g(x);S&&m(f=>{const k=[...f,S.id];return k.length===2?(o.createMidpoint(k[0],k[1]),c(),[]):k});break}case"select":{const S=g(x);u(S?[S.id]:[]);break}}},[n,o,c,h,p,u]),g=v=>{for(const x of a)if(x.type==="point"&&A.distance(x,v)<.5)return x};return y.useEffect(()=>{const v=r.current,d=v==null?void 0:v.getContext("2d");if(!(!v||!d)){if(d.fillStyle=`rgb(${i.backgroundColor.r},${i.backgroundColor.g},${i.backgroundColor.b})`,d.fillRect(0,0,e,t),i.showGrid){d.strokeStyle=$.resolveCssColor("var(--nice-border, #e0e0e0)",d.canvas),d.lineWidth=.5;const x=i.gridSpacing*i.scale,w=(e/2-i.centerX*i.scale)%x,S=(t/2+i.centerY*i.scale)%x;for(let f=w;f<e;f+=x)d.beginPath(),d.moveTo(f,0),d.lineTo(f,t),d.stroke();for(let f=S;f<t;f+=x)d.beginPath(),d.moveTo(0,f),d.lineTo(e,f),d.stroke()}if(i.showAxes){const x=b(0,0);d.strokeStyle=$.resolveCssColor("var(--nice-text, #333)",d.canvas),d.lineWidth=1,d.beginPath(),d.moveTo(0,x.y),d.lineTo(e,x.y),d.stroke(),d.beginPath(),d.moveTo(x.x,0),d.lineTo(x.x,t),d.stroke()}for(const x of a){if(!x.visible)continue;const w=`rgb(${x.color.r},${x.color.g},${x.color.b})`,S=l.includes(x.id);switch(x.type){case"point":{const f=b(x.x,x.y);d.beginPath(),d.arc(f.x,f.y,S?x.size+2:x.size,0,2*Math.PI),d.fillStyle=S?$.resolveCssColor("var(--nice-primary-hover, #1976d2)",d.canvas):w,d.fill(),x.label&&(d.fillStyle=$.resolveCssColor("var(--nice-text, #333)",d.canvas),d.font="12px sans-serif",d.fillText(x.label,f.x+8,f.y-8));break}case"segment":{const f=o.getPoint(x.point1Id),k=o.getPoint(x.point2Id);if(f&&k){const M=b(f.x,f.y),z=b(k.x,k.y);d.strokeStyle=w,d.lineWidth=x.width,d.beginPath(),d.moveTo(M.x,M.y),d.lineTo(z.x,z.y),d.stroke()}break}case"line":{const f=o.getPoint(x.point1Id),k=o.getPoint(x.point2Id);if(f&&k){const M=k.x-f.x,z=k.y-f.y,V=-1e3,Y=1e3,H=b(f.x+V*M,f.y+V*z),W=b(f.x+Y*M,f.y+Y*z);d.strokeStyle=w,d.lineWidth=x.width,d.beginPath(),d.moveTo(H.x,H.y),d.lineTo(W.x,W.y),d.stroke()}break}case"circle":{const f=o.getPoint(x.centerId);if(f){const k=b(f.x,f.y),M=x.radius*i.scale;d.beginPath(),d.arc(k.x,k.y,M,0,2*Math.PI),x.fill&&(d.fillStyle=`rgba(${x.fill.r},${x.fill.g},${x.fill.b},${x.fill.a??.2})`,d.fill()),d.strokeStyle=w,d.lineWidth=x.width,d.stroke()}break}case"polygon":{const f=x.pointIds.map(k=>o.getPoint(k)).filter(Boolean);if(f.length>0){d.beginPath();const k=b(f[0].x,f[0].y);d.moveTo(k.x,k.y);for(let M=1;M<f.length;M++){const z=b(f[M].x,f[M].y);d.lineTo(z.x,z.y)}d.closePath(),x.fill&&(d.fillStyle=`rgba(${x.fill.r},${x.fill.g},${x.fill.b},${x.fill.a??.2})`,d.fill()),d.strokeStyle=w,d.lineWidth=x.width,d.stroke()}break}}}if(p.length>0){d.fillStyle=$.resolveCssColor("var(--nice-primary-tint-30, rgba(25, 118, 210, 0.3))",d.canvas);for(const x of p){const w=o.getPoint(x);if(w){const S=b(w.x,w.y);d.beginPath(),d.arc(S.x,S.y,12,0,2*Math.PI),d.fill()}}}}},[a,i,e,t,l,p,o,b]),s.jsx("canvas",{ref:r,width:e,height:t,style:q.canvas,onClick:C})}function Oe({width:e,height:t}){const{tool:r,elements:o,view:a,service:n}=X(),[i,l]=y.useState(null),u={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"},c=o.filter(p=>p.type==="point").length;return s.jsxs("div",{style:q.statusBar,children:[s.jsxs("span",{children:["Tool: ",u[r]]}),s.jsx("span",{style:{margin:"0 16px"},children:"|"}),s.jsxs("span",{children:["Objects: ",o.length]}),s.jsx("span",{style:{margin:"0 16px"},children:"|"}),s.jsxs("span",{children:["Points: ",c]}),s.jsx("span",{style:{margin:"0 16px"},children:"|"}),s.jsxs("span",{children:["Scale: ",a.scale.toFixed(1),"x"]})]})}exports.CalculatorService=ie;exports.CalculusOps=F;exports.EQUATION_TEMPLATES=ee;exports.ExpressionParser=U;exports.FUNCTION_PRESETS=O;exports.GeoMath=A;exports.GeometryService=le;exports.GraphService=ae;exports.MATH_SYMBOLS=Q;exports.MathEditorService=te;exports.MatrixOps=R;exports.NiceCalculator=Te;exports.NiceGeometry=Ne;exports.NiceGraphPlotter=Se;exports.NiceI18nProvider=xe;exports.NiceMathEditor=ye;exports.createCalculatorService=$e;exports.createGeometryService=De;exports.createGraphService=Ce;exports.createMathEditorService=me;exports.getSymbolsByCategory=J;exports.recognizeHandwriting=re;exports.useCalculator=I;exports.useGeometry=X;exports.useGraph=D;exports.useMathEditor=G;exports.useNiceTranslation=E;
1
+ "use strict";var ge=Object.defineProperty;var ue=(e,t,r)=>t in e?ge(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var T=(e,t,r)=>ue(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),q=require("@nice2dev/ui"),B=require("@nice2dev/ui-core"),y=require("react"),O={en:{"calculator.matrixA":"Matrix A","calculator.matrixB":"Matrix B","calculator.exprPlaceholder":"Enter expression (e.g., x^2, sin(x))","calculator.differentiate":"Differentiate","calculator.integrate":"Integrate","calculator.convert":"Convert","plotter.quickAdd":"Quick add preset...","plotter.noPlots":"No plots added yet","plotter.grid":"Grid","plotter.axes":"Axes","editor.latexPlaceholder":"Enter LaTeX equation...","editor.clear":"Clear","editor.recognize":"Recognize","editor.recognizing":"Recognizing...","editor.latexInput":"LaTeX Input","editor.handwriting":"Handwriting","editor.handwritingNote":"Draw your equation above. Handwriting recognition requires external API integration.","editor.templates":"Templates","editor.copyLatex":"Copy LaTeX","plotter.close":"Close","calculator.standard":"Standard","calculator.scientific":"Scientific","calculator.programmer":"Programmer","calculator.matrix":"Matrix","calculator.calculus":"Calculus","calculator.units":"Units","geometry.select":"Select","geometry.point":"Point","geometry.segment":"Segment","geometry.line":"Line","geometry.ray":"Ray","geometry.circle":"Circle","geometry.polygon":"Polygon","geometry.perpendicular":"Perpendicular","geometry.parallel":"Parallel","geometry.midpoint":"Midpoint","geometry.angleBisector":"Angle Bisector","geometry.intersection":"Intersection","geometry.reflect":"Reflect","geometry.rotate":"Rotate","geometry.measure":"Measure","geometry.arc":"Arc","geometry.angle":"Angle","geometry.tangent":"Tangent","geometry.translate":"Translate","geometry.dilate":"Dilate","geometry.text":"Text","geometry.tool":"Tool: {tool}","geometry.objects":"Objects: {elements}","geometry.points":"Points: {pointCount}","geometry.scaleX":"Scale: {scale}x","plotter.parametricXTYT":"Parametric (x(t), y(t))","plotter.polarRF":"Polar r = f(θ)","plotter.n3dSurfaceZFX":"3D Surface z = f(x,y)","plotter.expression":"Expression...","plotter.addPlot":"+ Add Plot","editor.previewRequiresKatexMathjaxIntegration":"Preview (requires KaTeX/MathJax integration):"},pl:{"calculator.matrixA":"Macierz A","calculator.matrixB":"Macierz B","calculator.exprPlaceholder":"Wprowadź wyrażenie (np. x^2, sin(x))","calculator.differentiate":"Różniczkuj","calculator.integrate":"Całkuj","calculator.convert":"Przelicz","plotter.quickAdd":"Szybko dodaj ustawienie...","plotter.noPlots":"Nie dodano jeszcze żadnych wykresów","plotter.grid":"Siatka","plotter.axes":"Osie","editor.latexPlaceholder":"Wprowadź równanie LaTeX...","editor.clear":"Wyczyść","editor.recognize":"Rozpoznaj","editor.recognizing":"Rozpoznawanie...","editor.latexInput":"Wpis LaTeX","editor.handwriting":"Pismo odręczne","editor.handwritingNote":"Narysuj równanie powyżej. Rozpoznawanie pisma wymaga zewnętrznej integracji API.","editor.templates":"Szablony","editor.copyLatex":"Kopiuj LaTeX","plotter.close":"Zamknij","calculator.standard":"Standardowy","calculator.scientific":"Naukowy","calculator.programmer":"Programisty","calculator.matrix":"Macierze","calculator.calculus":"Analiza","calculator.units":"Jednostki","geometry.select":"Zaznacz","geometry.point":"Punkt","geometry.segment":"Odcinek","geometry.line":"Prosta","geometry.ray":"Półprosta","geometry.circle":"Okrąg","geometry.polygon":"Wielokąt","geometry.perpendicular":"Prostopadła","geometry.parallel":"Równoległa","geometry.midpoint":"Środek odcinka","geometry.angleBisector":"Dwusieczna kąta","geometry.intersection":"Przecięcie","geometry.reflect":"Odbicie","geometry.rotate":"Obrót","geometry.measure":"Pomiar","geometry.arc":"Łuk","geometry.angle":"Kąt","geometry.tangent":"Styczna","geometry.translate":"Przesunięcie","geometry.dilate":"Jednokładność","geometry.text":"Tekst","geometry.tool":"Narzędzie: {tool}","geometry.objects":"Obiekty: {elements}","geometry.points":"Punkty: {pointCount}","geometry.scaleX":"Skala: {scale}x","plotter.parametricXTYT":"Parametryczny (x(t), y(t))","plotter.polarRF":"Biegunowy r = f(θ)","plotter.n3dSurfaceZFX":"Powierzchnia 3D z = f(x,y)","plotter.expression":"Wyrażenie...","plotter.addPlot":"+ Dodaj wykres","editor.previewRequiresKatexMathjaxIntegration":"Podgląd (wymaga integracji KaTeX/MathJax):"},de:{"calculator.matrixA":"Matrix A","calculator.matrixB":"Matrix B","calculator.exprPlaceholder":"Ausdruck eingeben (z. B. x^2, sin(x))","calculator.differentiate":"Ableiten","calculator.integrate":"Integrieren","calculator.convert":"Umrechnen","plotter.quickAdd":"Voreinstellung schnell hinzufügen...","plotter.noPlots":"Noch keine Diagramme hinzugefügt","plotter.grid":"Raster","plotter.axes":"Achsen","editor.latexPlaceholder":"LaTeX-Gleichung eingeben...","editor.clear":"Löschen","editor.recognize":"Erkennen","editor.recognizing":"Erkennung läuft...","editor.latexInput":"LaTeX-Eingabe","editor.handwriting":"Handschrift","editor.handwritingNote":"Zeichnen Sie Ihre Gleichung oben. Die Handschrifterkennung erfordert eine externe API-Integration.","editor.templates":"Vorlagen","editor.copyLatex":"LaTeX kopieren","plotter.close":"Schließen","calculator.standard":"Standard","calculator.scientific":"Wissenschaftlich","calculator.programmer":"Programmierer","calculator.matrix":"Matrix","calculator.calculus":"Analysis","calculator.units":"Einheiten","geometry.select":"Auswählen","geometry.point":"Punkt","geometry.segment":"Strecke","geometry.line":"Gerade","geometry.ray":"Strahl","geometry.circle":"Kreis","geometry.polygon":"Polygon","geometry.perpendicular":"Senkrechte","geometry.parallel":"Parallele","geometry.midpoint":"Mittelpunkt","geometry.angleBisector":"Winkelhalbierende","geometry.intersection":"Schnittpunkt","geometry.reflect":"Spiegeln","geometry.rotate":"Drehen","geometry.measure":"Messen","geometry.arc":"Bogen","geometry.angle":"Winkel","geometry.tangent":"Tangente","geometry.translate":"Verschieben","geometry.dilate":"Strecken","geometry.text":"Text","geometry.tool":"Werkzeug: {tool}","geometry.objects":"Objekte: {elements}","geometry.points":"Punkte: {pointCount}","geometry.scaleX":"Maßstab: {scale}x","plotter.parametricXTYT":"Parametrisch (x(t), y(t))","plotter.polarRF":"Polar r = f(θ)","plotter.n3dSurfaceZFX":"3D-Fläche z = f(x,y)","plotter.expression":"Ausdruck...","plotter.addPlot":"+ Diagramm hinzufügen","editor.previewRequiresKatexMathjaxIntegration":"Vorschau (erfordert KaTeX/MathJax-Integration):"},fr:{"calculator.matrixA":"Matrice A","calculator.matrixB":"Matrice B","calculator.exprPlaceholder":"Saisir une expression (ex. x^2, sin(x))","calculator.differentiate":"Dériver","calculator.integrate":"Intégrer","calculator.convert":"Convertir","plotter.quickAdd":"Ajouter un préréglage rapide...","plotter.noPlots":"Aucun tracé ajouté pour le moment","plotter.grid":"Grille","plotter.axes":"Axes","editor.latexPlaceholder":"Saisir une équation LaTeX...","editor.clear":"Effacer","editor.recognize":"Reconnaître","editor.recognizing":"Reconnaissance...","editor.latexInput":"Saisie LaTeX","editor.handwriting":"Écriture manuscrite","editor.handwritingNote":"Dessinez votre équation ci-dessus. La reconnaissance d'écriture nécessite une intégration API externe.","editor.templates":"Modèles","editor.copyLatex":"Copier le LaTeX","plotter.close":"Fermer","calculator.standard":"Standard","calculator.scientific":"Scientifique","calculator.programmer":"Programmeur","calculator.matrix":"Matrice","calculator.calculus":"Analyse","calculator.units":"Unités","geometry.select":"Sélectionner","geometry.point":"Point","geometry.segment":"Segment","geometry.line":"Droite","geometry.ray":"Demi-droite","geometry.circle":"Cercle","geometry.polygon":"Polygone","geometry.perpendicular":"Perpendiculaire","geometry.parallel":"Parallèle","geometry.midpoint":"Milieu","geometry.angleBisector":"Bissectrice","geometry.intersection":"Intersection","geometry.reflect":"Réflexion","geometry.rotate":"Rotation","geometry.measure":"Mesurer","geometry.arc":"Arc","geometry.angle":"Angle","geometry.tangent":"Tangente","geometry.translate":"Translation","geometry.dilate":"Homothétie","geometry.text":"Texte","geometry.tool":"Outil : {tool}","geometry.objects":"Objets : {elements}","geometry.points":"Points : {pointCount}","geometry.scaleX":"Échelle : {scale}x","plotter.parametricXTYT":"Paramétrique (x(t), y(t))","plotter.polarRF":"Polaire r = f(θ)","plotter.n3dSurfaceZFX":"Surface 3D z = f(x,y)","plotter.expression":"Expression...","plotter.addPlot":"+ Ajouter un tracé","editor.previewRequiresKatexMathjaxIntegration":"Aperçu (nécessite l'intégration KaTeX/MathJax) :"},es:{"calculator.matrixA":"Matriz A","calculator.matrixB":"Matriz B","calculator.exprPlaceholder":"Introduce una expresión (p. ej. x^2, sin(x))","calculator.differentiate":"Derivar","calculator.integrate":"Integrar","calculator.convert":"Convertir","plotter.quickAdd":"Añadir preajuste rápido...","plotter.noPlots":"Aún no se ha añadido ningún gráfico","plotter.grid":"Cuadrícula","plotter.axes":"Ejes","editor.latexPlaceholder":"Introduce una ecuación LaTeX...","editor.clear":"Borrar","editor.recognize":"Reconocer","editor.recognizing":"Reconociendo...","editor.latexInput":"Entrada LaTeX","editor.handwriting":"Escritura a mano","editor.handwritingNote":"Dibuja tu ecuación arriba. El reconocimiento de escritura requiere integración con una API externa.","editor.templates":"Plantillas","editor.copyLatex":"Copiar LaTeX","plotter.close":"Cerrar","calculator.standard":"Estándar","calculator.scientific":"Científica","calculator.programmer":"Programador","calculator.matrix":"Matriz","calculator.calculus":"Cálculo","calculator.units":"Unidades","geometry.select":"Seleccionar","geometry.point":"Punto","geometry.segment":"Segmento","geometry.line":"Recta","geometry.ray":"Semirrecta","geometry.circle":"Circunferencia","geometry.polygon":"Polígono","geometry.perpendicular":"Perpendicular","geometry.parallel":"Paralela","geometry.midpoint":"Punto medio","geometry.angleBisector":"Bisectriz","geometry.intersection":"Intersección","geometry.reflect":"Reflejar","geometry.rotate":"Girar","geometry.measure":"Medir","geometry.arc":"Arco","geometry.angle":"Ángulo","geometry.tangent":"Tangente","geometry.translate":"Trasladar","geometry.dilate":"Homotecia","geometry.text":"Texto","geometry.tool":"Herramienta: {tool}","geometry.objects":"Objetos: {elements}","geometry.points":"Puntos: {pointCount}","geometry.scaleX":"Escala: {scale}x","plotter.parametricXTYT":"Paramétrica (x(t), y(t))","plotter.polarRF":"Polar r = f(θ)","plotter.n3dSurfaceZFX":"Superficie 3D z = f(x,y)","plotter.expression":"Expresión...","plotter.addPlot":"+ Añadir gráfica","editor.previewRequiresKatexMathjaxIntegration":"Vista previa (requiere integración con KaTeX/MathJax):"},it:{"calculator.matrixA":"Matrice A","calculator.matrixB":"Matrice B","calculator.exprPlaceholder":"Inserisci un’espressione (es. x^2, sin(x))","calculator.differentiate":"Derivare","calculator.integrate":"Integrare","calculator.convert":"Converti","plotter.quickAdd":"Aggiungi un preset rapido...","plotter.noPlots":"Nessun grafico aggiunto","plotter.grid":"Griglia","plotter.axes":"Assi","editor.latexPlaceholder":"Inserisci un’equazione LaTeX...","editor.clear":"Cancella","editor.recognize":"Riconosci","editor.recognizing":"Riconoscimento...","editor.latexInput":"Input LaTeX","editor.handwriting":"Scrittura a mano","editor.handwritingNote":"Disegna la tua equazione qui sopra. Il riconoscimento della scrittura richiede un’integrazione API esterna.","editor.templates":"Modelli","editor.copyLatex":"Copia LaTeX","plotter.close":"Chiudi","calculator.standard":"Standard","calculator.scientific":"Scientifica","calculator.programmer":"Programmatore","calculator.matrix":"Matrice","calculator.calculus":"Analisi","calculator.units":"Unità","geometry.select":"Seleziona","geometry.point":"Punto","geometry.segment":"Segmento","geometry.line":"Retta","geometry.ray":"Semiretta","geometry.circle":"Circonferenza","geometry.polygon":"Poligono","geometry.perpendicular":"Perpendicolare","geometry.parallel":"Parallela","geometry.midpoint":"Punto medio","geometry.angleBisector":"Bisettrice","geometry.intersection":"Intersezione","geometry.reflect":"Rifletti","geometry.rotate":"Ruota","geometry.measure":"Misura","geometry.arc":"Arco","geometry.angle":"Angolo","geometry.tangent":"Tangente","geometry.translate":"Trasla","geometry.dilate":"Omotetia","geometry.text":"Testo","geometry.tool":"Strumento: {tool}","geometry.objects":"Oggetti: {elements}","geometry.points":"Punti: {pointCount}","geometry.scaleX":"Scala: {scale}x","plotter.parametricXTYT":"Parametrico (x(t), y(t))","plotter.polarRF":"Polare r = f(θ)","plotter.n3dSurfaceZFX":"Superficie 3D z = f(x,y)","plotter.expression":"Espressione...","plotter.addPlot":"+ Aggiungi grafico","editor.previewRequiresKatexMathjaxIntegration":"Anteprima (richiede l'integrazione KaTeX/MathJax):"},pt:{"calculator.matrixA":"Matriz A","calculator.matrixB":"Matriz B","calculator.exprPlaceholder":"Introduza uma expressão (p. ex. x^2, sin(x))","calculator.differentiate":"Derivar","calculator.integrate":"Integrar","calculator.convert":"Converter","plotter.quickAdd":"Adicionar predefinição rápida...","plotter.noPlots":"Ainda não foram adicionados gráficos","plotter.grid":"Grelha","plotter.axes":"Eixos","editor.latexPlaceholder":"Introduza uma equação LaTeX...","editor.clear":"Limpar","editor.recognize":"Reconhecer","editor.recognizing":"A reconhecer...","editor.latexInput":"Entrada LaTeX","editor.handwriting":"Escrita à mão","editor.handwritingNote":"Desenhe a sua equação acima. O reconhecimento de escrita requer integração com uma API externa.","editor.templates":"Modelos","editor.copyLatex":"Copiar LaTeX","plotter.close":"Fechar","calculator.standard":"Padrão","calculator.scientific":"Científica","calculator.programmer":"Programador","calculator.matrix":"Matriz","calculator.calculus":"Cálculo","calculator.units":"Unidades","geometry.select":"Selecionar","geometry.point":"Ponto","geometry.segment":"Segmento","geometry.line":"Reta","geometry.ray":"Semirreta","geometry.circle":"Circunferência","geometry.polygon":"Polígono","geometry.perpendicular":"Perpendicular","geometry.parallel":"Paralela","geometry.midpoint":"Ponto médio","geometry.angleBisector":"Bissetriz","geometry.intersection":"Interseção","geometry.reflect":"Refletir","geometry.rotate":"Rodar","geometry.measure":"Medir","geometry.arc":"Arco","geometry.angle":"Ângulo","geometry.tangent":"Tangente","geometry.translate":"Transladar","geometry.dilate":"Homotetia","geometry.text":"Texto","geometry.tool":"Ferramenta: {tool}","geometry.objects":"Objetos: {elements}","geometry.points":"Pontos: {pointCount}","geometry.scaleX":"Escala: {scale}x","plotter.parametricXTYT":"Paramétrico (x(t), y(t))","plotter.polarRF":"Polar r = f(θ)","plotter.n3dSurfaceZFX":"Superfície 3D z = f(x,y)","plotter.expression":"Expressão...","plotter.addPlot":"+ Adicionar gráfico","editor.previewRequiresKatexMathjaxIntegration":"Pré-visualização (requer integração KaTeX/MathJax):"},cs:{"calculator.matrixA":"Matice A","calculator.matrixB":"Matice B","calculator.exprPlaceholder":"Zadejte výraz (např. x^2, sin(x))","calculator.differentiate":"Derivovat","calculator.integrate":"Integrovat","calculator.convert":"Převést","plotter.quickAdd":"Rychle přidat předvolbu...","plotter.noPlots":"Zatím nebyl přidán žádný graf","plotter.grid":"Mřížka","plotter.axes":"Osy","editor.latexPlaceholder":"Zadejte rovnici v LaTeXu...","editor.clear":"Vymazat","editor.recognize":"Rozpoznat","editor.recognizing":"Rozpoznávání...","editor.latexInput":"Zadání LaTeX","editor.handwriting":"Rukopis","editor.handwritingNote":"Nakreslete svou rovnici výše. Rozpoznávání rukopisu vyžaduje externí integraci API.","editor.templates":"Šablony","editor.copyLatex":"Kopírovat LaTeX","plotter.close":"Zavřít","calculator.standard":"Standardní","calculator.scientific":"Vědecká","calculator.programmer":"Programátorská","calculator.matrix":"Matice","calculator.calculus":"Analýza","calculator.units":"Jednotky","geometry.select":"Vybrat","geometry.point":"Bod","geometry.segment":"Úsečka","geometry.line":"Přímka","geometry.ray":"Polopřímka","geometry.circle":"Kružnice","geometry.polygon":"Mnohoúhelník","geometry.perpendicular":"Kolmice","geometry.parallel":"Rovnoběžka","geometry.midpoint":"Střed","geometry.angleBisector":"Osa úhlu","geometry.intersection":"Průsečík","geometry.reflect":"Zrcadlit","geometry.rotate":"Otočit","geometry.measure":"Měřit","geometry.arc":"Oblouk","geometry.angle":"Úhel","geometry.tangent":"Tečna","geometry.translate":"Posunout","geometry.dilate":"Stejnolehlost","geometry.text":"Text","geometry.tool":"Nástroj: {tool}","geometry.objects":"Objekty: {elements}","geometry.points":"Body: {pointCount}","geometry.scaleX":"Měřítko: {scale}x","plotter.parametricXTYT":"Parametrický (x(t), y(t))","plotter.polarRF":"Polární r = f(θ)","plotter.n3dSurfaceZFX":"3D plocha z = f(x,y)","plotter.expression":"Výraz...","plotter.addPlot":"+ Přidat graf","editor.previewRequiresKatexMathjaxIntegration":"Náhled (vyžaduje integraci KaTeX/MathJax):"},uk:{"calculator.matrixA":"Матриця A","calculator.matrixB":"Матриця B","calculator.exprPlaceholder":"Введіть вираз (напр. x^2, sin(x))","calculator.differentiate":"Диференціювати","calculator.integrate":"Інтегрувати","calculator.convert":"Перетворити","plotter.quickAdd":"Швидко додати пресет...","plotter.noPlots":"Поки що не додано жодного графіка","plotter.grid":"Сітка","plotter.axes":"Осі","editor.latexPlaceholder":"Введіть рівняння в LaTeX...","editor.clear":"Очистити","editor.recognize":"Розпізнати","editor.recognizing":"Розпізнавання...","editor.latexInput":"Введення LaTeX","editor.handwriting":"Рукопис","editor.handwritingNote":"Намалюйте своє рівняння вище. Розпізнавання рукопису потребує зовнішньої інтеграції з API.","editor.templates":"Шаблони","editor.copyLatex":"Копіювати LaTeX","plotter.close":"Закрити","calculator.standard":"Стандартний","calculator.scientific":"Науковий","calculator.programmer":"Програміста","calculator.matrix":"Матриці","calculator.calculus":"Аналіз","calculator.units":"Одиниці","geometry.select":"Вибрати","geometry.point":"Точка","geometry.segment":"Відрізок","geometry.line":"Пряма","geometry.ray":"Промінь","geometry.circle":"Коло","geometry.polygon":"Многокутник","geometry.perpendicular":"Перпендикуляр","geometry.parallel":"Паралельна","geometry.midpoint":"Середина","geometry.angleBisector":"Бісектриса","geometry.intersection":"Перетин","geometry.reflect":"Відбити","geometry.rotate":"Повернути","geometry.measure":"Виміряти","geometry.arc":"Дуга","geometry.angle":"Кут","geometry.tangent":"Дотична","geometry.translate":"Перенести","geometry.dilate":"Гомотетія","geometry.text":"Текст","geometry.tool":"Інструмент: {tool}","geometry.objects":"Об'єкти: {elements}","geometry.points":"Точки: {pointCount}","geometry.scaleX":"Масштаб: {scale}x","plotter.parametricXTYT":"Параметричний (x(t), y(t))","plotter.polarRF":"Полярний r = f(θ)","plotter.n3dSurfaceZFX":"3D-поверхня z = f(x,y)","plotter.expression":"Вираз...","plotter.addPlot":"+ Додати графік","editor.previewRequiresKatexMathjaxIntegration":"Попередній перегляд (потрібна інтеграція KaTeX/MathJax):"}},Z=y.createContext(null);function J(e,t){const r={...O.en,...O[e],...t};return{locale:e,t:(a,n)=>r[a]??n??a}}function me({locale:e="en",overrides:t,children:r}){const o=y.useMemo(()=>J(e,t),[e,t]);return y.createElement(Z.Provider,{value:o},r)}function $(){const e=y.useContext(Z),{lang:t}=B.useNiceTranslation(),r=O[t]?t:"en",o=y.useMemo(()=>J(r),[r]);return e??o}const xe=[{target:".nice-math-editor",titleKey:"tutorial.mathEditor.intro.title",title:"Math editor",contentKey:"tutorial.mathEditor.intro.content",content:"Write equations as LaTeX or insert symbols from the palette; switch to handwriting input, and preview the rendered formula live.",placement:"auto"}],Q=[{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 ee(e){return Q.filter(t=>t.category===e)}const te=[{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 re{constructor(t={}){T(this,"equations",new Map);T(this,"config");T(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 o={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(o.id,o),o}updateEquation(t,r,o){const a=this.equations.get(t);if(!a)throw new Error(`Equation not found: ${t}`);const n={...a,latex:r,label:o??a.label,updatedAt:new Date().toISOString()};return this.equations.set(t,n),n}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=[],o=/\\\[([\s\S]*?)\\\]/g;let a;for(;(a=o.exec(t))!==null;)r.push(this.createEquation(a[1].trim()));const n=/\\begin\{equation\}([\s\S]*?)\\end\{equation\}/g;for(;(a=n.exec(t))!==null;){const i=a[1].match(/\\label\{([^}]+)\}/),c=a[1].replace(/\\label\{[^}]+\}/,"").trim();r.push(this.createEquation(c,i==null?void 0:i[1]))}return r}generateId(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}}function ye(e){return new re(e)}async function oe(e){return await new Promise(r=>setTimeout(r,500)),{latex:e.reduce((r,o)=>r+o.points.length,0)>50?"\\sqrt{x^2 + y^2}":"x",confidence:.85,alternatives:["x","X","\\times"]}}const ae=y.createContext(null);function X(){const e=y.useContext(ae);if(!e)throw new Error("useMathEditor must be used within MathEditorProvider");return e}const R={toolbar:{display:"flex",gap:"8px",padding:"8px",borderBottom:"1px solid var(--nice-border, #e0e0e0)",backgroundColor:"var(--nice-bg-secondary, #fafafa)",flexWrap:"wrap",alignItems:"center"},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 he({service:e,initialLatex:t="",onChange:r,className:o,style:a,tutorial:n}){const{t:i}=$(),[c,g]=y.useState(t),[l,p]=y.useState("input"),m=y.useRef(null),h=y.useCallback(v=>{g(v),r==null||r(v)},[r]),b=y.useCallback(v=>{const d=m.current;if(!d){h(c+v);return}const u=d.selectionStart,k=d.selectionEnd,C=c.slice(0,u)+v+c.slice(k);h(C),setTimeout(()=>{d.focus(),d.selectionStart=d.selectionEnd=u+v.length},0)},[c,h]),w=y.useCallback(v=>{b(v.latex)},[b]),x={service:e,latex:c,setLatex:h,insertSymbol:b,insertTemplate:w,mode:l,setMode:p};return s.jsx(ae.Provider,{value:x,children:s.jsxs(q.NiceAppShell,{flush:!0,className:`nice-math-editor ${o??""}`,style:{position:"relative",...a},toolbar:s.jsx(fe,{}),sidebar:s.jsx(be,{}),children:[s.jsx("span",{style:{position:"absolute",top:6,right:6,zIndex:30},children:s.jsx(B.NiceTutorialButton,{steps:B.resolveTutorial(n,xe)})}),s.jsx("div",{style:R.editor,children:l==="input"?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{ref:m,value:c,onChange:v=>h(v.target.value),placeholder:i("editor.latexPlaceholder","Enter LaTeX equation..."),style:R.input}),s.jsx(ve,{latex:c})]}):s.jsx(we,{})})]})})}function fe(){const{t:e}=$(),{mode:t,setMode:r,latex:o,insertTemplate:a}=X(),[n,i]=y.useState(!1);return s.jsxs("div",{style:R.toolbar,children:[s.jsxs("button",{onClick:()=>r("input"),style:{...R.button,backgroundColor:t==="input"?"var(--nice-primary-hover, #1976d2)":"var(--nice-bg-tertiary, #9e9e9e)",color:t==="input"?"var(--nice-color-white, #fff)":"var(--nice-text-primary, #fff)"},children:[s.jsx(q.NiceIcon,{name:"keyboard",size:14})," ",e("editor.latexInput","LaTeX Input")]}),s.jsxs("button",{onClick:()=>r("handwriting"),style:{...R.button,backgroundColor:t==="handwriting"?"var(--nice-primary-hover, #1976d2)":"var(--nice-bg-tertiary, #9e9e9e)",color:t==="handwriting"?"var(--nice-color-white, #fff)":"var(--nice-text-primary, #fff)"},children:[s.jsx(q.NiceIcon,{name:"pen",size:14})," ",e("editor.handwriting","Handwriting")]}),s.jsx("div",{style:{borderLeft:"1px solid var(--nice-border, #ccc)",height:"24px",margin:"0 8px"}}),s.jsxs("div",{style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>i(!n),style:R.button,children:[s.jsx(q.NiceIcon,{name:"ruler",size:14})," ",e("editor.templates","Templates")," ",s.jsx(q.NiceIcon,{name:"chevron-down",size:12})]}),n&&s.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(c=>s.jsxs("div",{children:[s.jsx("div",{style:R.categoryHeader,children:c}),te.filter(g=>g.category===c).map(g=>s.jsxs("div",{onClick:()=>{a(g),i(!1)},style:{padding:"8px 12px",cursor:"pointer",borderBottom:"1px solid var(--nice-border, #eee)"},onMouseOver:l=>l.target.style.backgroundColor="var(--nice-bg-secondary, #f5f5f5)",onMouseOut:l=>l.target.style.backgroundColor="transparent",children:[s.jsx("div",{style:{fontWeight:500},children:g.name}),s.jsxs("div",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",fontFamily:"monospace"},children:[g.latex.substring(0,40),g.latex.length>40?"...":""]})]},g.name))]},c))})]}),s.jsx("div",{style:{flex:1}}),s.jsxs("button",{onClick:()=>navigator.clipboard.writeText(o),style:{...R.button,backgroundColor:"var(--nice-success, #4caf50)"},children:[s.jsx(q.NiceIcon,{name:"copy",size:14})," ",e("editor.copyLatex","Copy LaTeX")]})]})}function be(){const{insertSymbol:e}=X(),[t,r]=y.useState("greek"),o=["greek","operators","relations","arrows","functions","accents","delimiters","sets","logic","calculus","matrices"],a=ee(t);return s.jsxs("div",{style:R.sidebar,children:[s.jsx("div",{style:{display:"flex",flexWrap:"wrap",padding:"8px",gap:"4px"},children:o.map(n=>s.jsx("button",{onClick:()=>r(n),style:{padding:"4px 8px",fontSize:"11px",border:"1px solid var(--nice-border, #ddd)",borderRadius:"4px",backgroundColor:t===n?"var(--nice-primary-hover, #1976d2)":"var(--nice-bg, #fff)",color:t===n?"var(--nice-color-white, #fff)":"var(--nice-text, #333)",cursor:"pointer"},children:n},n))}),s.jsx("div",{style:R.symbolGrid,children:a.map(n=>s.jsx("button",{onClick:()=>e(n.latex),style:R.symbolButton,title:`${n.name}: ${n.latex}`,children:n.preview||n.latex},n.name))})]})}function ve({latex:e}){const{t}=$();return s.jsxs("div",{style:R.preview,children:[s.jsx("div",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",marginBottom:"8px"},children:t("editor.previewRequiresKatexMathjaxIntegration","Preview (requires KaTeX/MathJax integration):")}),s.jsx("code",{style:{fontSize:"16px"},children:e||"(empty)"})]})}function we(){const{t:e}=$(),{setLatex:t,setMode:r}=X(),o=y.useRef(null),[a,n]=y.useState([]),[i,c]=y.useState([]),[g,l]=y.useState(!1),[p,m]=y.useState(!1),h=d=>{const u=o.current;if(!u)return;l(!0);const k=u.getBoundingClientRect();c([{x:d.clientX-k.left,y:d.clientY-k.top,pressure:d.pressure,timestamp:Date.now()}])},b=d=>{if(!g)return;const u=o.current,k=u==null?void 0:u.getContext("2d");if(!u||!k)return;const C=u.getBoundingClientRect(),f={x:d.clientX-C.left,y:d.clientY-C.top,pressure:d.pressure,timestamp:Date.now()};if(c(P=>[...P,f]),i.length>0){const P=i[i.length-1];k.beginPath(),k.moveTo(P.x,P.y),k.lineTo(f.x,f.y),k.strokeStyle=B.resolveCssColor("var(--nice-text, #000)",k.canvas),k.lineWidth=2,k.lineCap="round",k.stroke()}},w=()=>{if(g){if(l(!1),i.length>1){const d={id:Date.now().toString(),points:[...i]};n(u=>[...u,d])}c([])}},x=()=>{const d=o.current,u=d==null?void 0:d.getContext("2d");u&&d&&u.clearRect(0,0,d.width,d.height),n([])},v=async()=>{if(a.length!==0){m(!0);try{const d=await oe(a);t(d.latex),r("input")}finally{m(!1)}}};return y.useEffect(()=>{const d=o.current;d&&(d.width=d.offsetWidth,d.height=200)},[]),s.jsxs("div",{children:[s.jsx("canvas",{ref:o,style:R.canvas,onPointerDown:h,onPointerMove:b,onPointerUp:w,onPointerLeave:w}),s.jsxs("div",{style:{display:"flex",gap:"8px",marginTop:"12px"},children:[s.jsx("button",{onClick:x,style:{...R.button,backgroundColor:"var(--nice-danger, #f44336)"},children:e("editor.clear","Clear")}),s.jsx("button",{onClick:v,disabled:a.length===0||p,style:R.button,children:p?e("editor.recognizing","Recognizing..."):e("editor.recognize","Recognize")})]}),s.jsx("p",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",marginTop:"8px"},children:e("editor.handwritingNote","Draw your equation above. Handwriting recognition requires external API integration.")})]})}const ke={pi:Math.PI,PI:Math.PI,e:Math.E,E:Math.E,phi:(1+Math.sqrt(5))/2,tau:Math.PI*2},Pe={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 Y{constructor(t={}){T(this,"pos",0);T(this,"expr","");T(this,"options");this.options=t}parse(t){this.expr=t.replace(/\s+/g,"").replace(/×/g,"*").replace(/÷/g,"/").replace(/−/g,"-").replace(/π/g,"pi").replace(/√(\d+(?:\.\d+)?)/g,"sqrt($1)").replace(/√/g,"sqrt"),this.pos=0;const r=this.parseAddSub();if(this.options.strict&&this.pos<this.expr.length)throw new Error(`Unexpected "${this.expr.slice(this.pos)}"`);return o=>this.evaluate(r,o)}parseAddSub(){let t=this.parseMulDiv();for(;this.pos<this.expr.length;){const r=this.expr[this.pos];if(r!=="+"&&r!=="-")break;this.pos++;const o=this.parseMulDiv();t={type:"binary",op:r,left:t,right:o}}return t}parseMulDiv(){let t=this.parseUnary();for(;this.pos<this.expr.length;){const r=this.expr[this.pos];if(r==="*"||r==="/")this.pos++,t={type:"binary",op:r,left:t,right:this.parseUnary()};else if(/[0-9a-zA-Z_(]/.test(r))t={type:"binary",op:"*",left:t,right:this.parsePower()};else break}return t}parseUnary(){return this.expr[this.pos]==="-"?(this.pos++,{type:"unary",arg:this.parseUnary()}):this.expr[this.pos]==="+"?(this.pos++,this.parseUnary()):this.parsePower()}parsePower(){const t=this.parsePrimary();return this.expr[this.pos]==="^"?(this.pos++,{type:"binary",op:"^",left:t,right:this.parseUnary()}):t}parsePrimary(){if(this.expr[this.pos]==="("){this.pos++;const o=this.parseAddSub();if(this.expr[this.pos]===")")this.pos++;else if(this.options.strict)throw new Error('Missing ")"');return o}const t=this.expr.slice(this.pos).match(/^(\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/);if(t)return this.pos+=t[0].length,{type:"number",value:parseFloat(t[0])};const r=this.expr.slice(this.pos).match(/^([a-zA-Z_][a-zA-Z0-9_]*)/);if(r){const o=r[1];if(this.pos+=o.length,this.expr[this.pos]==="("){this.pos++;const a=[];for(;this.expr[this.pos]!==")"&&this.pos<this.expr.length;)if(a.push(this.parseAddSub()),this.expr[this.pos]===",")this.pos++;else if(this.expr[this.pos]!==")")break;if(this.expr[this.pos]===")")this.pos++;else if(this.options.strict)throw new Error('Missing ")"');return{type:"call",name:o,args:a}}return{type:"variable",name:o}}if(this.options.strict)throw new Error(this.pos<this.expr.length?`Unexpected "${this.expr[this.pos]}"`:"Unexpected end");return{type:"number",value:0}}lookup(t,r){if(r in t)return t[r];if(this.options.ignoreCase){const o=r.toLowerCase(),a=Object.keys(t).find(n=>n.toLowerCase()===o);return a===void 0?void 0:t[a]}}evaluate(t,r){switch(t.type){case"number":return t.value;case"variable":{if(t.name in r)return r[t.name];const o=this.lookup({...ke,...this.options.constants},t.name);if(o!==void 0)return o;throw new Error(`Unknown variable: ${t.name}`)}case"unary":return-this.evaluate(t.arg,r);case"binary":{const o=this.evaluate(t.left,r),a=this.evaluate(t.right,r);switch(t.op){case"+":return o+a;case"-":return o-a;case"*":return o*a;case"/":return o/a;case"^":return Math.pow(o,a);default:return 0}}case"call":{const o=this.lookup({...Pe,...this.options.functions},t.name);if(!o)throw new Error(`Unknown function: ${t.name}`);const a=t.args.map(n=>this.evaluate(n,r));return o(...a)}default:return 0}}}class ne{constructor(t={}){T(this,"plots",new Map);T(this,"parser",new Y);T(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 o=this.plots.get(t);if(!o)throw new Error(`Plot not found: ${t}`);const a={...o,...r,id:o.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,o,a){const n=this.parser.parse(t),i=[],c=(r.max-r.min)/o;for(let g=0;g<=o;g++){const l=r.min+g*c;try{const p=n({x:l,...a});Number.isFinite(p)&&i.push({x:l,y:p})}catch{}}return i}compute2DParametric(t,r,o,a,n){const i=this.parser.parse(t),c=this.parser.parse(r),g=[],l=(o.max-o.min)/a;for(let p=0;p<=a;p++){const m=o.min+p*l;try{const h=i({t:m,...n}),b=c({t:m,...n});Number.isFinite(h)&&Number.isFinite(b)&&g.push({x:h,y:b})}catch{}}return g}compute2DPolar(t,r,o,a){const n=this.parser.parse(t),i=[],c=(r.max-r.min)/o;for(let g=0;g<=o;g++){const l=r.min+g*c;try{const p=n({theta:l,t:l,...a});if(Number.isFinite(p)){const m=p*Math.cos(l),h=p*Math.sin(l);i.push({x:m,y:h})}}catch{}}return i}compute3DSurface(t,r,o,a,n){const i=this.parser.parse(t),c=[],g=(r.max-r.min)/a,l=(o.max-o.min)/a;for(let p=0;p<=a;p++){const m=[],h=r.min+p*g;for(let b=0;b<=a;b++){const w=o.min+b*l;try{const x=i({x:h,y:w,...n});Number.isFinite(x)?m.push({x:h,y:w,z:x}):m.push({x:h,y:w,z:0})}catch{m.push({x:h,y:w,z:0})}}c.push(m)}return c}exportSVG(t,r,o,a){const i=o-80,c=a-80,g=m=>40+(m-r.xRange.min)/(r.xRange.max-r.xRange.min)*i,l=m=>a-40-(m-r.yRange.min)/(r.yRange.max-r.yRange.min)*c,p=[`<svg xmlns="http://www.w3.org/2000/svg" width="${o}" 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="var(--nice-border, #ddd)" stroke-width="0.5">');for(let m=Math.ceil(r.xRange.min);m<=r.xRange.max;m++){const h=g(m);p.push(`<line x1="${h}" y1="40" x2="${h}" y2="${a-40}"/>`)}for(let m=Math.ceil(r.yRange.min);m<=r.yRange.max;m++){const h=l(m);p.push(`<line x1="40" y1="${h}" x2="${o-40}" y2="${h}"/>`)}p.push("</g>")}if(r.showAxes){p.push('<g stroke="var(--nice-text, #333)" stroke-width="1">');const m=l(0),h=g(0);p.push(`<line x1="40" y1="${m}" x2="${o-40}" y2="${m}"/>`),p.push(`<line x1="${h}" y1="40" x2="${h}" y2="${a-40}"/>`),p.push("</g>")}for(const m of t.filter(h=>h.visible))if(m.type==="2d-function"){const h=this.compute2DFunction(m.expression,r.xRange,m.resolution||200);if(h.length>0){const b=h.map((w,x)=>`${x===0?"M":"L"}${g(w.x)},${l(w.y)}`).join(" ");p.push(`<path d="${b}" fill="none" stroke="rgb(${m.color.r},${m.color.g},${m.color.b})" stroke-width="${m.lineWidth}"/>`)}}return r.showLabels&&(p.push(`<text x="${o/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,o,a){const n=this.exportSVG(t,r,o,a);return new Promise((i,c)=>{const g=new Image;g.onload=()=>{const l=document.createElement("canvas");l.width=o,l.height=a;const p=l.getContext("2d");if(!p){c(new Error("Could not get canvas context"));return}p.drawImage(g,0,0),i(l.toDataURL("image/png"))},g.onerror=c,g.src="data:image/svg+xml;base64,"+btoa(n)})}generateId(){return Date.now().toString(36)+Math.random().toString(36).substring(2,8)}}function Ce(e){return new ne(e)}const G=[{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"}],ie=y.createContext(null);function L(){const e=y.useContext(ie);if(!e)throw new Error("useGraph must be used within GraphProvider");return e}const j={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 Se({service:e,width:t=800,height:r=600,className:o,style:a}){const[n,i]=y.useState([]),[c,g]=y.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}),[l,p]=y.useState({isPlaying:!1,parameter:"a",currentValue:0,minValue:-5,maxValue:5,speed:1}),m=y.useCallback(()=>{i(e.getPlots())},[e]),h=y.useCallback(u=>{g(k=>({...k,...u}))},[]),b=y.useCallback(u=>{p(k=>({...k,...u}))},[]),w=y.useCallback(u=>{e.addPlot(u),m()},[e,m]),x=y.useCallback(u=>{e.removePlot(u),m()},[e,m]),v=y.useCallback((u,k)=>{e.updatePlot(u,k),m()},[e,m]),d={service:e,plots:n,view:c,setView:h,addPlot:w,removePlot:x,updatePlot:v,animation:l,setAnimation:b,refresh:m};return s.jsx(ie.Provider,{value:d,children:s.jsxs("div",{className:o,style:{...j.container,...a},children:[s.jsxs("div",{style:j.sidebar,children:[s.jsx(Me,{}),s.jsx(je,{})]}),s.jsxs("div",{style:j.main,children:[s.jsx(Be,{width:t,height:r}),s.jsx(Te,{width:t,height:r})]})]})})}function Me(){const{t:e}=$(),{addPlot:t}=L(),[r,o]=y.useState("sin(x)"),[a,n]=y.useState("2d-function"),[i,c]=y.useState("cos(x)"),g=()=>{t({type:a,expression:r,expressionY:a==="2d-parametric"?i:void 0,color:{r:Math.floor(Math.random()*200),g:Math.floor(Math.random()*200),b:Math.floor(Math.random()*200)}})};return s.jsxs("div",{style:{padding:"12px",borderBottom:"1px solid var(--nice-border, #e0e0e0)"},children:[s.jsx("div",{style:{marginBottom:"8px"},children:s.jsxs("select",{value:a,onChange:l=>n(l.target.value),style:{...j.input,width:"100%"},children:[s.jsx("option",{value:"2d-function",children:"y = f(x)"}),s.jsx("option",{value:"2d-parametric",children:e("plotter.parametricXTYT","Parametric (x(t), y(t))")}),s.jsx("option",{value:"2d-polar",children:e("plotter.polarRF","Polar r = f(θ)")}),s.jsx("option",{value:"3d-surface",children:e("plotter.n3dSurfaceZFX","3D Surface z = f(x,y)")})]})}),s.jsx("div",{style:{marginBottom:"8px"},children:s.jsx("input",{type:"text",value:r,onChange:l=>o(l.target.value),placeholder:a==="2d-parametric"?"x(t) = ...":e("plotter.expression","Expression..."),style:{...j.input,width:"100%"}})}),a==="2d-parametric"&&s.jsx("div",{style:{marginBottom:"8px"},children:s.jsx("input",{type:"text",value:i,onChange:l=>c(l.target.value),placeholder:"y(t) = ...",style:{...j.input,width:"100%"}})}),s.jsx("button",{onClick:g,style:{...j.button,width:"100%"},children:e("plotter.addPlot","+ Add Plot")}),s.jsxs("select",{onChange:l=>{const p=G.find(m=>m.name===l.target.value);p&&t({type:p.type,expression:p.expression,expressionY:p.expressionY,label:p.name,color:{r:Math.floor(Math.random()*200),g:Math.floor(Math.random()*200),b:Math.floor(Math.random()*200)}})},style:{...j.input,width:"100%",marginTop:"8px"},value:"",children:[s.jsx("option",{value:"",disabled:!0,children:e("plotter.quickAdd","Quick add preset...")}),["basic","trigonometric","exponential","parametric","polar","3d"].map(l=>s.jsx("optgroup",{label:l.charAt(0).toUpperCase()+l.slice(1),children:G.filter(p=>p.category===l).map(p=>s.jsxs("option",{value:p.name,children:[p.name,": ",p.expression]},p.name))},l))]})]})}function je(){const{t:e}=$(),{plots:t,removePlot:r,updatePlot:o}=L();return s.jsxs("div",{style:j.plotList,children:[t.length===0&&s.jsx("div",{style:{color:"var(--nice-text-secondary, #666)",textAlign:"center",padding:"16px"},children:e("plotter.noPlots","No plots added yet")}),t.map(a=>s.jsxs("div",{style:j.plotItem,children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"8px"},children:[s.jsx("input",{type:"checkbox",checked:a.visible,onChange:n=>o(a.id,{visible:n.target.checked})}),s.jsx("div",{style:{width:"16px",height:"16px",borderRadius:"3px",backgroundColor:`rgb(${a.color.r},${a.color.g},${a.color.b})`}}),s.jsx("span",{style:{flex:1,fontWeight:500},children:a.label||a.expression}),s.jsx("button",{"aria-label":e("plotter.close","Close"),onClick:()=>r(a.id),style:{padding:"2px 6px",backgroundColor:"var(--nice-danger, #f44336)",color:"white",border:"none",borderRadius:"3px",cursor:"pointer",fontSize:"12px"},children:s.jsx(B.NiceIcon,{name:"close",size:14})})]}),s.jsx("div",{style:{fontSize:"12px",color:"var(--nice-text-secondary, #666)",fontFamily:"monospace"},children:a.type==="2d-parametric"?s.jsxs(s.Fragment,{children:["x(t) = ",a.expression,s.jsx("br",{}),"y(t) = ",a.expressionY]}):a.expression})]},a.id))]})}function Be({width:e,height:t}){const{t:r}=$(),{service:o,plots:a,view:n,setView:i}=L(),c=()=>{const l=o.exportSVG(a,n,e,t),p=new Blob([l],{type:"image/svg+xml"}),m=URL.createObjectURL(p),h=document.createElement("a");h.href=m,h.download="graph.svg",h.click(),URL.revokeObjectURL(m)},g=async()=>{const l=await o.exportPNG(a,n,e,t),p=document.createElement("a");p.href=l,p.download="graph.png",p.click()};return s.jsxs("div",{style:j.toolbar,children:[s.jsxs("label",{style:{fontSize:"12px"},children:["X: ["," ",s.jsx("input",{type:"number",value:n.xRange.min,onChange:l=>i({xRange:{...n.xRange,min:Number(l.target.value)}}),style:{...j.input,width:"50px"}}),","," ",s.jsx("input",{type:"number",value:n.xRange.max,onChange:l=>i({xRange:{...n.xRange,max:Number(l.target.value)}}),style:{...j.input,width:"50px"}}),"]"]}),s.jsxs("label",{style:{fontSize:"12px"},children:["Y: ["," ",s.jsx("input",{type:"number",value:n.yRange.min,onChange:l=>i({yRange:{...n.yRange,min:Number(l.target.value)}}),style:{...j.input,width:"50px"}}),","," ",s.jsx("input",{type:"number",value:n.yRange.max,onChange:l=>i({yRange:{...n.yRange,max:Number(l.target.value)}}),style:{...j.input,width:"50px"}}),"]"]}),s.jsxs("label",{style:{fontSize:"12px"},children:[s.jsx("input",{type:"checkbox",checked:n.showGrid,onChange:l=>i({showGrid:l.target.checked})}),r("plotter.grid","Grid")]}),s.jsxs("label",{style:{fontSize:"12px"},children:[s.jsx("input",{type:"checkbox",checked:n.showAxes,onChange:l=>i({showAxes:l.target.checked})}),r("plotter.axes","Axes")]}),s.jsx("div",{style:{flex:1}}),s.jsxs("button",{onClick:c,style:{...j.button,backgroundColor:"var(--nice-success, #4caf50)"},children:[s.jsx(B.NiceIcon,{name:"download",size:14})," SVG"]}),s.jsxs("button",{onClick:g,style:{...j.button,backgroundColor:"var(--nice-warning, #ff9800)"},children:[s.jsx(B.NiceIcon,{name:"download",size:14})," PNG"]})]})}function Te({width:e,height:t}){const r=y.useRef(null),{service:o,plots:a,view:n,animation:i}=L(),c=40;return y.useEffect(()=>{const g=r.current,l=g==null?void 0:g.getContext("2d");if(!g||!l)return;l.fillStyle=`rgb(${n.backgroundColor.r},${n.backgroundColor.g},${n.backgroundColor.b})`,l.fillRect(0,0,e,t);const p=e-c*2,m=t-c*2,h=x=>c+(x-n.xRange.min)/(n.xRange.max-n.xRange.min)*p,b=x=>t-c-(x-n.yRange.min)/(n.yRange.max-n.yRange.min)*m;if(n.showGrid){l.strokeStyle=B.resolveCssColor("var(--nice-border, #e0e0e0)",l.canvas),l.lineWidth=.5;for(let x=Math.ceil(n.xRange.min);x<=n.xRange.max;x++){const v=h(x);l.beginPath(),l.moveTo(v,c),l.lineTo(v,t-c),l.stroke()}for(let x=Math.ceil(n.yRange.min);x<=n.yRange.max;x++){const v=b(x);l.beginPath(),l.moveTo(c,v),l.lineTo(e-c,v),l.stroke()}}if(n.showAxes){l.strokeStyle=B.resolveCssColor("var(--nice-text, #333)",l.canvas),l.lineWidth=1;const x=b(0);l.beginPath(),l.moveTo(c,x),l.lineTo(e-c,x),l.stroke();const v=h(0);if(l.beginPath(),l.moveTo(v,c),l.lineTo(v,t-c),l.stroke(),n.showLabels){l.fillStyle=B.resolveCssColor("var(--nice-text, #333)",l.canvas),l.font="12px sans-serif",l.textAlign="center",l.fillText("x",e-c+15,x+4),l.fillText("y",v,c-10),l.font="10px sans-serif";for(let d=Math.ceil(n.xRange.min);d<=n.xRange.max;d++)d!==0&&l.fillText(String(d),h(d),x+15);for(let d=Math.ceil(n.yRange.min);d<=n.yRange.max;d++)d!==0&&(l.textAlign="right",l.fillText(String(d),v-5,b(d)+4))}}const w=i.isPlaying?{[i.parameter]:i.currentValue}:{};for(const x of a.filter(v=>v.visible)){const v=`rgb(${x.color.r},${x.color.g},${x.color.b})`;l.strokeStyle=v,l.lineWidth=x.lineWidth||2;let d=[];switch(x.type){case"2d-function":d=o.compute2DFunction(x.expression,n.xRange,x.resolution||200,w);break;case"2d-parametric":d=o.compute2DParametric(x.expression,x.expressionY||"sin(t)",x.parameterRange||{min:0,max:2*Math.PI},x.resolution||200,w);break;case"2d-polar":d=o.compute2DPolar(x.expression,x.parameterRange||{min:0,max:2*Math.PI},x.resolution||200,w);break}if(d.length>0){l.beginPath();let u=!1;for(const k of d){const C=h(k.x),f=b(k.y);if(f<0||f>t){u=!1;continue}u?l.lineTo(C,f):(l.moveTo(C,f),u=!0)}l.stroke()}}},[a,n,i,o,e,t]),s.jsx("canvas",{ref:r,width:e,height:t,style:j.canvas})}const N=[{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}],z={create(e,t,r=0){const o=[];for(let a=0;a<e;a++)o.push(new Array(t).fill(r));return{rows:e,cols:t,data:o}},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 o=0;o<e.rows;o++)for(let a=0;a<e.cols;a++)r.data[o][a]=e.data[o][a]+t.data[o][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 o=0;o<e.rows;o++)for(let a=0;a<e.cols;a++)r.data[o][a]=e.data[o][a]-t.data[o][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 o=0;o<e.rows;o++)for(let a=0;a<t.cols;a++){let n=0;for(let i=0;i<e.cols;i++)n+=e.data[o][i]*t.data[i][a];r.data[o][a]=n}return r},scalar(e,t){const r=this.create(e.rows,e.cols);for(let o=0;o<e.rows;o++)for(let a=0;a<e.cols;a++)r.data[o][a]=e.data[o][a]*t;return r},transpose(e){const t=this.create(e.cols,e.rows);for(let r=0;r<e.rows;r++)for(let o=0;o<e.cols;o++)t.data[o][r]=e.data[r][o];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 o=this.create(e.rows-1,e.cols-1);let a=0;for(let n=0;n<e.rows;n++){if(n===t)continue;let i=0;for(let c=0;c<e.cols;c++)c!==r&&(o.data[a][i]=e.data[n][c],i++);a++}return o},inverse(e){const t=this.determinant(e);if(t===0)throw new Error("Matrix is singular, cannot compute inverse");const r=e.rows,o=this.create(r,r);for(let a=0;a<r;a++)for(let n=0;n<r;n++){const i=Math.pow(-1,a+n),c=this.determinant(this.minor(e,a,n));o.data[n][a]=i*c}return this.scalar(o,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],o=e.data[1][0],a=e.data[1][1],n=t+a,i=t*a-r*o,c=n*n-4*i;if(c<0)throw new Error("Complex eigenvalues not supported");const g=Math.sqrt(c);return[(n+g)/2,(n-g)/2]},toString(e,t=4){return e.data.map(r=>"[ "+r.map(o=>o.toFixed(t).padStart(10)).join(" ")+" ]").join(`
4
+ `)}},U={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,o=1e3){o%2!==0&&o++;const a=(r-t)/o;let n=e(t)+e(r);for(let i=1;i<o;i++){const c=t+i*a;n+=i%2===0?2*e(c):4*e(c)}return a/3*n},findRoot(e,t,r=1e-10,o=100){let a=t;for(let n=0;n<o;n++){const i=e(a);if(Math.abs(i)<r)return a;const c=this.derivative(e,a);if(c===0)throw new Error("Derivative is zero, Newton-Raphson failed");a=a-i/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 o=parseInt(t[1],10);return o===1?"1":o===2?"2*x":`${o}*x^${o-1}`}const r=e.match(/^(-?\d+\.?\d*)\*x\^(\d+)$/);if(r){const o=parseFloat(r[1]),a=parseInt(r[2],10),n=o*a;return a===1?String(n):a===2?`${n}*x`:`${n}*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 o=t*t-4*e*r;if(o<0)throw new Error("No real solutions (complex roots)");if(o===0)return[-t/(2*e)];const a=Math.sqrt(o);return[(-t+a)/(2*e),(-t-a)/(2*e)]}};class se{constructor(t={}){T(this,"history",[]);T(this,"memory",0);T(this,"variables",new Map);T(this,"config");this.config={precision:t.precision??12,angleUnit:t.angleUnit??"rad"}}evaluate(t){const r=this.config.angleUnit==="deg",o=c=>r?c*Math.PI/180:c,a=c=>r?c*180/Math.PI:c,n=new Y({strict:!0,ignoreCase:!0,functions:{log:Math.log10,sin:c=>Math.sin(o(c)),cos:c=>Math.cos(o(c)),tan:c=>Math.tan(o(c)),asin:c=>a(Math.asin(c)),acos:c=>a(Math.acos(c)),atan:c=>a(Math.atan(c))}});let i;try{i=n.parse(t)(Object.fromEntries(this.variables))}catch(c){throw new Error(`Invalid expression: ${c.message}`)}if(!Number.isFinite(i))throw new Error("Invalid expression: Invalid result");return i}addHistory(t,r,o){this.history.unshift({id:Date.now().toString(36),expression:t,result:r,timestamp:new Date().toISOString(),mode:o}),this.history.length>100&&this.history.pop()}getHistory(){return this.history}clearHistory(){this.history=[]}memoryStore(t){this.memory=t}memoryRecall(){return this.memory}memoryAdd(t){this.memory+=t}memoryClear(){this.memory=0}setVariable(t,r){this.variables.set(t,r)}getVariable(t){return this.variables.get(t)}convertBase(t,r,o){const a={BIN:2,OCT:8,DEC:10,HEX:16},n=parseInt(t,a[r]);if(isNaN(n))throw new Error("Invalid number for base conversion");return n.toString(a[o]).toUpperCase()}convertUnits(t,r,o){const a=N.find(c=>c.symbol===r),n=N.find(c=>c.symbol===o);if(!a||!n)throw new Error("Unknown unit");if(a.category!==n.category)throw new Error("Cannot convert between different unit categories");const i=a.toBase(t);return n.fromBase(i)}getUnitsByCategory(t){return N.filter(r=>r.category===t)}getUnitCategories(){return[...new Set(N.map(t=>t.category))]}format(t){const r=this.config.precision;return Math.abs(t)<1e-10?"0":Math.abs(t)>1e10||Math.abs(t)<1e-6?t.toExponential(r):parseFloat(t.toPrecision(r)).toString()}}function Re(e){return new se(e)}const le=y.createContext(null);function I(){const e=y.useContext(le);if(!e)throw new Error("useCalculator must be used within CalculatorProvider");return e}const M={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-text-primary, #fff)",fontSize:"32px",fontFamily:"'JetBrains Mono', monospace",textAlign:"right",wordBreak:"break-all"},keypad:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:"1px",backgroundColor:"var(--nice-bg-tertiary, #333)",padding:"1px"},key:{padding:"20px",border:"none",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",fontSize:"18px",cursor:"pointer",transition:"background-color 0.1s"},keyOperator:{backgroundColor:"var(--nice-warning, #ff9f0a)",color:"var(--nice-text, #000)"},keyFunction:{backgroundColor:"var(--nice-bg-tertiary, #505050)"}};function ze({service:e,className:t,style:r}){const[o,a]=y.useState("0"),[n,i]=y.useState("standard"),[c,g]=y.useState([]),[l,p]=y.useState(!1),m=y.useCallback(x=>{l&&/[0-9.]/.test(x)?(a(x),p(!1)):(a(v=>v==="0"&&x!=="."?x:v+x),p(!1))},[l]),h=y.useCallback(()=>{a("0"),p(!1)},[]),b=y.useCallback(()=>{try{const x=e.evaluate(o),v=e.format(x);e.addHistory(o,v,n),g(e.getHistory()),a(v),p(!0)}catch{a("Error"),p(!0)}},[o,n,e]),w={service:e,display:o,setDisplay:a,mode:n,setMode:i,history:c,calculate:b,appendDigit:m,clear:h};return s.jsx(le.Provider,{value:w,children:s.jsxs("div",{className:t,style:{...M.container,...r},children:[s.jsx(Ae,{}),s.jsx($e,{}),n==="standard"&&s.jsx(ce,{}),n==="scientific"&&s.jsx(Ee,{}),n==="programmer"&&s.jsx(Ie,{}),n==="matrix"&&s.jsx(qe,{}),n==="calculus"&&s.jsx(De,{}),n==="units"&&s.jsx(Le,{})]})})}function Ae(){const{t:e}=$(),{mode:t,setMode:r}=I(),o=[{id:"standard",label:e("calculator.standard","Standard")},{id:"scientific",label:e("calculator.scientific","Scientific")},{id:"programmer",label:e("calculator.programmer","Programmer")},{id:"matrix",label:e("calculator.matrix","Matrix")},{id:"calculus",label:e("calculator.calculus","Calculus")},{id:"units",label:e("calculator.units","Units")}];return s.jsx("div",{style:M.modeSelector,children:o.map(a=>s.jsx("button",{onClick:()=>r(a.id),style:{...M.modeButton,backgroundColor:t===a.id?"var(--nice-primary-hover, #1976d2)":"transparent",color:t===a.id?"var(--nice-color-white, #fff)":"var(--nice-text-secondary, #888)"},children:a.label},a.id))})}function $e(){const{display:e}=I();return s.jsx("div",{style:M.display,children:s.jsx("div",{style:M.displayText,children:e})})}function ce(){const{appendDigit:e,clear:t,calculate:r,setDisplay:o,display:a}=I(),n=[{label:"AC",action:t,style:M.keyFunction},{label:"±",action:()=>o(a.startsWith("-")?a.slice(1):"-"+a),style:M.keyFunction},{label:"%",action:()=>e("/100"),style:M.keyFunction},{label:"÷",action:()=>e("/"),style:M.keyOperator},{label:"7",action:()=>e("7")},{label:"8",action:()=>e("8")},{label:"9",action:()=>e("9")},{label:"×",action:()=>e("*"),style:M.keyOperator},{label:"4",action:()=>e("4")},{label:"5",action:()=>e("5")},{label:"6",action:()=>e("6")},{label:"−",action:()=>e("-"),style:M.keyOperator},{label:"1",action:()=>e("1")},{label:"2",action:()=>e("2")},{label:"3",action:()=>e("3")},{label:"+",action:()=>e("+"),style:M.keyOperator},{label:"0",action:()=>e("0")},{label:".",action:()=>e(".")},{label:"⌫",action:()=>o(a.length>1?a.slice(0,-1):"0")},{label:"=",action:r,style:M.keyOperator}];return s.jsx("div",{style:M.keypad,children:n.map((i,c)=>s.jsx("button",{onClick:i.action,style:{...M.key,...i.style||{}},children:i.label},c))})}function Ee(){const{appendDigit:e,clear:t,calculate:r,setDisplay:o,display:a}=I(),n=[{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(")}],i=[{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 s.jsxs("div",{children:[s.jsx("div",{style:{...M.keypad,gridTemplateColumns:"repeat(5, 1fr)"},children:[...n,...i,...c].map((g,l)=>s.jsx("button",{onClick:g.action,style:{...M.key,...M.keyFunction,padding:"12px"},children:g.label},l))}),s.jsx(ce,{})]})}function Ie(){const{display:e,setDisplay:t,service:r}=I(),[o,a]=y.useState("DEC"),n=c=>{try{const g=r.convertBase(e,o,c);t(g),a(c)}catch{t("Error")}},i=o==="HEX"?["A","B","C","D","E","F"]:[];return s.jsxs("div",{children:[s.jsx("div",{style:{display:"flex",gap:"4px",padding:"8px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:["BIN","OCT","DEC","HEX"].map(c=>s.jsx("button",{onClick:()=>n(c),style:{flex:1,padding:"8px",border:"none",borderRadius:"4px",backgroundColor:o===c?"var(--nice-primary-hover, #1976d2)":"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",cursor:"pointer"},children:c},c))}),i.length>0&&s.jsx("div",{style:{...M.keypad,gridTemplateColumns:"repeat(6, 1fr)"},children:i.map(c=>s.jsx("button",{onClick:()=>t(e==="0"?c:e+c),style:M.key,children:c},c))}),s.jsx("div",{style:{...M.keypad,gridTemplateColumns:"repeat(4, 1fr)"},children:["7","8","9","AND","4","5","6","OR","1","2","3","XOR","0","NOT","<<",">>"].map(c=>{const g=["AND","OR","XOR","NOT","<<",">>"].includes(c);return s.jsx("button",{onClick:()=>t(e==="0"?c:e+c),style:{...M.key,...g?M.keyFunction:{}},children:c},c)})})]})}function qe(){const{t:e}=$(),[t,r]=y.useState(z.create(2,2)),[o,a]=y.useState(z.create(2,2)),[n,i]=y.useState(""),c=(l,p,m,h,b)=>{const w={...l,data:l.data.map(x=>[...x])};w.data[m][h]=parseFloat(b)||0,p(w)},g=[{label:"A + B",fn:()=>z.toString(z.add(t,o))},{label:"A - B",fn:()=>z.toString(z.subtract(t,o))},{label:"A × B",fn:()=>z.toString(z.multiply(t,o))},{label:"det(A)",fn:()=>z.determinant(t).toFixed(4)},{label:"Aᵀ",fn:()=>z.toString(z.transpose(t))},{label:"A⁻¹",fn:()=>z.toString(z.inverse(t))}];return s.jsxs("div",{style:{padding:"12px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:[s.jsxs("div",{style:{display:"flex",gap:"12px",marginBottom:"12px"},children:[s.jsxs("div",{children:[s.jsx("div",{style:{color:"var(--nice-text-secondary, #888)",marginBottom:"4px"},children:e("calculator.matrixA","Matrix A")}),s.jsx(_,{matrix:t,onChange:(l,p,m)=>c(t,r,l,p,m)})]}),s.jsxs("div",{children:[s.jsx("div",{style:{color:"var(--nice-text-secondary, #888)",marginBottom:"4px"},children:e("calculator.matrixB","Matrix B")}),s.jsx(_,{matrix:o,onChange:(l,p,m)=>c(o,a,l,p,m)})]})]}),s.jsx("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginBottom:"12px"},children:g.map(l=>s.jsx("button",{onClick:()=>{try{i(l.fn())}catch(p){i(p.message)}},style:{padding:"8px 12px",backgroundColor:"var(--nice-primary-hover, #1976d2)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:"4px",cursor:"pointer"},children:l.label},l.label))}),n&&s.jsx("pre",{style:{color:"var(--nice-text-primary, #fff)",fontFamily:"monospace",whiteSpace:"pre-wrap"},children:n})]})}function _({matrix:e,onChange:t}){return s.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(${e.cols}, 50px)`,gap:"4px"},children:e.data.map((r,o)=>r.map((a,n)=>s.jsx("input",{type:"number",value:a,onChange:i=>t(o,n,i.target.value),style:{width:"100%",padding:"4px",textAlign:"center",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"}},`${o}-${n}`)))})}function De(){const{t:e}=$(),[t,r]=y.useState("x^2"),[o,a]=y.useState("");return s.jsxs("div",{style:{padding:"12px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:[s.jsx("input",{type:"text",value:t,onChange:n=>r(n.target.value),placeholder:e("calculator.exprPlaceholder","Enter expression (e.g., x^2, sin(x))"),style:{width:"100%",padding:"8px",marginBottom:"12px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"}}),s.jsxs("div",{style:{display:"flex",gap:"4px",flexWrap:"wrap",marginBottom:"12px"},children:[s.jsx("button",{onClick:()=>a(`d/dx(${t}) = ${U.symbolicDerivative(t)}`),style:{padding:"8px 12px",backgroundColor:"var(--nice-success, #4caf50)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:"4px",cursor:"pointer"},children:e("calculator.differentiate","Differentiate")}),s.jsx("button",{onClick:()=>a(`∫(${t})dx = ${U.symbolicIntegral(t)}`),style:{padding:"8px 12px",backgroundColor:"var(--nice-primary, #2196f3)",color:"var(--nice-text-on-primary, #fff)",border:"none",borderRadius:"4px",cursor:"pointer"},children:e("calculator.integrate","Integrate")})]}),o&&s.jsx("div",{style:{color:"var(--nice-text-primary, #fff)",fontFamily:"monospace",padding:"8px",backgroundColor:"var(--nice-bg, #1e1e1e)",borderRadius:"4px"},children:o})]})}function Le(){const{t:e}=$(),{service:t}=I(),[r,o]=y.useState("1"),[a,n]=y.useState("m"),[i,c]=y.useState("ft"),[g,l]=y.useState("Length"),[p,m]=y.useState(""),h=t.getUnitCategories(),b=t.getUnitsByCategory(g),w=()=>{try{const x=t.convertUnits(parseFloat(r),a,i);m(`${r} ${a} = ${t.format(x)} ${i}`)}catch(x){m(x.message)}};return s.jsxs("div",{style:{padding:"12px",backgroundColor:"var(--nice-bg-secondary, #252525)"},children:[s.jsx("select",{value:g,onChange:x=>{l(x.target.value);const v=t.getUnitsByCategory(x.target.value);v.length>=2&&(n(v[0].symbol),c(v[1].symbol))},style:{width:"100%",padding:"8px",marginBottom:"12px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"},children:h.map(x=>s.jsx("option",{value:x,children:x},x))}),s.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center",marginBottom:"12px"},children:[s.jsx("input",{type:"number",value:r,onChange:x=>o(x.target.value),style:{flex:1,padding:"8px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"}}),s.jsx("select",{value:a,onChange:x=>n(x.target.value),style:{padding:"8px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"},children:b.map(x=>s.jsxs("option",{value:x.symbol,children:[x.name," (",x.symbol,")"]},x.symbol))})]}),s.jsxs("div",{style:{display:"flex",gap:"8px",alignItems:"center",marginBottom:"12px"},children:[s.jsx("span",{style:{color:"var(--nice-text-secondary, #888)"},children:s.jsx(B.NiceIcon,{name:"arrow-right",size:12})}),s.jsx("select",{value:i,onChange:x=>c(x.target.value),style:{flex:1,padding:"8px",backgroundColor:"var(--nice-border, #3c3c3c)",color:"var(--nice-color-white, #fff)",border:"1px solid var(--nice-border-color, #555)",borderRadius:"4px"},children:b.map(x=>s.jsxs("option",{value:x.symbol,children:[x.name," (",x.symbol,")"]},x.symbol))})]}),s.jsx("button",{onClick:w,style:{width:"100%",padding:"12px",backgroundColor:"var(--nice-warning, #ff9f0a)",color:"var(--nice-text, #000)",border:"none",borderRadius:"4px",fontSize:"16px",cursor:"pointer"},children:e("calculator.convert","Convert")}),p&&s.jsx("div",{style:{marginTop:"12px",color:"var(--nice-text-primary, #fff)",fontSize:"18px",textAlign:"center"},children:p})]})}const A={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 o=Math.atan2(e.y-t.y,e.x-t.x);let n=Math.atan2(r.y-t.y,r.x-t.x)-o;return n<0&&(n+=2*Math.PI),n},angleDegrees(e,t,r){return this.angle(e,t,r)*180/Math.PI},closestPointOnLine(e,t,r){const o=t.x-e.x,a=t.y-e.y,n=((r.x-e.x)*o+(r.y-e.y)*a)/(o*o+a*a);return{x:e.x+n*o,y:e.y+n*a}},lineIntersection(e,t,r,o){const a=(e.x-t.x)*(r.y-o.y)-(e.y-t.y)*(r.x-o.x);if(Math.abs(a)<1e-10)return null;const n=((e.x-r.x)*(r.y-o.y)-(e.y-r.y)*(r.x-o.x))/a;return{x:e.x+n*(t.x-e.x),y:e.y+n*(t.y-e.y)}},circleLineIntersection(e,t,r,o){const a=o.x-r.x,n=o.y-r.y,i=r.x-e.x,c=r.y-e.y,g=a*a+n*n,l=2*(i*a+c*n),p=i*i+c*c-t*t,m=l*l-4*g*p;if(m<0)return[];const h=Math.sqrt(m),b=(-l-h)/(2*g),w=(-l+h)/(2*g),x=[];return b>=0&&b<=1&&x.push({x:r.x+b*a,y:r.y+b*n}),w>=0&&w<=1&&Math.abs(w-b)>1e-10&&x.push({x:r.x+w*a,y:r.y+w*n}),x},circleCircleIntersection(e,t,r,o){const a=this.distance(e,r);if(a>t+o||a<Math.abs(t-o)||a===0)return[];const n=(t*t-o*o+a*a)/(2*a),i=Math.sqrt(t*t-n*n),c=e.x+n*(r.x-e.x)/a,g=e.y+n*(r.y-e.y)/a;return[{x:c+i*(r.y-e.y)/a,y:g-i*(r.x-e.x)/a},{x:c-i*(r.y-e.y)/a,y:g+i*(r.x-e.x)/a}]},perpendicularThrough(e,t,r){this.closestPointOnLine(e,t,r);const o=t.x-e.x,a=t.y-e.y;return{p1:r,p2:{x:r.x-a,y:r.y+o}}},parallelThrough(e,t,r){const o=t.x-e.x,a=t.y-e.y;return{p1:r,p2:{x:r.x+o,y:r.y+a}}},angleBisector(e,t,r){const o=Math.atan2(e.y-t.y,e.x-t.x),a=Math.atan2(r.y-t.y,r.x-t.x);let n=(o+a)/2;return Math.abs(a-o)>Math.PI&&(n+=Math.PI),{x:t.x+Math.cos(n),y:t.y+Math.sin(n)}},reflect(e,t,r){const o=this.closestPointOnLine(t,r,e);return{x:2*o.x-e.x,y:2*o.y-e.y}},rotate(e,t,r){const o=Math.cos(r),a=Math.sin(r),n=e.x-t.x,i=e.y-t.y;return{x:t.x+n*o-i*a,y:t.y+n*a+i*o}},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 o=0;o<r;o++){const a=(o+1)%r;t+=e[o].x*e[a].y,t-=e[a].x*e[o].y}return Math.abs(t)/2},polygonPerimeter(e){let t=0;const r=e.length;for(let o=0;o<r;o++){const a=(o+1)%r;t+=this.distance(e[o],e[a])}return t},circumcenter(e,t,r){const o=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))/o,n=((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))/o;return{x:a,y:n}},incenter(e,t,r){const o=this.distance(e,t),a=this.distance(t,r),n=this.distance(r,e),i=o+a+n;return{x:(a*e.x+n*t.x+o*r.x)/i,y:(a*e.y+n*t.y+o*r.y)/i}},centroid(e,t,r){return{x:(e.x+t.x+r.x)/3,y:(e.y+t.y+r.y)/3}}};class de{constructor(){T(this,"elements",new Map);T(this,"nextLabel",1)}addElement(t){const r=this.generateId(),o={...t,id:r};return this.elements.set(r,o),o}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 o=this.elements.get(t);o&&this.elements.set(t,{...o,...r,id:t,type:o.type})}deleteElement(t){var r;this.elements.delete(t);for(const[o,a]of this.elements)(r=a.dependencies)!=null&&r.includes(t)&&this.deleteElement(o)}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,o){return this.addElement({type:"point",x:t,y:r,label:o??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 o=this.getPoint(t),a=this.getPoint(r);if(!o||!a)return null;const n=A.midpoint(o,a),i=this.createPoint(n.x,n.y);return i.dependencies=[t,r],i.color={r:0,g:150,b:0},i}createPerpendicular(t,r,o){const a=this.getPoint(t),n=this.getPoint(r),i=this.getPoint(o);if(!a||!n||!i)return null;const c=A.perpendicularThrough(a,n,i),g=this.createPoint(c.p2.x,c.p2.y),l=this.createLine(o,g.id);return l.dependencies=[t,r,o],l}createParallel(t,r,o){const a=this.getPoint(t),n=this.getPoint(r),i=this.getPoint(o);if(!a||!n||!i)return null;const c=A.parallelThrough(a,n,i),g=this.createPoint(c.p2.x,c.p2.y),l=this.createLine(o,g.id);return l.dependencies=[t,r,o],l}createIntersection(t,r){const o=this.elements.get(t),a=this.elements.get(r);if(!o||!a)return[];const n=[],i=l=>{if(l.type==="line"||l.type==="segment"||l.type==="ray"){const p=l,m=this.getPoint(p.point1Id??p.originId),h=this.getPoint(p.point2Id??p.throughId);if(m&&h)return[m,h]}return null},c=i(o),g=i(a);if(c&&g){const l=A.lineIntersection(c[0],c[1],g[0],g[1]);if(l){const p=this.createPoint(l.x,l.y);p.dependencies=[t,r],p.color={r:255,g:0,b:0},n.push(p)}}if(o.type==="circle"&&g){const l=o,p=this.getPoint(l.centerId);if(p){const m=A.circleLineIntersection(p,l.radius,g[0],g[1]);for(const h of m){const b=this.createPoint(h.x,h.y);b.dependencies=[t,r],b.color={r:255,g:0,b:0},n.push(b)}}}if(o.type==="circle"&&a.type==="circle"){const l=o,p=a,m=this.getPoint(l.centerId),h=this.getPoint(p.centerId);if(m&&h){const b=A.circleCircleIntersection(m,l.radius,h,p.radius);for(const w of b){const x=this.createPoint(w.x,w.y);x.dependencies=[t,r],x.color={r:255,g:0,b:0},n.push(x)}}}return n}calculateMeasurement(t,r){switch(t){case"distance":{const o=this.getPoint(r[0]),a=this.getPoint(r[1]);if(o&&a)return A.distance(o,a);break}case"angle":{const o=this.getPoint(r[0]),a=this.getPoint(r[1]),n=this.getPoint(r[2]);if(o&&a&&n)return A.angleDegrees(o,a,n);break}case"area":case"perimeter":{const o=this.elements.get(r[0]);if((o==null?void 0:o.type)==="polygon"){const a=o.pointIds.map(n=>this.getPoint(n)).filter(Boolean);return t==="area"?A.polygonArea(a):A.polygonPerimeter(a)}break}}return 0}exportSVG(t,r,o){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(${o.backgroundColor.r},${o.backgroundColor.g},${o.backgroundColor.b})"/>`);const n=(i,c)=>({x:t/2+(i-o.centerX)*o.scale,y:r/2-(c-o.centerY)*o.scale});if(o.showGrid){a.push('<g stroke="var(--nice-border, #ddd)" stroke-width="0.5">');for(let i=Math.floor(-t/2/o.scale+o.centerX);i<=t/2/o.scale+o.centerX;i+=o.gridSpacing){const c=n(i,0);a.push(`<line x1="${c.x}" y1="0" x2="${c.x}" y2="${r}"/>`)}for(let i=Math.floor(-r/2/o.scale+o.centerY);i<=r/2/o.scale+o.centerY;i+=o.gridSpacing){const c=n(0,i);a.push(`<line x1="0" y1="${c.y}" x2="${t}" y2="${c.y}"/>`)}a.push("</g>")}if(o.showAxes){const i=n(0,0);a.push('<g stroke="var(--nice-text, #333)" stroke-width="1">'),a.push(`<line x1="0" y1="${i.y}" x2="${t}" y2="${i.y}"/>`),a.push(`<line x1="${i.x}" y1="0" x2="${i.x}" y2="${r}"/>`),a.push("</g>")}for(const i of this.getAllElements()){if(!i.visible)continue;const c=`rgb(${i.color.r},${i.color.g},${i.color.b})`;switch(i.type){case"point":{const g=n(i.x,i.y);a.push(`<circle cx="${g.x}" cy="${g.y}" r="${i.size}" fill="${c}"/>`),i.label&&a.push(`<text x="${g.x+8}" y="${g.y-8}" font-size="12">${i.label}</text>`);break}case"segment":{const g=this.getPoint(i.point1Id),l=this.getPoint(i.point2Id);if(g&&l){const p=n(g.x,g.y),m=n(l.x,l.y);a.push(`<line x1="${p.x}" y1="${p.y}" x2="${m.x}" y2="${m.y}" stroke="${c}" stroke-width="${i.width}"/>`)}break}case"circle":{const g=this.getPoint(i.centerId);if(g){const l=n(g.x,g.y),p=i.radius*o.scale,m=i.fill?`rgba(${i.fill.r},${i.fill.g},${i.fill.b},${i.fill.a??.2})`:"none";a.push(`<circle cx="${l.x}" cy="${l.y}" r="${p}" fill="${m}" stroke="${c}" stroke-width="${i.width}"/>`)}break}case"polygon":{const g=i.pointIds.map(l=>this.getPoint(l)).filter(Boolean);if(g.length>0){const p=g.map(h=>n(h.x,h.y)).map((h,b)=>`${b===0?"M":"L"}${h.x},${h.y}`).join(" ")+" Z",m=i.fill?`rgba(${i.fill.r},${i.fill.g},${i.fill.b},${i.fill.a??.2})`:"none";a.push(`<path d="${p}" fill="${m}" stroke="${c}" stroke-width="${i.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 Ne(){return new de}const pe=y.createContext(null);function F(){const e=y.useContext(pe);if(!e)throw new Error("useGeometry must be used within GeometryProvider");return e}const D={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 Xe({service:e,width:t=800,height:r=600,className:o,style:a}){const[n,i]=y.useState([]),[c,g]=y.useState("point"),[l,p]=y.useState([]),[m,h]=y.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=y.useCallback(()=>{i(e.getAllElements())},[e]),w=y.useCallback(v=>{h(d=>({...d,...v}))},[]);y.useEffect(()=>{b()},[b]);const x={service:e,elements:n,tool:c,setTool:g,view:m,setView:w,selectedIds:l,setSelectedIds:p,refresh:b};return s.jsx(pe.Provider,{value:x,children:s.jsxs("div",{className:o,style:{...D.container,...a},children:[s.jsx(Fe,{}),s.jsxs("div",{style:D.main,children:[s.jsx(Oe,{width:t,height:r}),s.jsx(Ge,{width:t,height:r})]})]})})}function Fe(){const{t:e}=$(),{tool:t,setTool:r}=F(),o=[{id:"select",icon:"cursor",title:e("geometry.select","Select")},{id:"point",icon:"point",title:e("geometry.point","Point")},{id:"segment",icon:"segment",title:e("geometry.segment","Segment")},{id:"line",icon:"line",title:e("geometry.line","Line")},{id:"ray",icon:"arrow-right",title:e("geometry.ray","Ray")},{id:"circle",icon:"circle",title:e("geometry.circle","Circle")},{id:"polygon",icon:"triangle",title:e("geometry.polygon","Polygon")},{id:"perpendicular",icon:"perpendicular",title:e("geometry.perpendicular","Perpendicular")},{id:"parallel",icon:"parallel",title:e("geometry.parallel","Parallel")},{id:"midpoint",icon:"midpoint",title:e("geometry.midpoint","Midpoint")},{id:"bisector",icon:"angle-bisector",title:e("geometry.angleBisector","Angle Bisector")},{id:"intersection",icon:"close",title:e("geometry.intersection","Intersection")},{id:"reflect",icon:"shuffle",title:e("geometry.reflect","Reflect")},{id:"rotate",icon:"refresh",title:e("geometry.rotate","Rotate")},{id:"measure",icon:"ruler",title:e("geometry.measure","Measure")}];return s.jsx("div",{style:D.toolbar,children:o.map(a=>s.jsx("button",{onClick:()=>r(a.id),title:a.title,style:{...D.toolButton,backgroundColor:t===a.id?"var(--nice-primary-hover, #1976d2)":"transparent",color:t===a.id?"var(--nice-color-white, #fff)":"var(--nice-text, #333)"},children:s.jsx(B.NiceIcon,{name:a.icon,size:16})},a.id))})}function Oe({width:e,height:t}){const r=y.useRef(null),{service:o,elements:a,tool:n,view:i,selectedIds:c,setSelectedIds:g,refresh:l}=F(),[p,m]=y.useState([]),h=y.useCallback((v,d)=>{const u=(v-e/2)/i.scale+i.centerX,k=-(d-t/2)/i.scale+i.centerY;return i.snapToGrid?{x:Math.round(u/i.gridSpacing)*i.gridSpacing,y:Math.round(k/i.gridSpacing)*i.gridSpacing}:{x:u,y:k}},[e,t,i]),b=y.useCallback((v,d)=>({x:e/2+(v-i.centerX)*i.scale,y:t/2-(d-i.centerY)*i.scale}),[e,t,i]),w=y.useCallback(v=>{for(const u of a)if(u.type==="point"&&A.distance(u,v)<.5)return u},[a]),x=y.useCallback(v=>{var k;const d=(k=r.current)==null?void 0:k.getBoundingClientRect();if(!d)return;const u=h(v.clientX-d.left,v.clientY-d.top);switch(n){case"point":{o.createPoint(u.x,u.y),l();break}case"segment":case"line":case"ray":{const C=w(u);if(C)m(f=>{const P=[...f,C.id];return P.length===2?(n==="segment"?o.createSegment(P[0],P[1]):n==="line"?o.createLine(P[0],P[1]):n==="ray"&&o.createRay(P[0],P[1]),l(),[]):P});else{const f=o.createPoint(u.x,u.y);m(P=>{const S=[...P,f.id];return S.length===2?(n==="segment"?o.createSegment(S[0],S[1]):n==="line"?o.createLine(S[0],S[1]):n==="ray"&&o.createRay(S[0],S[1]),l(),[]):S}),l()}break}case"circle":{const C=w(u);if(C)m(f=>{if(f.length===0)return[C.id];const P=o.getPoint(f[0]);if(P){const S=A.distance(P,u);o.createCircle(f[0],S),l()}return[]});else if(p.length===1){const f=o.getPoint(p[0]);if(f){const P=A.distance(f,u);o.createCircle(p[0],P),l(),m([])}}else{const f=o.createPoint(u.x,u.y);m([f.id]),l()}break}case"midpoint":{const C=w(u);C&&m(f=>{const P=[...f,C.id];return P.length===2?(o.createMidpoint(P[0],P[1]),l(),[]):P});break}case"select":{const C=w(u);g(C?[C.id]:[]);break}}},[n,o,l,h,p,g,w]);return y.useEffect(()=>{const v=r.current,d=v==null?void 0:v.getContext("2d");if(!(!v||!d)){if(d.fillStyle=`rgb(${i.backgroundColor.r},${i.backgroundColor.g},${i.backgroundColor.b})`,d.fillRect(0,0,e,t),i.showGrid){d.strokeStyle=B.resolveCssColor("var(--nice-border, #e0e0e0)",d.canvas),d.lineWidth=.5;const u=i.gridSpacing*i.scale,k=(e/2-i.centerX*i.scale)%u,C=(t/2+i.centerY*i.scale)%u;for(let f=k;f<e;f+=u)d.beginPath(),d.moveTo(f,0),d.lineTo(f,t),d.stroke();for(let f=C;f<t;f+=u)d.beginPath(),d.moveTo(0,f),d.lineTo(e,f),d.stroke()}if(i.showAxes){const u=b(0,0);d.strokeStyle=B.resolveCssColor("var(--nice-text, #333)",d.canvas),d.lineWidth=1,d.beginPath(),d.moveTo(0,u.y),d.lineTo(e,u.y),d.stroke(),d.beginPath(),d.moveTo(u.x,0),d.lineTo(u.x,t),d.stroke()}for(const u of a){if(!u.visible)continue;const k=`rgb(${u.color.r},${u.color.g},${u.color.b})`,C=c.includes(u.id);switch(u.type){case"point":{const f=b(u.x,u.y);d.beginPath(),d.arc(f.x,f.y,C?u.size+2:u.size,0,2*Math.PI),d.fillStyle=C?B.resolveCssColor("var(--nice-primary-hover, #1976d2)",d.canvas):k,d.fill(),u.label&&(d.fillStyle=B.resolveCssColor("var(--nice-text, #333)",d.canvas),d.font="12px sans-serif",d.fillText(u.label,f.x+8,f.y-8));break}case"segment":{const f=o.getPoint(u.point1Id),P=o.getPoint(u.point2Id);if(f&&P){const S=b(f.x,f.y),E=b(P.x,P.y);d.strokeStyle=k,d.lineWidth=u.width,d.beginPath(),d.moveTo(S.x,S.y),d.lineTo(E.x,E.y),d.stroke()}break}case"line":{const f=o.getPoint(u.point1Id),P=o.getPoint(u.point2Id);if(f&&P){const S=P.x-f.x,E=P.y-f.y,V=-1e3,K=1e3,W=b(f.x+V*S,f.y+V*E),H=b(f.x+K*S,f.y+K*E);d.strokeStyle=k,d.lineWidth=u.width,d.beginPath(),d.moveTo(W.x,W.y),d.lineTo(H.x,H.y),d.stroke()}break}case"circle":{const f=o.getPoint(u.centerId);if(f){const P=b(f.x,f.y),S=u.radius*i.scale;d.beginPath(),d.arc(P.x,P.y,S,0,2*Math.PI),u.fill&&(d.fillStyle=`rgba(${u.fill.r},${u.fill.g},${u.fill.b},${u.fill.a??.2})`,d.fill()),d.strokeStyle=k,d.lineWidth=u.width,d.stroke()}break}case"polygon":{const f=u.pointIds.map(P=>o.getPoint(P)).filter(Boolean);if(f.length>0){d.beginPath();const P=b(f[0].x,f[0].y);d.moveTo(P.x,P.y);for(let S=1;S<f.length;S++){const E=b(f[S].x,f[S].y);d.lineTo(E.x,E.y)}d.closePath(),u.fill&&(d.fillStyle=`rgba(${u.fill.r},${u.fill.g},${u.fill.b},${u.fill.a??.2})`,d.fill()),d.strokeStyle=k,d.lineWidth=u.width,d.stroke()}break}}}if(p.length>0){d.fillStyle=B.resolveCssColor("var(--nice-primary-tint-30, rgba(25, 118, 210, 0.3))",d.canvas);for(const u of p){const k=o.getPoint(u);if(k){const C=b(k.x,k.y);d.beginPath(),d.arc(C.x,C.y,12,0,2*Math.PI),d.fill()}}}}},[a,i,e,t,c,p,o,b]),s.jsx("canvas",{ref:r,width:e,height:t,style:D.canvas,onClick:x})}function Ge({width:e,height:t}){const{t:r}=$(),{tool:o,elements:a,view:n,service:i}=F(),[c,g]=y.useState(null),l={select:r("geometry.select","Select"),point:r("geometry.point","Point"),line:r("geometry.line","Line"),ray:r("geometry.ray","Ray"),segment:r("geometry.segment","Segment"),circle:r("geometry.circle","Circle"),arc:r("geometry.arc","Arc"),polygon:r("geometry.polygon","Polygon"),angle:r("geometry.angle","Angle"),perpendicular:r("geometry.perpendicular","Perpendicular"),parallel:r("geometry.parallel","Parallel"),bisector:r("geometry.angleBisector","Angle Bisector"),midpoint:r("geometry.midpoint","Midpoint"),tangent:r("geometry.tangent","Tangent"),intersection:r("geometry.intersection","Intersection"),reflect:r("geometry.reflect","Reflect"),rotate:r("geometry.rotate","Rotate"),translate:r("geometry.translate","Translate"),dilate:r("geometry.dilate","Dilate"),measure:r("geometry.measure","Measure"),text:r("geometry.text","Text")},p=a.filter(m=>m.type==="point").length;return s.jsxs("div",{style:D.statusBar,children:[s.jsx("span",{children:r("geometry.tool","Tool: {tool}").replace("{tool}",String(l[o]))}),s.jsx("span",{style:{margin:"0 16px"},children:"|"}),s.jsx("span",{children:r("geometry.objects","Objects: {elements}").replace("{elements}",String(a.length))}),s.jsx("span",{style:{margin:"0 16px"},children:"|"}),s.jsx("span",{children:r("geometry.points","Points: {pointCount}").replace("{pointCount}",String(p))}),s.jsx("span",{style:{margin:"0 16px"},children:"|"}),s.jsx("span",{children:r("geometry.scaleX","Scale: {scale}x").replace("{scale}",String(n.scale.toFixed(1)))})]})}exports.CalculatorService=se;exports.CalculusOps=U;exports.EQUATION_TEMPLATES=te;exports.ExpressionParser=Y;exports.FUNCTION_PRESETS=G;exports.GeoMath=A;exports.GeometryService=de;exports.GraphService=ne;exports.MATH_SYMBOLS=Q;exports.MathEditorService=re;exports.MatrixOps=z;exports.NiceCalculator=ze;exports.NiceGeometry=Xe;exports.NiceGraphPlotter=Se;exports.NiceI18nProvider=me;exports.NiceMathEditor=he;exports.createCalculatorService=Re;exports.createGeometryService=Ne;exports.createGraphService=Ce;exports.createMathEditorService=ye;exports.getSymbolsByCategory=ee;exports.recognizeHandwriting=oe;exports.useCalculator=I;exports.useGeometry=F;exports.useGraph=L;exports.useMathEditor=X;exports.useNiceTranslation=$;