import * as React from 'react';

interface PolynomialEquationProps {
  coefficients: number[];
  className?: string;
}

export const PolynomialEquation: React.FC<PolynomialEquationProps> = ({
  coefficients,
  className = '',
}) => {
  const renderTerm = (coeff: number, degree: number, isFirst: boolean) => {
    if (Math.abs(coeff) < 1e-10) return null; // Skip near-zero coefficients

    const absCoeff = Math.abs(coeff);
    const isPositive = coeff >= 0;

    // Determine coefficient display
    let coeffDisplay = '';
    if (degree === 0) {
      // Constant term
      coeffDisplay = absCoeff.toFixed(3);
    } else if (absCoeff === 1) {
      // Coefficient of 1, don't show it
      coeffDisplay = '';
    } else {
      // Regular coefficient
      coeffDisplay = absCoeff.toFixed(3);
    }

    // Determine variable display
    let variableDisplay = null;
    if (degree === 0) {
      // No variable for constant term
      variableDisplay = null;
    } else if (degree === 1) {
      // Linear term: just x
      variableDisplay = <span>x</span>;
    } else {
      // Higher degree: x with superscript
      variableDisplay = (
        <span>
          x<sup>{degree}</sup>
        </span>
      );
    }

    // Determine sign display
    let signDisplay = null;
    if (isFirst) {
      // First term: only show minus if negative
      signDisplay = isPositive ? null : <span>−</span>;
    } else {
      // Subsequent terms: always show sign with spacing
      signDisplay = <span className="mx-1">{isPositive ? '+' : '−'}</span>;
    }

    return (
      <React.Fragment key={degree}>
        {signDisplay}
        {coeffDisplay && <span>{coeffDisplay}</span>}
        {variableDisplay}
      </React.Fragment>
    );
  };

  const terms = [];
  let hasTerms = false;

  // Render terms from highest to lowest degree
  for (let i = coefficients.length - 1; i >= 0; i--) {
    const term = renderTerm(coefficients[i], i, !hasTerms);
    if (term !== null) {
      terms.push(term);
      hasTerms = true;
    }
  }

  if (!hasTerms) {
    return <span className={className}>y = 0</span>;
  }

  return (
    <span className={className}>
      <span>y = </span>
      {terms}
    </span>
  );
};
