import { useEffect, useRef } from "react";
import { clsn } from "~utils";

import styles from "./article.module.less";

interface ArticleProps {
  className?: string;
  value: string | number;
  onChange: (value: string) => void;
}

function Article({ className, value, onChange }: ArticleProps) {
  const articleRef = useRef<HTMLElement>(null);

  useEffect(() => {
    if (!articleRef.current) {
      return;
    }

    if (articleRef.current.innerHTML !== String(value)) {
      articleRef.current.innerHTML = String(value);
    }
  }, [value]);

  return (
    <article
      ref={articleRef}
      className={clsn(styles.article, className)}
      contentEditable
      onInput={(ev) => onChange(articleRef.current.innerHTML)}
    />
  );
}

export default Article;
