// character.jsx — Keitta 마스코트 (보라색 털뭉치 클레이 스타일)
// 단순함: 눈 + 다리만, 입체감(그림자 + 하이라이트)
// 다양한 포즈 지원: default, wave, point, sit, peek, think, sleep, jump

const KEITTA_COLORS = {
  body: '#7C5CFC',       // 메인 보라
  bodyDark: '#5B3FD9',   // 그림자
  bodyLight: '#A892FF',  // 하이라이트
  bodyDeep: '#3D2799',   // 깊은 음영
  eye: '#1A0F3D',
  eyeShine: '#FFFFFF',
  leg: '#3D2799',
  blush: 'rgba(255, 120, 180, 0.35)',
};

// 털 텍스처를 표현하는 작은 spike들
function FurSpikes({ count = 24, cx = 60, cy = 60, rx = 48, ry = 44, color }) {
  const spikes = [];
  for (let i = 0; i < count; i++) {
    const angle = (i / count) * Math.PI * 2 - Math.PI / 2;
    const r1 = 1 + (i % 3) * 0.5;
    const r2 = 3 + (i % 4) * 0.8;
    const x1 = cx + Math.cos(angle) * rx;
    const y1 = cy + Math.sin(angle) * ry;
    const x2 = cx + Math.cos(angle) * (rx + r2 + 1);
    const y2 = cy + Math.sin(angle) * (ry + r2 + 1);
    spikes.push(
      <line key={i} x1={x1} y1={y1} x2={x2} y2={y2}
        stroke={color} strokeWidth={r1 * 2 + 1} strokeLinecap="round" />
    );
  }
  return <g>{spikes}</g>;
}

// 마우스 좌표를 따라가는 동공 오프셋 hook
function useEyeFollow(enabled) {
  const ref = React.useRef(null);
  const [off, setOff] = React.useState({ x: 0, y: 0 });
  React.useEffect(() => {
    if (!enabled) return;
    const onMove = (e) => {
      const el = ref.current;
      if (!el) return;
      const r = el.getBoundingClientRect();
      const cx = r.left + r.width / 2;
      const cy = r.top + r.height / 2;
      const dx = e.clientX - cx;
      const dy = e.clientY - cy;
      const d = Math.hypot(dx, dy) || 1;
      // 최대 1.5px (svg 좌표계)
      const max = 1.6;
      const k = Math.min(d, 200) / 200;
      setOff({ x: (dx / d) * max * k, y: (dy / d) * max * k });
    };
    window.addEventListener('mousemove', onMove, { passive: true });
    return () => window.removeEventListener('mousemove', onMove);
  }, [enabled]);
  return [ref, off];
}

// 메인 캐릭터 컴포넌트
function Keitta({ pose = 'default', size = 120, color, style, className, followCursor = false }) {
  const c = { ...KEITTA_COLORS };
  if (color) {
    // primary 색상이 바뀌면 자동으로 파생색 만들기
    c.body = color;
  }
  const [eyeRef, eyeOff] = useEyeFollow(followCursor);

  // 포즈별 변형
  const poses = {
    default: { tilt: 0, eyeY: 0, mouthOpen: false, leftArm: null, rightArm: null, leg: 'stand' },
    wave: { tilt: -3, eyeY: 0, mouthOpen: true, leftArm: null, rightArm: 'wave', leg: 'stand' },
    point: { tilt: 0, eyeY: 0, mouthOpen: false, leftArm: null, rightArm: 'point', leg: 'stand' },
    sit: { tilt: 0, eyeY: 1, mouthOpen: false, leftArm: null, rightArm: null, leg: 'sit' },
    peek: { tilt: -8, eyeY: -1, mouthOpen: false, leftArm: null, rightArm: null, leg: 'stand' },
    think: { tilt: 5, eyeY: -2, mouthOpen: false, leftArm: null, rightArm: 'chin', leg: 'stand' },
    sleep: { tilt: 12, eyeY: 0, mouthOpen: false, leftArm: null, rightArm: null, leg: 'sit', sleeping: true },
    jump: { tilt: 0, eyeY: -1, mouthOpen: true, leftArm: 'up', rightArm: 'up', leg: 'jump' },
    look: { tilt: 0, eyeY: 0, mouthOpen: false, leftArm: null, rightArm: null, leg: 'stand', lookSide: true },
  };
  const p = poses[pose] || poses.default;

  return (
    <svg ref={eyeRef} viewBox="0 0 140 140" width={size} height={size} style={style} className={className}
         xmlns="http://www.w3.org/2000/svg">
      <defs>
        <radialGradient id={`kbody-${pose}`} cx="40%" cy="35%" r="70%">
          <stop offset="0%" stopColor={c.bodyLight}/>
          <stop offset="55%" stopColor={c.body}/>
          <stop offset="100%" stopColor={c.bodyDark}/>
        </radialGradient>
        <radialGradient id={`kshadow-${pose}`} cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="rgba(0,0,0,0.25)"/>
          <stop offset="100%" stopColor="rgba(0,0,0,0)"/>
        </radialGradient>
        <filter id={`ksoft-${pose}`}>
          <feGaussianBlur stdDeviation="0.6"/>
        </filter>
      </defs>

      {/* 바닥 그림자 */}
      <ellipse cx="70" cy={p.leg === 'jump' ? 128 : 122} rx={p.leg === 'jump' ? 22 : 32} ry={p.leg === 'jump' ? 3 : 5}
               fill={`url(#kshadow-${pose})`}/>

      <g transform={`rotate(${p.tilt} 70 70)${p.leg === 'jump' ? ' translate(0 -8)' : ''}`}>
        {/* 다리 */}
        {p.leg === 'stand' && (
          <g>
            <rect x="55" y="105" width="6" height="14" rx="3" fill={c.leg}/>
            <rect x="79" y="105" width="6" height="14" rx="3" fill={c.leg}/>
            <ellipse cx="58" cy="120" rx="6" ry="3" fill={c.leg}/>
            <ellipse cx="82" cy="120" rx="6" ry="3" fill={c.leg}/>
          </g>
        )}
        {p.leg === 'sit' && (
          <g>
            <ellipse cx="58" cy="115" rx="8" ry="4" fill={c.leg}/>
            <ellipse cx="82" cy="115" rx="8" ry="4" fill={c.leg}/>
          </g>
        )}
        {p.leg === 'jump' && (
          <g>
            <rect x="55" y="103" width="6" height="10" rx="3" fill={c.leg} transform="rotate(-15 58 108)"/>
            <rect x="79" y="103" width="6" height="10" rx="3" fill={c.leg} transform="rotate(15 82 108)"/>
            <ellipse cx="55" cy="113" rx="5" ry="2.5" fill={c.leg}/>
            <ellipse cx="85" cy="113" rx="5" ry="2.5" fill={c.leg}/>
          </g>
        )}

        {/* 털 (뒤쪽 레이어) */}
        <FurSpikes count={32} cx={70} cy={65} rx={42} ry={40} color={c.bodyDark}/>

        {/* 몸통 */}
        <ellipse cx="70" cy="65" rx="44" ry="42" fill={`url(#kbody-${pose})`}/>

        {/* 털 (앞쪽 레이어 — 더 짧고 밝게) */}
        <FurSpikes count={20} cx={70} cy={65} rx={42} ry={40} color={c.body}/>

        {/* 하이라이트 (반사광) */}
        <ellipse cx="52" cy="48" rx="14" ry="10" fill={c.bodyLight} opacity="0.5" filter={`url(#ksoft-${pose})`}/>
        <ellipse cx="48" cy="44" rx="6" ry="4" fill="white" opacity="0.35"/>

        {/* 볼터치 */}
        <ellipse cx="46" cy="72" rx="7" ry="4" fill={c.blush}/>
        <ellipse cx="92" cy="72" rx="7" ry="4" fill={c.blush}/>

        {/* 눈 */}
        {!p.sleeping ? (
          <g>
            {/* 왼눈 */}
            <ellipse cx={(p.lookSide ? 58 : 56) + eyeOff.x} cy={62 + p.eyeY + eyeOff.y} rx="5" ry="6.5" fill={c.eye}/>
            <circle cx={(p.lookSide ? 60 : 57.5) + eyeOff.x} cy={60 + p.eyeY + eyeOff.y} r="2" fill={c.eyeShine}/>
            <circle cx={(p.lookSide ? 56.5 : 55) + eyeOff.x} cy={64 + p.eyeY + eyeOff.y} r="0.8" fill={c.eyeShine}/>
            {/* 오른눈 */}
            <ellipse cx={(p.lookSide ? 86 : 84) + eyeOff.x} cy={62 + p.eyeY + eyeOff.y} rx="5" ry="6.5" fill={c.eye}/>
            <circle cx={(p.lookSide ? 88 : 85.5) + eyeOff.x} cy={60 + p.eyeY + eyeOff.y} r="2" fill={c.eyeShine}/>
            <circle cx={(p.lookSide ? 84.5 : 83) + eyeOff.x} cy={64 + p.eyeY + eyeOff.y} r="0.8" fill={c.eyeShine}/>
          </g>
        ) : (
          <g stroke={c.eye} strokeWidth="2" strokeLinecap="round" fill="none">
            <path d="M 51 62 Q 56 66 61 62"/>
            <path d="M 79 62 Q 84 66 89 62"/>
          </g>
        )}

        {/* 입 (작은 점이나 살짝 웃음) */}
        {p.mouthOpen ? (
          <ellipse cx="70" cy="80" rx="4" ry="3" fill={c.eye}/>
        ) : (
          <path d="M 66 78 Q 70 81 74 78" stroke={c.eye} strokeWidth="1.5" fill="none" strokeLinecap="round"/>
        )}

        {/* 팔 (포즈별) */}
        {p.rightArm === 'wave' && (
          <g>
            <ellipse cx="118" cy="40" rx="7" ry="9" fill={c.body} transform="rotate(20 118 40)"/>
            <FurSpikes count={10} cx={118} cy={40} rx={6} ry={8} color={c.body}/>
          </g>
        )}
        {p.rightArm === 'point' && (
          <g transform="rotate(-30 110 60)">
            <rect x="105" y="55" width="14" height="8" rx="4" fill={c.body}/>
            <circle cx="120" cy="59" r="5" fill={c.body}/>
          </g>
        )}
        {p.rightArm === 'chin' && (
          <g>
            <ellipse cx="92" cy="88" rx="6" ry="7" fill={c.body}/>
          </g>
        )}
        {p.rightArm === 'up' && (
          <g>
            <ellipse cx="115" cy="30" rx="7" ry="8" fill={c.body}/>
          </g>
        )}
        {p.leftArm === 'up' && (
          <g>
            <ellipse cx="25" cy="30" rx="7" ry="8" fill={c.body}/>
          </g>
        )}

        {/* 잠잘 때 ZZZ */}
        {p.sleeping && (
          <g fill={c.eye} opacity="0.6" fontFamily="ui-sans-serif" fontWeight="700" fontSize="10">
            <text x="105" y="35">z</text>
            <text x="115" y="25" fontSize="8">z</text>
          </g>
        )}
      </g>
    </svg>
  );
}

// 말풍선 (캐릭터의 가이드 멘트용)
function SpeechBubble({ children, side = 'right', color = '#1A1530', textColor = 'white', style }) {
  const tailLeft = side === 'left';
  return (
    <div style={{
      position: 'relative',
      background: color,
      color: textColor,
      padding: '10px 16px',
      borderRadius: 14,
      fontSize: 13,
      fontWeight: 500,
      lineHeight: 1.45,
      boxShadow: '0 4px 14px rgba(60,40,140,0.12)',
      maxWidth: 240,
      ...style,
    }}>
      {children}
      <svg style={{
        position: 'absolute',
        bottom: -8,
        [tailLeft ? 'left' : 'right']: 18,
        width: 14,
        height: 10,
      }} viewBox="0 0 14 10">
        <path d={tailLeft ? 'M0 0 L14 0 L8 10 Z' : 'M0 0 L14 0 L6 10 Z'} fill={color}/>
      </svg>
    </div>
  );
}

window.Keitta = Keitta;
window.SpeechBubble = SpeechBubble;
window.KEITTA_COLORS = KEITTA_COLORS;
