import { useState } from 'react';
import { usePersonaStore } from '@/store/personaStore';
import type { CyreneForm, Mood } from '@/types/persona';

interface CyreneAvatarProps {
  size?: 'sm' | 'md' | 'lg';
  className?: string;
}

/**
 * 根据昔涟形态和心情获取对应的头像图片路径。
 *
 * 图片目录结构：
 * - 1st_Form/ (空 — 尚未收集，回退到 2nd_Form)
 * - 2nd_Form/: Cyrene-2F-N-Happy-1.png, Cyrene-2F-N-Tangle-1.png
 * - 3rd_Form/: Cyrene-3F-Q-Happy-1.png, Cyrene-3F-Q-Happy-2.png
 */
function getAvatarPath(form: CyreneForm, _mood: Mood): string {
  const base = '/images/Cyrene_Avatar';

  // de_moi_ge 形态使用 3rd_Form，其余形态（mimi/default）使用 2nd_Form
  // 注意：1st_Form 目录为空，mimi 也回退到 2nd_Form
  if (form === 'de_moi_ge') {
    return `${base}/3rd_Form/Cyrene-3F-Q-Happy-1.png`;
  }

  // mimi / default 形态：happy 用 Happy 图，thoughtful/worried 用 Tangle 图
  if (_mood === 'thoughtful' || _mood === 'worried') {
    return `${base}/2nd_Form/Cyrene-2F-N-Tangle-1.png`;
  }

  return `${base}/2nd_Form/Cyrene-2F-N-Happy-1.png`;
}

/** 图片加载失败时的回退 emoji */
const FORM_FALLBACK_EMOJI: Record<CyreneForm, string> = {
  mimi: '🌸',
  default: '🌺',
  de_moi_ge: '🌌',
};

const SIZE_CLASS = {
  sm: 'w-8 h-8 text-lg',
  md: 'w-12 h-12 text-2xl',
  lg: 'w-20 h-20 text-4xl',
};

const FORM_LABEL: Record<CyreneForm, string> = {
  mimi: '迷迷',
  default: '小昔涟',
  de_moi_ge: '德谬歌',
};

export function CyreneAvatar({ size = 'md', className = '' }: CyreneAvatarProps) {
  const { currentForm, mood } = usePersonaStore();
  const [imgError, setImgError] = useState(false);
  const avatarSrc = getAvatarPath(currentForm, mood);
  const fallbackEmoji = FORM_FALLBACK_EMOJI[currentForm] || '🌸';

  return (
    <div
      className={`${SIZE_CLASS[size]} rounded-full bg-gradient-to-br from-pink-200 to-pink-400 dark:from-pink-800 dark:to-pink-600 flex items-center justify-center shadow-md overflow-hidden ${className}`}
      title={`昔涟 · ${FORM_LABEL[currentForm]}`}
    >
      {imgError ? (
        <span role="img" aria-label="昔涟">
          {fallbackEmoji}
        </span>
      ) : (
        <img
          src={avatarSrc}
          alt={`昔涟 · ${FORM_LABEL[currentForm]}`}
          className="w-full h-full object-cover"
          onError={() => setImgError(true)}
        />
      )}
    </div>
  );
}
