import { useEffect, useRef, useState } from 'react';

/*
  this is the content card component, used for building out sections of content consistently throughout the website
  uses bootstrap styling out of the box

  title and description are two optional props that can be passed as normal, as well as children which pulls 
  from the children of this element when called elsewhere

  **possible to-do**: change formatting styling when title and description are NULL, right now the header section just disappear
 */

interface ContentCardProps {
  title?: string; // Optional
  description?: string; // Optional
  fullPage?: boolean; // Optional
  children: React.ReactNode; // This allows passing any content to the body as a child
  className?: string;
  style?: React.CSSProperties; // Optional inline style
}

const ContentCard: React.FC<ContentCardProps> = ({
  title,
  description,
  fullPage,
  children,
  className,
  style,
}) => {
  const divRef = useRef<HTMLDivElement>(null);
  const [isLastElement, setIsLastElement] = useState(false);

  useEffect(() => {
    const checkIfLastElement = () => {
      if (divRef.current && divRef.current.parentElement) {
        setIsLastElement(divRef.current.nextElementSibling === null);
      }
    };

    checkIfLastElement();

    const observer = new MutationObserver(() => {
      checkIfLastElement();
    });

    if (divRef.current?.parentElement) {
      observer.observe(divRef.current.parentElement, { childList: true });
    }

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

  return (
    <div
      ref={divRef}
      className={
        'card border-dark ' +
        (isLastElement ? '' : 'mb-3 ') +
        (fullPage ? 'flex-grow-1 ' : '')
      }
    >
      {(title || description) && (
        <div className='card-header'>
          {title && <h5 className='text-bold lh-lg mb-0'>{title}</h5>}
          {description && (
            <div className='card-subtitle text-muted lh-sm mb-2'>
              {description}
            </div>
          )}
        </div>
      )}
      <div className='card-body'>{children}</div>
    </div>
  );
};

export default ContentCard;
