import { useEffect, useRef, useState } from "react";
import type { EquationFocusData } from "@gnommo/slide-contracts";
import { ensureMathJax } from "../lib/mathJax";
import type { SlideRuntimeProps } from "../types/lecture";

export default function EquationFocus({
  props,
  latexString,
  displayMode,
  paused
}: SlideRuntimeProps) {
  const data = props as EquationFocusData;
  const header = String(data.header ?? data.eyebrow ?? "Equation focus");
  const title = String(data.title ?? "Definition of the mean");
  const annotation = String(
    data.annotation ??
      "The mean is the total of all observations divided by the number of observations."
  );
  const equationContainerRef = useRef<HTMLDivElement | null>(null);
  const [renderState, setRenderState] = useState<"loading" | "ready" | "error">(
    "loading"
  );

  useEffect(() => {
    const container = equationContainerRef.current;
    const equationSource =
      latexString ?? String.raw`\bar{x} = \frac{1}{N}\sum_{i=0}^{N} x_i`;

    if (!container) {
      return;
    }

    let cancelled = false;
    setRenderState("loading");

    void ensureMathJax()
      .then(async () => {
        if (cancelled || !equationContainerRef.current) {
          return;
        }

        const activeContainer = equationContainerRef.current;
        activeContainer.textContent = `\\[${equationSource}\\]`;
        window.MathJax?.typesetClear?.([activeContainer]);
        await window.MathJax?.typesetPromise?.([activeContainer]);

        if (!cancelled) {
          setRenderState("ready");
        }
      })
      .catch(() => {
        if (!cancelled && equationContainerRef.current) {
          equationContainerRef.current.textContent = equationSource;
          setRenderState("error");
        }
      });

    return () => {
      cancelled = true;
      if (equationContainerRef.current) {
        window.MathJax?.typesetClear?.([equationContainerRef.current]);
      }
    };
  }, [latexString]);

  return (
    <article
      className={`equation-focus equation-focus--${displayMode} ${
        paused ? "equation-focus--paused" : ""
      }`}
    >
      <div className="equation-focus__content">
        <p className="equation-focus__eyebrow">{header}</p>
        <h2 className="equation-focus__title">{title}</h2>
        <div className="equation-focus__equation-frame">
          <div
            ref={equationContainerRef}
            className={`equation-focus__equation equation-focus__equation--mathjax ${
              renderState === "loading" ? "equation-focus__equation--loading" : ""
            } ${renderState === "error" ? "equation-focus__equation--error" : ""}`}
            aria-live="polite"
          />
        </div>
        <p className="equation-focus__annotation">{annotation}</p>
      </div>
    </article>
  );
}
