import React, { useState, useEffect, useRef } from 'react';
import katex from 'katex';
import 'katex/dist/katex.min.css';

const MathInput: React.FC = () => {
  const [latex, setLatex] = useState<string>('f(x) = \\frac{1}{1+e^{-x}}');
  const displayRef = useRef<HTMLDivElement>(null);
  
  useEffect(() => {
    renderLatex();
  }, [latex]);
//// tow input show and edit
  const renderLatex = () => {
    if (displayRef.current) {
      try {
        katex.render(latex, displayRef.current, {
          throwOnError: false,
          displayMode: true,
        });
      } catch (error) {
        console.error('KaTeX rendering error:', error);
        displayRef.current.textContent = 'Error rendering LaTeX';
      }
    }
  };

  const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setLatex(event.target.value);
  };

  return (
    <div style={{ padding: '20px' }}>
      <input
        type="text"
        value={latex}
        onChange={handleInputChange}
        style={{
          width: '100%',
          padding: '10px',
          fontSize: '16px',
          border: '1px solid #ccc',
          borderRadius: '4px',
          fontFamily: 'monospace',
          marginBottom: '10px',
        }}
      />
      <div
        ref={displayRef}
        style={{
          width: '100%',
          padding: '10px',
          fontSize: '16px',
          border: '1px solid #ccc',
          borderRadius: '4px',
          minHeight: '40px',
        }}
      />
    </div>
  );
};

export default MathInput;
