import React, { useEffect, useState, useRef } from "react";
import { Content, MessageLineContainer, Prefix, Suffix } from "./styled";

interface MessageLineProps {
  text: string;
}

export const MessageLine = (props: MessageLineProps) => {
  const { text } = props;
  const [showPreSuffix, setShowPreSuffix] = useState(true);
  const containerRef = useRef<HTMLDivElement | null>(null);
  const contentRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    let observer: ResizeObserver | undefined;
    if (containerRef.current && contentRef.current) {
      observer = new ResizeObserver(() => {
        if (!containerRef.current) return;
        const { width: containerWidth } = containerRef.current!.getBoundingClientRect();
        const { width: contentWidth } = contentRef.current!.getBoundingClientRect();

        setShowPreSuffix(containerWidth - contentWidth > 28);
      });

      observer.observe(containerRef.current);
    }

    return () => {
      observer?.disconnect?.();
    };
  }, []);

  return (
    <MessageLineContainer
      ref={containerRef}
      style={{ justifyContent: showPreSuffix ? "space-between" : "center" }}
    >
      <Prefix style={{ display: showPreSuffix ? "block" : "none" }} />
      <Content ref={contentRef}>{text}</Content>
      <Suffix style={{ display: showPreSuffix ? "block" : "none" }} />
    </MessageLineContainer>
  );
};
