/* global React */
const { useEffect, useRef, useState } = React;

function Avatar({ state = "idle", mood = "neutral", speakingAmp = 0 }) {
  const [blink, setBlink] = useState(false);
  const [bob, setBob] = useState(0);
  const [look, setLook] = useState({ x: 0, y: 0 });
  const rafRef = useRef();

  useEffect(() => {
    let cancelled = false;
    const loop = () => {
      if (cancelled) return;
      const delay = 2400 + Math.random() * 3500;
      setTimeout(() => {
        if (cancelled) return;
        setBlink(true);
        setTimeout(() => {
          if (cancelled) return;
          setBlink(false);
          loop();
        }, 130);
      }, delay);
    };
    loop();
    return () => { cancelled = true; };
  }, []);

  useEffect(() => {
    let t0 = performance.now();
    const tick = (t) => {
      const dt = (t - t0) / 1000;
      const breathe = Math.sin(dt * 1.2) * 0.5;
      const speak = state === "speaking" ? Math.sin(dt * 4.5) * 0.8 : 0;
      setBob(breathe + speak);
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafRef.current);
  }, [state]);

  useEffect(() => {
    let cancelled = false;
    const loop = () => {
      if (cancelled) return;
      const delay = 1800 + Math.random() * 3200;
      setTimeout(() => {
        if (cancelled) return;
        const x = (Math.random() - 0.5) * 1.6;
        const y = (Math.random() - 0.5) * 0.8;
        setLook({ x, y });
        loop();
      }, delay);
    };
    loop();
    return () => { cancelled = true; };
  }, []);

  const mouthAmp = state === "speaking" ? Math.max(0.1, speakingAmp) : 0;
  const smileCurve = mood === "delighted" ? 4 : mood === "encouraging" ? 3 : 2;
  const browLift = mood === "encouraging" || mood === "thinking" ? -1.2 : 0;
  const browTilt = mood === "thinking" ? -3 : 0;

  const headTransform = `translate(0, ${bob}) rotate(${look.x * 0.4})`;

  const mouthW = 22;
  const openH = 2 + mouthAmp * 10;
  const cornerLift = smileCurve;

  const mouthPath = (() => {
    if (mouthAmp < 0.15) {
      return `M ${-mouthW/2} 0 Q 0 ${cornerLift} ${mouthW/2} 0`;
    }
    const w = mouthW;
    const h = openH;
    return `M ${-w/2} 0
            Q ${-w/2} ${h} 0 ${h}
            Q ${w/2} ${h} ${w/2} 0
            Q 0 ${cornerLift * 0.5} ${-w/2} 0
            Z`;
  })();

  return (
    <svg className="avatar-svg" viewBox="0 0 320 320" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <radialGradient id="bgGrad" cx="50%" cy="40%" r="60%">
          <stop offset="0%" stopColor="#FFF6E8" />
          <stop offset="100%" stopColor="#F0E4D1" />
        </radialGradient>
        <linearGradient id="hairGrad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="#3A2418" />
          <stop offset="100%" stopColor="#2A1A12" />
        </linearGradient>
        <linearGradient id="skinGrad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="#F2C9A2" />
          <stop offset="100%" stopColor="#E3B080" />
        </linearGradient>
        <linearGradient id="sweaterGrad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="#6A8E5F" />
          <stop offset="100%" stopColor="#4F7146" />
        </linearGradient>
        <clipPath id="bgClip">
          <circle cx="160" cy="160" r="156" />
        </clipPath>
      </defs>

      <circle cx="160" cy="160" r="156" fill="url(#bgGrad)" />

      <g opacity="0.4" clipPath="url(#bgClip)">
        <circle cx="50" cy="60" r="3" fill="#E55934" opacity="0.5" />
        <circle cx="270" cy="80" r="2" fill="#6A8E5F" opacity="0.6" />
        <circle cx="40" cy="240" r="2.5" fill="#E8A33D" opacity="0.5" />
        <circle cx="280" cy="220" r="2" fill="#E55934" opacity="0.4" />
      </g>

      <circle cx="160" cy="160" r="154" fill="none" stroke="#1F1A14" strokeWidth="2" opacity="0.08" />

      <g transform={`translate(160, 170) ${headTransform}`}>
        <g transform="translate(0, 95)">
          <path
            d="M -110 60 Q -110 -10 -55 -20 L 55 -20 Q 110 -10 110 60 Z"
            fill="url(#sweaterGrad)"
          />
          <path
            d="M -28 -18 Q 0 -2 28 -18"
            fill="none"
            stroke="#3F5A37"
            strokeWidth="2"
            opacity="0.5"
          />
        </g>

        <rect x="-15" y="55" width="30" height="30" rx="6" fill="url(#skinGrad)" />

        {/* Hair back cap — full crown, no gaps */}
        <path
          d="M -72 -8
             Q -88 -60 -42 -86
             Q 0 -102 42 -86
             Q 88 -60 72 -8
             Q 70 18 68 36
             L 56 48
             Q 60 24 56 4
             Q 50 -8 40 -10
             L -40 -10
             Q -50 -8 -56 4
             Q -60 24 -56 48
             L -68 36
             Q -70 18 -72 -8 Z"
          fill="url(#hairGrad)"
        />

        <ellipse cx="0" cy="0" rx="60" ry="68" fill="url(#skinGrad)" />

        <ellipse cx="-32" cy="22" rx="13" ry="8" fill="#E89A8E" opacity="0.45" />
        <ellipse cx="32" cy="22" rx="13" ry="8" fill="#E89A8E" opacity="0.45" />

        {/* Hair fringe — clean side-swept, no skin gaps */}
        <path
          d="M -60 -28
             Q -74 -68 -16 -80
             Q 30 -80 56 -58
             Q 64 -42 60 -28
             Q 56 -20 46 -22
             Q 30 -40 4 -36
             Q -22 -38 -42 -28
             Q -54 -22 -60 -28 Z"
          fill="url(#hairGrad)"
        />

        <g transform={`translate(0, ${browLift})`}>
          <path
            d={`M -32 -22 q 12 ${-3 + browTilt} 22 0`}
            stroke="#2A1A12"
            strokeWidth="3"
            strokeLinecap="round"
            fill="none"
            transform={`rotate(${-browTilt}, -21, -22)`}
          />
          <path
            d={`M 10 -22 q 12 ${-3 - browTilt} 22 0`}
            stroke="#2A1A12"
            strokeWidth="3"
            strokeLinecap="round"
            fill="none"
            transform={`rotate(${browTilt}, 21, -22)`}
          />
        </g>

        <g transform={`translate(${look.x}, ${look.y})`}>
          <g transform="translate(-20, -8)">
            {blink ? (
              <path d="M -7 0 q 7 3 14 0" stroke="#2A1A12" strokeWidth="2.5" strokeLinecap="round" fill="none" />
            ) : (
              <>
                <ellipse cx="0" cy="0" rx="7" ry="8.5" fill="#FFFFFF" />
                <ellipse cx={look.x * 0.6} cy={look.y * 0.5} rx="4.5" ry="5.5" fill="#2A1A12" />
                <circle cx={look.x * 0.6 - 1.2} cy={look.y * 0.5 - 1.5} r="1.4" fill="#FFFFFF" />
              </>
            )}
          </g>
          <g transform="translate(20, -8)">
            {blink ? (
              <path d="M -7 0 q 7 3 14 0" stroke="#2A1A12" strokeWidth="2.5" strokeLinecap="round" fill="none" />
            ) : (
              <>
                <ellipse cx="0" cy="0" rx="7" ry="8.5" fill="#FFFFFF" />
                <ellipse cx={look.x * 0.6} cy={look.y * 0.5} rx="4.5" ry="5.5" fill="#2A1A12" />
                <circle cx={look.x * 0.6 - 1.2} cy={look.y * 0.5 - 1.5} r="1.4" fill="#FFFFFF" />
              </>
            )}
          </g>
        </g>

        <path d="M -3 8 q 3 5 6 0" stroke="#C99270" strokeWidth="1.5" strokeLinecap="round" fill="none" opacity="0.6" />

        <g transform="translate(0, 28)">
          <path
            d={mouthPath}
            fill={mouthAmp > 0.15 ? "#7A2A2A" : "none"}
            stroke="#2A1A12"
            strokeWidth="2.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
          {mouthAmp > 0.5 && (
            <rect x="-6" y="-1" width="12" height="3.5" rx="1.5" fill="#FFFFFF" opacity="0.9" />
          )}
        </g>

        <circle cx="-58" cy="14" r="2.5" fill="#E8A33D" />
        <circle cx="58" cy="14" r="2.5" fill="#E8A33D" />
      </g>
    </svg>
  );
}

window.Avatar = Avatar;
