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

interface AITutorAvatarProps {
  /** Whether the avatar is currently speaking. Drives the mouth animation. */
  speaking?: boolean;
  /** Optional audio element whose playback drives `speaking` automatically. */
  audio?: HTMLAudioElement | null;
  /** Pixel diameter. Defaults to 96px (good for sidebar). */
  size?: number;
  /** Display name for the tooltip. */
  name?: string;
}

/**
 * Lightweight CSS-only "talking head" avatar. We avoid a 3D engine on
 * purpose — most students open the platform on modest hardware and we
 * already ship a TTS pipeline. The avatar mouth animates while
 * `speaking` is true OR while the bound `audio` element is playing.
 *
 * Idle state: the head bobs gently and blinks every 4s.
 * Speaking state: the mouth opens/closes at ~5Hz with random amplitude.
 */
export default function AITutorAvatar({
  speaking = false,
  audio,
  size = 96,
  name = "AI Tutor",
}: AITutorAvatarProps) {
  const [audioActive, setAudioActive] = useState(false);
  const blinkRef = useRef<NodeJS.Timeout | null>(null);
  const [blink, setBlink] = useState(false);

  useEffect(() => {
    if (!audio) return;
    const onPlay = () => setAudioActive(true);
    const onStop = () => setAudioActive(false);
    audio.addEventListener("play", onPlay);
    audio.addEventListener("playing", onPlay);
    audio.addEventListener("pause", onStop);
    audio.addEventListener("ended", onStop);
    return () => {
      audio.removeEventListener("play", onPlay);
      audio.removeEventListener("playing", onPlay);
      audio.removeEventListener("pause", onStop);
      audio.removeEventListener("ended", onStop);
    };
  }, [audio]);

  useEffect(() => {
    const tick = () => {
      setBlink(true);
      window.setTimeout(() => setBlink(false), 140);
    };
    blinkRef.current = setInterval(tick, 3500 + Math.random() * 1500);
    return () => {
      if (blinkRef.current) clearInterval(blinkRef.current);
    };
  }, []);

  const isSpeaking = speaking || audioActive;

  return (
    <div
      className="ai-tutor-avatar relative inline-flex items-center justify-center"
      style={{ width: size, height: size }}
      aria-label={name}
      title={name}
    >
      <style>{`
        @keyframes ai-bob { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-2px); } }
        @keyframes ai-mouth {
          0%   { transform: scaleY(0.2); }
          50%  { transform: scaleY(1); }
          100% { transform: scaleY(0.4); }
        }
        @keyframes ai-glow {
          0%, 100% { box-shadow: 0 0 0 0 rgba(245, 158, 11, 0.55); }
          50%      { box-shadow: 0 0 20px 6px rgba(245, 158, 11, 0); }
        }
      `}</style>
      <div
        className="rounded-full bg-gradient-to-br from-orange-200 to-amber-100 dark:from-orange-900/30 dark:to-amber-900/20 border border-amber-300/60 flex items-center justify-center"
        style={{
          width: size, height: size,
          animation: `ai-bob 4s ease-in-out infinite${isSpeaking ? ", ai-glow 1.8s ease-out infinite" : ""}`,
        }}
      >
        <svg viewBox="0 0 100 100" width={size * 0.7} height={size * 0.7} aria-hidden="true">
          <ellipse cx="35" cy="42" rx="5" ry={blink ? 0.5 : 5} fill="#1f2937" />
          <ellipse cx="65" cy="42" rx="5" ry={blink ? 0.5 : 5} fill="#1f2937" />
          <circle cx="33" cy="40" r="1.5" fill="#fff" />
          <circle cx="63" cy="40" r="1.5" fill="#fff" />
          <ellipse
            cx="50" cy="64"
            rx="13"
            ry={isSpeaking ? 7 : 2}
            fill="#dc2626"
            style={{
              transformOrigin: "50px 64px",
              animation: isSpeaking ? "ai-mouth 220ms ease-in-out infinite" : "none",
            }}
          />
          <circle cx="22" cy="60" r="3" fill="#fbbf24" opacity="0.5" />
          <circle cx="78" cy="60" r="3" fill="#fbbf24" opacity="0.5" />
        </svg>
      </div>
      {isSpeaking && (
        <span className="absolute -bottom-1 inline-flex items-center gap-0.5 px-2 py-0.5 rounded-full bg-orange-500 text-[10px] font-semibold text-white">
          speaking
        </span>
      )}
    </div>
  );
}
