import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';

/**
 * RotatingTips — a subtle, rotating general "did you know" line shown while the
 * agent is running, to make the wait useful. Tips are static, curated, and
 * localized (chat.tips.items). Mount this only when the job is busy; it stops
 * rotating automatically on unmount.
 *
 * Personalized, prompt-specific coaching is a separate feature (the on-demand
 * prompt evaluator in the create dialog) — these tips are general only.
 */
const ROTATE_MS = 7000;
const FADE_MS = 300;

export default function RotatingTips() {
  const { t } = useTranslation('chat');
  const items = t('tips.items', { returnObjects: true }) as unknown;
  const tips = Array.isArray(items) ? (items as string[]) : [];

  // Random start so the same tip isn't always first; guarded for empty list.
  const [idx, setIdx] = useState(() => (tips.length ? Math.floor(Math.random() * tips.length) : 0));
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    if (tips.length <= 1) return;
    const pendingTimeouts = new Set<ReturnType<typeof setTimeout>>();
    const rotate = setInterval(() => {
      setVisible(false);
      const swap = setTimeout(() => {
        setIdx((i) => (i + 1) % tips.length);
        setVisible(true);
        pendingTimeouts.delete(swap);
      }, FADE_MS);
      pendingTimeouts.add(swap);
    }, ROTATE_MS);
    return () => {
      clearInterval(rotate);
      pendingTimeouts.forEach(clearTimeout);
    };
  }, [tips.length]);

  if (tips.length === 0) return null;

  return (
    <div className="flex justify-start" aria-live="polite">
      <div className="inline-flex items-start gap-2 px-2.5 py-1 max-w-[80%] text-2xs text-slate-500 dark:text-slate-400">
        <span className="flex-shrink-0 opacity-70" aria-hidden="true">💡</span>
        <span className="font-medium flex-shrink-0 text-slate-400 dark:text-slate-500">
          {t('tips.label')}
        </span>
        <span
          className={`transition-opacity ease-in-out ${visible ? 'opacity-100' : 'opacity-0'}`}
          style={{ transitionDuration: `${FADE_MS}ms` }}
        >
          {tips[idx]}
        </span>
      </div>
    </div>
  );
}
