import { useEffect, useRef, useState } from 'react';
import { CoverView, View } from '@tarojs/components';
import { registerFloatingToastListener } from '../lib/floating-toast';

const TOAST_MS = 2600;

export default function FloatingToastHost() {
  const [text, setText] = useState('');
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    return registerFloatingToastListener((message) => {
      if (timerRef.current) clearTimeout(timerRef.current);
      setText(message);
      timerRef.current = setTimeout(() => {
        setText('');
        timerRef.current = null;
      }, TOAST_MS);
    });
  }, []);

  useEffect(() => {
    return () => {
      if (timerRef.current) clearTimeout(timerRef.current);
    };
  }, []);

  if (!text) return null;

  const Box = process.env.TARO_ENV === 'weapp' ? CoverView : View;
  return <Box className="mu-float-toast">{text}</Box>;
}
