import {
  createRef,
  forwardRef,
  useEffect,
  useImperativeHandle,
  useState,
} from 'react';

type ToastRootRefType = {
  show: (message: string | React.ReactNode) => void;
};

export const toastRootRef = createRef<ToastRootRefType>();

export const toast = (message: string | React.ReactNode) => {
  toastRootRef.current?.show(message);
};

const ToastRoot = forwardRef<ToastRootRefType, {}>((_, ref) => {
  const [message, setMessage] = useState<string | React.ReactNode | null>(null);
  const [visible, setVisible] = useState(false);

  useImperativeHandle(ref, () => ({
    show: (message) => {
      setMessage(message);
      setVisible(true);
    },
  }));

  useEffect(() => {
    if (!visible) return;
    const timer = setTimeout(() => setVisible(false), 3000);
    return () => clearTimeout(timer);
  }, [visible, message]);

  useEffect(() => {
    if (visible) return;
    const t = setTimeout(() => setMessage(null), 250);
    return () => clearTimeout(t);
  }, [visible]);

  if (!message) return null;

  return (
    <div className="fixed left-1/2 -translate-x-1/2 z-[400] pointer-events-none"
      style={{ bottom: 'calc(env(safe-area-inset-bottom) + 24px)' }}
    >
      <div
        className={`pointer-events-auto px-4 py-2.5 rounded-2xl shadow-xl
          bg-black/85 text-white text-[14px] backdrop-blur-sm cursor-pointer
          transition-all duration-200 max-w-[80vw]
          ${visible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-2'}
        `}
        onClick={() => setVisible(false)}
      >
        {message}
      </div>
    </div>
  );
});

ToastRoot.displayName = 'ToastRoot';

export default ToastRoot;
