'use client';

import { useEffect, useState } from 'react';
import { Volume2 } from 'lucide-react';
import { speak, isTtsSupported } from '@/lib/tts';

/**
 * A round "read aloud" button. Pass `autoPlay` (young age bands) to read once
 * on mount. Renders nothing if the browser has no speech synthesis.
 */
export default function SpeakButton({
  text,
  autoPlay = false,
  className = '',
  size = 'md',
}: {
  text: string;
  autoPlay?: boolean;
  className?: string;
  size?: 'sm' | 'md';
}) {
  const [supported, setSupported] = useState(false);

  useEffect(() => {
    setSupported(isTtsSupported());
  }, []);

  useEffect(() => {
    if (autoPlay && supported && text) {
      const t = setTimeout(() => speak(text), 350);
      return () => clearTimeout(t);
    }
  }, [autoPlay, supported, text]);

  if (!supported) return null;

  const dim = size === 'sm' ? 'h-8 w-8' : 'h-10 w-10';
  const icon = size === 'sm' ? 'h-4 w-4' : 'h-5 w-5';

  return (
    <button
      type="button"
      onClick={() => speak(text)}
      aria-label="পড়ে শোনাও"
      className={`flex ${dim} shrink-0 items-center justify-center rounded-full bg-leaf-100 text-leaf-600 transition active:scale-90 ${className}`}
    >
      <Volume2 className={icon} />
    </button>
  );
}
