import { useRef, useEffect, useMemo } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';

interface CharacterProps {
  color: string;
  isCelebrating: boolean;
  delay?: number;
  type: 'flag' | 'cheerer' | 'dancer';
  hairColor?: string;
  skinTone?: string;
  holdsFlag?: boolean;
  index: number;
}

// Smooth easing functions
const easeInOutQuad = (t: number): number => {
  return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
};

const easeOutBounce = (t: number): number => {
  if (t < 1 / 2.75) {
    return 7.5625 * t * t;
  } else if (t < 2 / 2.75) {
    return 7.5625 * (t -= 1.5 / 2.75) * t + 0.75;
  } else if (t < 2.5 / 2.75) {
    return 7.5625 * (t -= 2.25 / 2.75) * t + 0.9375;
  } else {
    return 7.5625 * (t -= 2.625 / 2.75) * t + 0.984375;
  }
};

// Smooth noise function
const noise = (x: number): number => {
  return Math.sin(x) * 0.5 + Math.sin(x * 2.3) * 0.25 + Math.sin(x * 4.7) * 0.125;
};

// Realistic Flag Component with cloth physics simulation
function AnimatedFlag({ flagTexture, isCelebrating, time }: { flagTexture: THREE.Texture; isCelebrating: boolean; time: number }) {
  const flagMeshRef = useRef<THREE.Mesh>(null);
  const flagGeometryRef = useRef<THREE.PlaneGeometry>(null);
  
  // Store original positions for vertex displacement
  const originalPositions = useRef<Float32Array | null>(null);
  
  useEffect(() => {
    if (flagMeshRef.current && flagMeshRef.current.geometry) {
      const geometry = flagMeshRef.current.geometry as THREE.PlaneGeometry;
      flagGeometryRef.current = geometry;
      
      // Store original vertex positions
      const positions = geometry.attributes.position.array as Float32Array;
      originalPositions.current = new Float32Array(positions);
      
      // Increase segmentation for better cloth simulation
      geometry.dispose();
      const newGeometry = new THREE.PlaneGeometry(2.5, 1.25, 32, 16);
      flagMeshRef.current.geometry = newGeometry;
      originalPositions.current = new Float32Array(newGeometry.attributes.position.array);
    }
  }, []);
  
  useFrame((state) => {
    if (!flagMeshRef.current || !originalPositions.current) return;
    
    const geometry = flagMeshRef.current.geometry as THREE.PlaneGeometry;
    const positions = geometry.attributes.position.array as Float32Array;
    const originalPos = originalPositions.current;
    
    const elapsed = state.clock.getElapsedTime();
    const windStrength = isCelebrating ? 1.5 : 0.8;
    const flutterSpeed = isCelebrating ? 8 : 4;
    
    // Update each vertex for cloth-like waving
    for (let i = 0; i < positions.length; i += 3) {
      const x = originalPos[i];
      const y = originalPos[i + 1];
      const z = originalPos[i + 2];
      
      // Distance from flag pole (adjusted for larger flag width of 2.5)
      const distanceFromPole = (x + 1.25) / 2.5;
      
      // Multiple wave layers
      const wave1 = Math.sin(elapsed * flutterSpeed * 0.5 + distanceFromPole * 4) * 0.15 * distanceFromPole * windStrength;
      const wave2 = Math.sin(elapsed * flutterSpeed + distanceFromPole * 8 + y * 3) * 0.08 * distanceFromPole * windStrength;
      const wave3 = Math.sin(elapsed * flutterSpeed * 2 + distanceFromPole * 12 + y * 5) * 0.04 * distanceFromPole * windStrength;
      const turbulence = noise(elapsed * 2 + distanceFromPole * 6) * 0.06 * distanceFromPole * windStrength;
      const verticalFlutter = Math.sin(elapsed * flutterSpeed * 0.7 + distanceFromPole * 3) * 0.05 * (1 - Math.abs(y) / 0.625) * distanceFromPole;
      
      const zOffset = (wave1 + wave2 + wave3 + turbulence) * (0.3 + distanceFromPole * 0.7);
      const yOffset = verticalFlutter * windStrength;
      
      positions[i] = x;
      positions[i + 1] = y + yOffset;
      positions[i + 2] = z + zOffset;
    }
    
    geometry.attributes.position.needsUpdate = true;
    geometry.computeVertexNormals();
    
    flagMeshRef.current.rotation.y = Math.sin(elapsed * 0.5) * 0.1 + 0.1;
    flagMeshRef.current.rotation.z = Math.sin(elapsed * 0.3) * 0.05;
  });
  
  return (
    <mesh ref={flagMeshRef} position={[1.25, 1.8, 0]}>
      <planeGeometry args={[2.5, 1.25, 32, 16]} />
      <meshStandardMaterial 
        map={flagTexture} 
        side={THREE.DoubleSide}
        roughness={0.6}
        metalness={0.1}
      />
    </mesh>
  );
}

function Character({ color, isCelebrating, delay = 0, type, hairColor = '#2D1B0E', skinTone = '#F5DEB3', holdsFlag = false, index }: CharacterProps) {
  const groupRef = useRef<THREE.Group>(null);
  const flagRef = useRef<THREE.Mesh>(null);
  const leftArmRef = useRef<THREE.Group>(null);
  const rightArmRef = useRef<THREE.Group>(null);
  const leftForearmRef = useRef<THREE.Group>(null);
  const rightForearmRef = useRef<THREE.Group>(null);
  const leftHandRef = useRef<THREE.Group>(null);
  const rightHandRef = useRef<THREE.Group>(null);
  const headRef = useRef<THREE.Group>(null);
  const neckRef = useRef<THREE.Group>(null);
  const torsoRef = useRef<THREE.Group>(null);
  const leftLegRef = useRef<THREE.Group>(null);
  const rightLegRef = useRef<THREE.Group>(null);
  const leftKneeRef = useRef<THREE.Group>(null);
  const rightKneeRef = useRef<THREE.Group>(null);
  const leftFootRef = useRef<THREE.Group>(null);
  const rightFootRef = useRef<THREE.Group>(null);
  const hairRef = useRef<THREE.Group>(null);
  const faceRef = useRef<THREE.Group>(null);
  const leftEyeRef = useRef<THREE.Group>(null);
  const rightEyeRef = useRef<THREE.Group>(null);
  const mouthRef = useRef<THREE.Mesh>(null);
  
  const startTimeRef = useRef<number | null>(null);
  const blinkStateRef = useRef({ isBlinking: false, blinkStart: 0, nextBlink: Math.random() * 3000 + 2000 });
  const clapRef = useRef({ isClapping: false, clapCount: 0, lastClap: 0 });

  // Create flag texture
  const flagTexture = useMemo(() => {
    const canvas = document.createElement('canvas');
    canvas.width = 512;
    canvas.height = 256;
    const ctx = canvas.getContext('2d')!;
    
    const gradient = ctx.createLinearGradient(0, 0, 512, 0);
    gradient.addColorStop(0, '#2E90FA');
    gradient.addColorStop(1, '#84CAFF');
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, 512, 256);
    
    ctx.fillStyle = '#FFFFFF';
    ctx.font = 'bold 40px Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText('Freshyo for', 256, 100);
    ctx.fillText('mahabubnagar', 256, 160);
    
    ctx.strokeStyle = '#FFFFFF';
    ctx.lineWidth = 4;
    ctx.strokeRect(10, 10, 492, 236);
    
    const texture = new THREE.TextureLoader().load(canvas.toDataURL());
    return texture;
  }, []);

  useEffect(() => {
    if (isCelebrating && startTimeRef.current === null) {
      startTimeRef.current = Date.now() + delay;
    }
  }, [isCelebrating, delay]);

  useFrame((state) => {
    if (!groupRef.current) return;
    
    const time = state.clock.getElapsedTime();
    const currentTime = Date.now();
    
    // Blinking animation
    if (!blinkStateRef.current.isBlinking && currentTime > blinkStateRef.current.nextBlink) {
      blinkStateRef.current.isBlinking = true;
      blinkStateRef.current.blinkStart = currentTime;
      blinkStateRef.current.nextBlink = currentTime + Math.random() * 4000 + 3000;
    }
    
    if (blinkStateRef.current.isBlinking) {
      const blinkProgress = (currentTime - blinkStateRef.current.blinkStart) / 150;
      if (blinkProgress >= 1) {
        blinkStateRef.current.isBlinking = false;
        if (leftEyeRef.current && rightEyeRef.current) {
          leftEyeRef.current.scale.y = 1;
          rightEyeRef.current.scale.y = 1;
        }
      } else {
        const blinkScale = Math.sin(blinkProgress * Math.PI);
        if (leftEyeRef.current && rightEyeRef.current) {
          leftEyeRef.current.scale.y = 1 - blinkScale * 0.8;
          rightEyeRef.current.scale.y = 1 - blinkScale * 0.8;
        }
      }
    }
    
    if (isCelebrating && startTimeRef.current && currentTime > startTimeRef.current) {
      const elapsed = (currentTime - startTimeRef.current) / 1000;
      
      if (type === 'flag') {
        // FLAG BEARER - Joyful marching with flag waving
        const marchSpeed = 1.5;
        const marchX = Math.sin(elapsed * marchSpeed * 0.3) * 1.5;
        const bounce = Math.abs(Math.sin(elapsed * marchSpeed * 2)) * 0.15;
        
        // Happy marching in place with slight side-to-side
        groupRef.current.position.set(marchX, bounce, 0);
        groupRef.current.rotation.y = Math.sin(elapsed * 0.5) * 0.2;
        
        // Joyful arm movements - waving flag energetically
        if (leftArmRef.current && rightArmRef.current) {
          // Left arm waves in celebration
          const waveHeight = Math.sin(elapsed * 3) * 0.4 + 0.6;
          leftArmRef.current.rotation.x = -waveHeight;
          leftArmRef.current.rotation.z = 0.2;
          
          // Right arm holds flag high with pride
          rightArmRef.current.rotation.x = -0.8 + Math.sin(elapsed * 2) * 0.1;
          rightArmRef.current.rotation.z = -0.1;
        }
        
        if (leftForearmRef.current && rightForearmRef.current) {
          leftForearmRef.current.rotation.x = 0.3 + Math.sin(elapsed * 3) * 0.2;
          rightForearmRef.current.rotation.x = 0.1;
        }
        
        // Happy head movement
        if (headRef.current) {
          headRef.current.rotation.y = Math.sin(elapsed * 1.5) * 0.15;
          headRef.current.rotation.x = -0.1;
        }
        
        // Big smile
        if (mouthRef.current) {
          mouthRef.current.scale.set(1.3, 1.3, 1.3);
        }
        
      } else if (type === 'cheerer') {
        // CHEERER - Clapping and cheering with joy
        const cheerSpeed = 2.5;
        const bounce = Math.abs(Math.sin(elapsed * cheerSpeed)) * 0.2;
        const sideSway = Math.sin(elapsed * 0.8) * 0.8;
        
        // Happy bouncing in place
        groupRef.current.position.set(sideSway, bounce, 0);
        groupRef.current.rotation.y = Math.sin(elapsed * 0.6) * 0.3;
        
        // Clapping animation
        const clapCycle = (elapsed * 4) % 1;
        const isClappingPhase = clapCycle < 0.3;
        
        if (leftArmRef.current && rightArmRef.current) {
          if (isClappingPhase) {
            // Arms come together to clap
            const clapProgress = easeInOutQuad(clapCycle / 0.3);
            leftArmRef.current.rotation.x = -0.5 - clapProgress * 0.3;
            leftArmRef.current.rotation.z = 0.8 - clapProgress * 0.6;
            rightArmRef.current.rotation.x = -0.5 - clapProgress * 0.3;
            rightArmRef.current.rotation.z = -0.8 + clapProgress * 0.6;
          } else {
            // Arms spread wide in joy
            const spreadProgress = easeInOutQuad((clapCycle - 0.3) / 0.7);
            leftArmRef.current.rotation.x = -0.8 + spreadProgress * 0.4;
            leftArmRef.current.rotation.z = 0.2 + spreadProgress * 0.6;
            rightArmRef.current.rotation.x = -0.8 + spreadProgress * 0.4;
            rightArmRef.current.rotation.z = -0.2 - spreadProgress * 0.6;
          }
        }
        
        if (leftForearmRef.current && rightForearmRef.current) {
          // Forearms bend during clap
          const forearmBend = isClappingPhase ? 0.8 : 0.2;
          leftForearmRef.current.rotation.x = forearmBend;
          rightForearmRef.current.rotation.x = forearmBend;
        }
        
        // Enthusiastic head bob
        if (headRef.current) {
          headRef.current.rotation.x = Math.sin(elapsed * 3) * 0.15;
          headRef.current.rotation.y = Math.sin(elapsed * 2) * 0.2;
        }
        
        // Excited hair movement
        if (hairRef.current) {
          hairRef.current.rotation.x = Math.sin(elapsed * 4) * 0.1;
        }
        
        // Huge excited smile
        if (mouthRef.current) {
          mouthRef.current.scale.set(1.4, 1.2, 1.4);
        }
        
      } else if (type === 'dancer') {
        // DANCER - Graceful joyful dancing
        const danceSpeed = 2.0;
        const beat = elapsed * danceSpeed;
        
        // Elegant swaying dance
        const swayX = Math.sin(beat) * 1.2;
        const swayZ = Math.cos(beat * 0.7) * 0.5;
        const bounce = Math.abs(Math.sin(beat * 2)) * 0.25;
        
        groupRef.current.position.set(swayX, bounce, swayZ);
        
        // Graceful spinning
        groupRef.current.rotation.y = beat * 0.5 + Math.sin(beat * 0.5) * 0.3;
        groupRef.current.rotation.z = Math.sin(beat) * 0.15;
        
        // Beautiful arm movements - like dancing
        if (leftArmRef.current && rightArmRef.current) {
          const armFlow1 = Math.sin(beat) * 0.5 + 0.3;
          const armFlow2 = Math.cos(beat) * 0.5 + 0.3;
          
          // Elegant flowing arms
          leftArmRef.current.rotation.x = armFlow1;
          rightArmRef.current.rotation.x = armFlow2;
          leftArmRef.current.rotation.z = 0.3 + Math.sin(beat * 1.5) * 0.4;
          rightArmRef.current.rotation.z = -0.3 - Math.cos(beat * 1.5) * 0.4;
        }
        
        if (leftForearmRef.current && rightForearmRef.current) {
          // Graceful forearm waves
          leftForearmRef.current.rotation.x = 0.4 + Math.sin(beat * 2) * 0.3;
          rightForearmRef.current.rotation.x = 0.4 + Math.cos(beat * 2) * 0.3;
        }
        
        // Joyful head movement
        if (headRef.current) {
          headRef.current.rotation.y = Math.sin(beat * 0.8) * 0.25;
          headRef.current.rotation.x = Math.sin(beat * 1.5) * 0.1;
          headRef.current.rotation.z = Math.cos(beat) * 0.1;
        }
        
        // Flowing hair
        if (hairRef.current) {
          hairRef.current.rotation.z = Math.sin(beat * 1.5) * 0.15;
          hairRef.current.rotation.x = Math.cos(beat) * 0.1;
        }
        
        // Happy dancing smile
        if (mouthRef.current) {
          mouthRef.current.scale.set(1.2, 1.1, 1.2);
        }
      }
      
      // Joyful leg movements for all types
      if (leftLegRef.current && rightLegRef.current && leftKneeRef.current && rightKneeRef.current) {
        const legSpeed = type === 'dancer' ? 4 : 3;
        const leg1 = Math.sin(elapsed * legSpeed) * 0.3;
        const leg2 = Math.sin(elapsed * legSpeed + Math.PI) * 0.3;
        
        leftLegRef.current.rotation.x = leg1;
        rightLegRef.current.rotation.x = leg2;
        
        // Happy knee bouncing
        leftKneeRef.current.rotation.x = 0.3 + Math.abs(leg1) * 0.4;
        rightKneeRef.current.rotation.x = 0.3 + Math.abs(leg2) * 0.4;
      }
      
      // Breathing with excitement
      if (torsoRef.current) {
        const excitedBreath = 1 + Math.sin(elapsed * 3) * 0.025;
        torsoRef.current.scale.set(excitedBreath, excitedBreath, excitedBreath);
      }
      
    } else {
      // IDLE - Natural breathing and subtle swaying
      const idleTime = time * 0.8;
      const breathCycle = Math.sin(idleTime) * 0.5 + 0.5;
      
      // Gentle positioning based on character type
      if (type === 'flag') {
        groupRef.current.position.set(0, breathCycle * 0.02, 0);
        groupRef.current.rotation.set(0, Math.sin(idleTime * 0.3) * 0.08, 0);
      } else if (type === 'cheerer') {
        const swayX = -1.5 + Math.sin(idleTime * 0.5) * 0.05;
        groupRef.current.position.set(swayX, breathCycle * 0.02, 0.3 + Math.cos(idleTime * 0.4) * 0.03);
        groupRef.current.rotation.y = Math.sin(idleTime * 0.2) * 0.05;
      } else if (type === 'dancer') {
        const swayX = 1.5 + Math.cos(idleTime * 0.6) * 0.05;
        groupRef.current.position.set(swayX, breathCycle * 0.025, -0.3 + Math.sin(idleTime * 0.5) * 0.03);
        groupRef.current.rotation.y = Math.cos(idleTime * 0.3) * 0.06;
      }
      
      // Relaxed arm positions
      if (leftArmRef.current && rightArmRef.current) {
        leftArmRef.current.rotation.x = Math.sin(idleTime + index) * 0.08;
        rightArmRef.current.rotation.x = Math.sin(idleTime + index + 0.5) * 0.08;
        leftArmRef.current.rotation.z = 0.1 + Math.sin(idleTime * 0.7) * 0.03;
        rightArmRef.current.rotation.z = -0.1 - Math.sin(idleTime * 0.7) * 0.03;
        
        if (leftForearmRef.current && rightForearmRef.current) {
          leftForearmRef.current.rotation.x = 0.2 + Math.sin(idleTime * 0.5) * 0.05;
          rightForearmRef.current.rotation.x = 0.2 + Math.sin(idleTime * 0.5 + 0.3) * 0.05;
        }
      }
      
      // Gentle head movement
      if (headRef.current) {
        headRef.current.rotation.y = Math.sin(idleTime * 0.4 + index) * 0.08;
        headRef.current.rotation.x = Math.sin(idleTime * 0.3) * 0.03;
      }
      
      // Subtle hair movement
      if (hairRef.current) {
        hairRef.current.rotation.x = Math.sin(idleTime * 0.6) * 0.03;
        hairRef.current.rotation.z = Math.cos(idleTime * 0.5) * 0.02;
      }
      
      // Normal breathing
      if (torsoRef.current) {
        const breathScale = 1 + breathCycle * 0.015;
        torsoRef.current.scale.set(breathScale, breathScale, breathScale);
      }
      
      // Neutral expression
      if (mouthRef.current) {
        mouthRef.current.scale.set(1, 1, 1);
      }
    }
    
    // Flag physics
    if (flagRef.current && holdsFlag) {
      const waveIntensity = isCelebrating ? 0.5 : 0.1;
      const baseWave = Math.sin(time * 4) * waveIntensity;
      const movementLag = Math.sin(time * 3 + 0.5) * waveIntensity * 0.5;
      
      flagRef.current.rotation.y = baseWave + movementLag;
      flagRef.current.rotation.z = Math.sin(time * 2.5) * 0.1 + (isCelebrating ? Math.sin(time * 5) * 0.15 : 0);
      
      const velocityX = groupRef.current.position.x - (groupRef.current.userData.lastX || groupRef.current.position.x);
      flagRef.current.rotation.y += velocityX * 0.5;
      groupRef.current.userData.lastX = groupRef.current.position.x;
    }
  });

  return (
    <group ref={groupRef}>
      {/* Shadow */}
      <mesh position={[0, 0.01, 0]} rotation={[-Math.PI / 2, 0, 0]}>
        <circleGeometry args={[0.45, 32]} />
        <meshBasicMaterial color="#000000" transparent opacity={0.2} />
      </mesh>

      {/* HEAD GROUP */}
      <group ref={headRef} position={[0, 1.75, 0]}>
        {/* Neck */}
        <group ref={neckRef} position={[0, -0.35, 0]}>
          <mesh>
            <cylinderGeometry args={[0.09, 0.1, 0.25, 16]} />
            <meshToonMaterial color={skinTone} />
          </mesh>
        </group>
        
        {/* Main head */}
        <mesh scale={[0.95, 1.0, 0.92]}>
          <sphereGeometry args={[0.22, 32, 32]} />
          <meshToonMaterial color={skinTone} />
        </mesh>
        
        {/* Hair */}
        <group ref={hairRef}>
          <mesh position={[0, 0.18, 0]} scale={[1.05, 0.5, 1.0]}>
            <sphereGeometry args={[0.2, 32, 32, 0, Math.PI * 2, 0, Math.PI / 2]} />
            <meshToonMaterial color={hairColor} />
          </mesh>
          
          <mesh position={[0, 0.05, -0.12]} scale={[1.0, 0.8, 0.5]}>
            <sphereGeometry args={[0.18, 24, 24]} />
            <meshToonMaterial color={hairColor} />
          </mesh>
          
          <mesh position={[-0.18, 0.08, 0.08]} rotation={[0, -0.4, -0.15]} scale={[0.6, 0.9, 0.4]}>
            <capsuleGeometry args={[0.08, 0.2, 8, 16]} />
            <meshToonMaterial color={hairColor} />
          </mesh>
          
          <mesh position={[0.18, 0.08, 0.08]} rotation={[0, 0.4, 0.15]} scale={[0.6, 0.9, 0.4]}>
            <capsuleGeometry args={[0.08, 0.2, 8, 16]} />
            <meshToonMaterial color={hairColor} />
          </mesh>
          
          <mesh position={[0, 0.15, 0.15]} rotation={[0.6, 0, 0]} scale={[1.2, 0.3, 0.3]}>
            <capsuleGeometry args={[0.04, 0.12, 6, 12]} />
            <meshToonMaterial color={hairColor} />
          </mesh>
        </group>

        {/* FACE */}
        <group ref={faceRef} position={[0, 0, 0.18]}>
          {/* Eyes */}
          <group position={[0, 0.02, 0]}>
            {/* Left eye */}
            <group ref={leftEyeRef} position={[-0.09, 0, 0]}>
              <mesh scale={[1, 1.15, 0.25]}>
                <sphereGeometry args={[0.055, 16, 16]} />
                <meshBasicMaterial color="white" />
              </mesh>
              <mesh position={[0, 0, 0.04]}>
                <sphereGeometry args={[0.032, 16, 16]} />
                <meshBasicMaterial color="#5D4E37" />
              </mesh>
              <mesh position={[0, 0, 0.055]}>
                <sphereGeometry args={[0.018, 16, 16]} />
                <meshBasicMaterial color="#1a1a1a" />
              </mesh>
              <mesh position={[0.015, 0.015, 0.06]}>
                <sphereGeometry args={[0.008, 8, 8]} />
                <meshBasicMaterial color="white" />
              </mesh>
            </group>

            {/* Right eye */}
            <group ref={rightEyeRef} position={[0.09, 0, 0]}>
              <mesh scale={[1, 1.15, 0.25]}>
                <sphereGeometry args={[0.055, 16, 16]} />
                <meshBasicMaterial color="white" />
              </mesh>
              <mesh position={[0, 0, 0.04]}>
                <sphereGeometry args={[0.032, 16, 16]} />
                <meshBasicMaterial color="#5D4E37" />
              </mesh>
              <mesh position={[0, 0, 0.055]}>
                <sphereGeometry args={[0.018, 16, 16]} />
                <meshBasicMaterial color="#1a1a1a" />
              </mesh>
              <mesh position={[0.015, 0.015, 0.06]}>
                <sphereGeometry args={[0.008, 8, 8]} />
                <meshBasicMaterial color="white" />
              </mesh>
            </group>
          </group>

          {/* Eyebrows */}
          <mesh position={[-0.09, 0.1, 0.02]} rotation={[0, 0, -0.05]}>
            <capsuleGeometry args={[0.012, 0.06, 6, 12]} />
            <meshBasicMaterial color={hairColor} />
          </mesh>
          <mesh position={[0.09, 0.1, 0.02]} rotation={[0, 0, 0.05]}>
            <capsuleGeometry args={[0.012, 0.06, 6, 12]} />
            <meshBasicMaterial color={hairColor} />
          </mesh>

          {/* Nose */}
          <mesh position={[0, -0.04, 0.03]}>
            <sphereGeometry args={[0.018, 8, 8]} />
            <meshToonMaterial color={skinTone} />
          </mesh>

          {/* Mouth */}
          <mesh ref={mouthRef} position={[0, -0.09, 0.02]} rotation={[0, 0, 0]}>
            <torusGeometry args={[0.05, 0.012, 8, 16, Math.PI]} />
            <meshBasicMaterial color="#E57373" />
          </mesh>
          
          {/* Blush marks */}
          <mesh position={[-0.14, -0.06, 0.08]}>
            <sphereGeometry args={[0.025, 8, 8]} />
            <meshBasicMaterial color="#FFB6C1" transparent opacity={0.4} />
          </mesh>
          <mesh position={[0.14, -0.06, 0.08]}>
            <sphereGeometry args={[0.025, 8, 8]} />
            <meshBasicMaterial color="#FFB6C1" transparent opacity={0.4} />
          </mesh>
        </group>

        {/* Ears */}
        <mesh position={[-0.2, -0.02, 0]} rotation={[0, 0, -0.2]}>
          <sphereGeometry args={[0.07, 16, 16]} />
          <meshToonMaterial color={skinTone} />
        </mesh>
        <mesh position={[0.2, -0.02, 0]} rotation={[0, 0, 0.2]}>
          <sphereGeometry args={[0.07, 16, 16]} />
          <meshToonMaterial color={skinTone} />
        </mesh>
      </group>

      {/* TORSO */}
      <group ref={torsoRef} position={[0, 1.0, 0]}>
        <mesh position={[0, 0.15, 0]} scale={[1.1, 1.0, 0.8]}>
          <sphereGeometry args={[0.28, 32, 32]} />
          <meshToonMaterial color={color} />
        </mesh>
        
        <mesh position={[0, -0.15, 0]} scale={[1.0, 0.9, 0.75]}>
          <sphereGeometry args={[0.26, 32, 32]} />
          <meshToonMaterial color="#2d3436" />
        </mesh>
      </group>

      {/* LEGS */}
      {/* Left Leg */}
      <group ref={leftLegRef} position={[-0.14, 0.65, 0]}>
        <mesh position={[0, -0.25, 0]}>
          <capsuleGeometry args={[0.1, 0.5, 8, 16]} />
          <meshToonMaterial color="#2d3436" />
        </mesh>
        
        <group ref={leftKneeRef} position={[0, -0.55, 0]}>
          <mesh>
            <sphereGeometry args={[0.09, 16, 16]} />
            <meshToonMaterial color={skinTone} />
          </mesh>
          
          <mesh position={[0, -0.25, 0]}>
            <capsuleGeometry args={[0.08, 0.5, 8, 16]} />
            <meshToonMaterial color={skinTone} />
          </mesh>
          
          <group ref={leftFootRef} position={[0, -0.55, 0.05]}>
            <mesh>
              <boxGeometry args={[0.14, 0.1, 0.22]} />
              <meshToonMaterial color="#636e72" />
            </mesh>
          </group>
        </group>
      </group>

      {/* Right Leg */}
      <group ref={rightLegRef} position={[0.14, 0.65, 0]}>
        <mesh position={[0, -0.25, 0]}>
          <capsuleGeometry args={[0.1, 0.5, 8, 16]} />
          <meshToonMaterial color="#2d3436" />
        </mesh>
        
        <group ref={rightKneeRef} position={[0, -0.55, 0]}>
          <mesh>
            <sphereGeometry args={[0.09, 16, 16]} />
            <meshToonMaterial color={skinTone} />
          </mesh>
          
          <mesh position={[0, -0.25, 0]}>
            <capsuleGeometry args={[0.08, 0.5, 8, 16]} />
            <meshToonMaterial color={skinTone} />
          </mesh>
          
          <group ref={rightFootRef} position={[0, -0.55, 0.05]}>
            <mesh>
              <boxGeometry args={[0.14, 0.1, 0.22]} />
              <meshToonMaterial color="#636e72" />
            </mesh>
          </group>
        </group>
      </group>

      {/* ARMS */}
      {/* Left Arm */}
      <group ref={leftArmRef} position={[-0.3, 1.15, 0]}>
        <mesh position={[0, -0.18, 0]}>
          <capsuleGeometry args={[0.08, 0.36, 8, 16]} />
          <meshToonMaterial color={color} />
        </mesh>
        
        <group ref={leftForearmRef} position={[0, -0.4, 0]}>
          <mesh>
            <sphereGeometry args={[0.075, 16, 16]} />
            <meshToonMaterial color={skinTone} />
          </mesh>
          
          <mesh position={[0, -0.16, 0]}>
            <capsuleGeometry args={[0.065, 0.32, 8, 16]} />
            <meshToonMaterial color={skinTone} />
          </mesh>
          
          <group ref={leftHandRef} position={[0, -0.38, 0]}>
            <mesh>
              <boxGeometry args={[0.1, 0.12, 0.06]} />
              <meshToonMaterial color={skinTone} />
            </mesh>
            
            <mesh position={[-0.06, 0.02, 0.02]} rotation={[0, 0, -0.5]}>
              <capsuleGeometry args={[0.025, 0.1, 6, 12]} />
              <meshToonMaterial color={skinTone} />
            </mesh>
            
            <mesh position={[0, -0.08, 0.02]}>
              <boxGeometry args={[0.08, 0.08, 0.04]} />
              <meshToonMaterial color={skinTone} />
            </mesh>
          </group>
        </group>
      </group>

      {/* Right Arm */}
      <group ref={rightArmRef} position={[0.3, 1.15, 0]}>
        <mesh position={[0, -0.18, 0]}>
          <capsuleGeometry args={[0.08, 0.36, 8, 16]} />
          <meshToonMaterial color={color} />
        </mesh>
        
        <group ref={rightForearmRef} position={[0, -0.4, 0]}>
          <mesh>
            <sphereGeometry args={[0.075, 16, 16]} />
            <meshToonMaterial color={skinTone} />
          </mesh>
          
          <mesh position={[0, -0.16, 0]}>
            <capsuleGeometry args={[0.065, 0.32, 8, 16]} />
            <meshToonMaterial color={skinTone} />
          </mesh>
          
          <group ref={rightHandRef} position={[0, -0.38, 0]}>
            <mesh>
              <boxGeometry args={[0.1, 0.12, 0.06]} />
              <meshToonMaterial color={skinTone} />
            </mesh>
            
            <mesh position={[0.06, 0.02, 0.02]} rotation={[0, 0, 0.5]}>
              <capsuleGeometry args={[0.025, 0.1, 6, 12]} />
              <meshToonMaterial color={skinTone} />
            </mesh>
            
            <mesh position={[0, -0.08, 0.02]}>
              <boxGeometry args={[0.08, 0.08, 0.04]} />
              <meshToonMaterial color={skinTone} />
            </mesh>
          </group>
        </group>
      </group>

      {/* FLAG - Larger and more prominent */}
      {holdsFlag && (
        <group position={[0.5, 1.5, 0.2]} rotation={[0, 0, -0.15]}>
          <group position={[0, 0, 0]}>
            <mesh>
              <sphereGeometry args={[0.12, 16, 16]} />
              <meshToonMaterial color={skinTone} />
            </mesh>
          </group>
          
          <mesh position={[0, 1.4, 0]}>
            <cylinderGeometry args={[0.022, 0.022, 2.8, 12]} />
            <meshToonMaterial color="#5d4037" />
          </mesh>
          
          <mesh position={[0, 2.8, 0]}>
            <sphereGeometry args={[0.08, 16, 16]} />
            <meshStandardMaterial color="#f1c40f" metalness={0.5} roughness={0.3} />
          </mesh>
          
          <AnimatedFlag flagTexture={flagTexture} isCelebrating={isCelebrating} time={0} />
        </group>
      )}
    </group>
  );
}

interface CharactersProps {
  isCelebrating: boolean;
}

export default function Characters({ isCelebrating }: CharactersProps) {
  return (
    <group>
      {/* Character 1 - Cheerer - Left side */}
      <Character
        color="#53B1FD"
        isCelebrating={isCelebrating}
        delay={200}
        type="cheerer"
        hairColor="#1C1917"
        skinTone="#E8D5C4"
        index={0}
      />
      
      {/* Character 2 - Flag Bearer - Center */}
      <Character
        color="#2E90FA"
        isCelebrating={isCelebrating}
        delay={0}
        type="flag"
        hairColor="#4A3728"
        skinTone="#F5DEB3"
        holdsFlag={true}
        index={1}
      />
      
      {/* Character 3 - Dancer - Right side */}
      <Character
        color="#84CAFF"
        isCelebrating={isCelebrating}
        delay={400}
        type="dancer"
        hairColor="#3D2914"
        skinTone="#F5E6D3"
        index={2}
      />
    </group>
  );
}
