// character.jsx — v5 · 진짜 사람 형태
//
// 변경:
//   · stick figure ❌ → 알약(pill) 형태 몸 + 어깨/허리 곡선
//   · 작은 손 동그라미 + 작은 발 타원
//   · 큰 둥근 머리 (자연스러운 비율)
//   · 옷깃 힌트 (단순한 V 라인)
//   · 모자/장식 ❌
//
// viewBox 240 × 280  (머리 ~ 발)
//   머리:  cx=120, cy=66, r=44, stroke 7
//   목:    (120,108) → (120,124)
//   몸:    알약 path (어깨~허리 둥글게)
//   팔:    어깨 양옆 → 무릎 쪽 손 (작은 원)
//   다리:  짧은 곡선, 발 (작은 타원)

const INK = '#1f1d1a';

// ─────────────────────────────────────────────────────────────────────────────
// 사이트 색
const SITE_COLORS = {
  talk:     { name: 'TalkCatcher',     value: '#4A90C2', label: 'Calm Blue' },
  boston:   { name: 'SymptomCatcher',  value: '#E8A317', label: 'Marigold' },
  neuro:    { name: 'TrackCatcher',    value: '#F47C3C', label: 'Headspace Orange' },
  modality: { name: 'ModalityCatcher', value: '#6B9B5C', label: 'Sage' },
};

// 4 사이트 분위기 팔레트 — 같은 가구 다른 색조
const SITE_PALETTES = {
  talk: {
    name: 'Calm Blue · Evening',
    wallTop: '#dbe7f1', wallMid: '#bcd2e3', wallBot: '#9bb8d0',
    floor:   '#7e9bb3', floorDark: '#5e7a92',
    wood:    '#6a8194', woodDark: '#4c6173', woodLight: '#9bb1c2',
    fabric:  '#a8bccd', fabricSoft: '#c0d0de', fabricDeep: '#5c7587',
    leaf:    '#688060', leafDark: '#4c6446', leafLight: '#9ab28b',
    rust:    '#8aa1b3', glow: '#dde7f1', cream: '#f4f7fa',
    accent: '#4A90C2',
    // 창밖: 밤 도시
    skyTop: '#2a3a55', skyMid: '#3e5874', skyBot: '#6488a8',
    sun: '#f0e3a8',  // 달
    silhouette: '#1a2438',
    starColor: '#ffffff',
  },
  boston: {
    name: 'Marigold · Morning',
    wallTop: '#fef0d2', wallMid: '#fadfa5', wallBot: '#eecf85',
    floor:   '#dab362', floorDark: '#a8853f',
    wood:    '#c08855', woodDark: '#8e5e30', woodLight: '#deb784',
    fabric:  '#e3c180', fabricSoft: '#ecd29c', fabricDeep: '#a87a3a',
    leaf:    '#7a9a64', leafDark: '#5d7c4a', leafLight: '#a8c188',
    rust:    '#c97144', glow: '#fde8b8', cream: '#fefaf2',
    accent: '#E8A317',
    // 창밖: 아침 햇살 + 산
    skyTop: '#fce6b4', skyMid: '#fbd086', skyBot: '#f5a868',
    sun: '#fbe294',
    silhouette: '#a89464',
    starColor: '#ffffff',
  },
  neuro: {
    name: 'Headspace Orange · Sunset',
    wallTop: '#fde0c8', wallMid: '#fbc196', wallBot: '#f3a06a',
    floor:   '#d8804a', floorDark: '#a0552a',
    wood:    '#b8744a', woodDark: '#7a4828', woodLight: '#d8a880',
    fabric:  '#e8a472', fabricSoft: '#f3be94', fabricDeep: '#a85a30',
    leaf:    '#6a8048', leafDark: '#4a5832', leafLight: '#94a86c',
    rust:    '#c25e2a', glow: '#fbc596', cream: '#fef3e6',
    accent: '#F47C3C',
    // 창밖: 노을
    skyTop: '#ffd1a0', skyMid: '#fa9560', skyBot: '#c45c30',
    sun: '#ffba6a',  // 큰 해
    silhouette: '#7a4028',
    starColor: '#ffffff',
  },
  modality: {
    name: 'Sage · Daytime',
    wallTop: '#e6efe1', wallMid: '#cadbc2', wallBot: '#a7bf9b',
    floor:   '#8aab7c', floorDark: '#6a8d5d',
    wood:    '#a89465', woodDark: '#7a684a', woodLight: '#c7b58e',
    fabric:  '#c0d3b3', fabricSoft: '#d6e2cb', fabricDeep: '#7a9a64',
    leaf:    '#5d7c4a', leafDark: '#3e5230', leafLight: '#a8c188',
    rust:    '#c19a64', glow: '#eaf3dd', cream: '#f6faf2',
    accent: '#6B9B5C',
    // 창밖: 푸른 하늘 + 산
    skyTop: '#c5dde8', skyMid: '#a4c4d6', skyBot: '#88b08c',
    sun: '#fff6c8',
    silhouette: '#5a7048',
    starColor: '#ffffff',
  },
};

// ─────────────────────────────────────────────────────────────────────────────
// 표정 — 새 좌표계 (머리 cx=120, cy=66, r=44)
//   눈 y=66, 눈 cx L=104 R=136, r=4.5~5
//   눈썹 y=50~58
//   입 cx=120, y=82~88
const EXPRESSIONS = {
  adhd: {
    theme: 'Clinical', label: 'ADHD', tone: '활기 있게 따라감',
    eyes: 'open',
    pupilL: { cx: 102, cy: 65, r: 5 },
    pupilR: { cx: 138, cy: 65, r: 5 },
    browL: 'M88,52 L116,49',
    browR: 'M124,49 Q138,46 152,52',
    mouth: 'M110,86 Q120,94 130,86',
  },
  depression: {
    theme: 'Clinical', label: 'Depression', tone: '깊은 따뜻함',
    eyes: 'closed',
    browL: null, browR: null,
    mouth: 'M108,84 Q120,96 132,84',
  },
  anxiety: {
    theme: 'Clinical', label: 'Anxiety', tone: '차분 · 함께 호흡',
    eyes: 'open',
    pupilL: { cx: 105, cy: 68, r: 4.5 },
    pupilR: { cx: 135, cy: 68, r: 4.5 },
    browL: 'M90,56 Q102,53 116,55',
    browR: 'M124,55 Q138,53 150,56',
    mouth: 'M114,88 Q120,91 126,88',
  },
  sleep: {
    theme: 'Clinical', label: 'Sleep', tone: '평온 · 푹 쉬는',
    eyes: 'sleepy',
    browL: null, browR: null,
    mouth: 'M115,88 Q120,91 125,88',
  },
  burnout: {
    theme: 'Clinical', label: 'Burnout', tone: '온전한 이해',
    eyes: 'open',
    pupilL: { cx: 105, cy: 70, r: 4.5 },
    pupilR: { cx: 135, cy: 70, r: 4.5 },
    browL: 'M90,56 L116,51',
    browR: 'M124,51 L150,56',
    mouth: 'M114,89 L126,89',
  },
  ptsd: {
    theme: 'Clinical', label: 'PTSD', tone: '안전 · 함께 있음',
    eyes: 'open',
    pupilL: { cx: 105, cy: 66, r: 5.5 },
    pupilR: { cx: 135, cy: 66, r: 5.5 },
    browL: null, browR: null,
    mouth: 'M112,86 Q120,92 128,86',
  },
  ocd: {
    theme: 'Clinical', label: 'OCD', tone: '판단하지 않음',
    eyes: 'open',
    pupilL: { cx: 105, cy: 67, r: 5 },
    pupilR: { cx: 135, cy: 67, r: 5 },
    browL: 'M90,53 L116,52',
    browR: 'M124,52 L150,53',
    mouth: 'M114,86 Q120,90 126,86',
  },
  bipolar: {
    theme: 'Clinical', label: 'Bipolar', tone: '균형 · 닻',
    eyes: 'open',
    pupilL: { cx: 105, cy: 66, r: 5 },
    pupilR: { cx: 135, cy: 66, r: 5 },
    browL: null, browR: null,
    mouth: 'M115,87 Q120,89 125,87',
  },
  autism: {
    theme: 'Clinical', label: 'Autism', tone: '명료함 · 예측 가능',
    eyes: 'open',
    pupilL: { cx: 105, cy: 66, r: 5 },
    pupilR: { cx: 135, cy: 66, r: 5 },
    browL: null, browR: null,
    mouth: 'M114,88 L126,88',
  },
  learning: {
    theme: 'Performance', label: 'Learning', tone: '호기심 · 같이 발견',
    eyes: 'open',
    pupilL: { cx: 105, cy: 64, r: 5.5 },
    pupilR: { cx: 135, cy: 64, r: 5.5 },
    browL: 'M90,47 Q102,43 116,47',
    browR: 'M124,47 Q138,43 150,47',
    mouth: 'M110,85 Q120,94 130,85',
  },
  performance: {
    theme: 'Performance', label: 'Peak Performance', tone: '집중 · 예리함',
    eyes: 'open',
    pupilL: { cx: 105, cy: 66, r: 5 },
    pupilR: { cx: 135, cy: 66, r: 5 },
    browL: 'M90,54 L116,54',
    browR: 'M124,54 L150,54',
    browWeight: 5.5,
    mouth: 'M111,86 Q120,92 129,86',
  },
};

const EXPRESSION_KEYS = Object.keys(EXPRESSIONS);
const SITE_THEMES = {
  talk:     ['anxiety', 'depression', 'burnout', 'ptsd'],
  boston:   ['adhd', 'autism', 'sleep', 'bipolar'],
  neuro:    ['ocd', 'ptsd', 'anxiety', 'depression'],
  modality: ['learning', 'performance', 'burnout', 'sleep'],
};

// ─────────────────────────────────────────────────────────────────────────────
// 얼굴 파츠
function Eye({ side, exp, eyeDir = 'center' }) {
  const cxBase = side === 'L' ? 104 : 136;
  if (exp.eyes === 'closed') {
    return (
      <path
        d={`M${cxBase - 10},69 Q${cxBase},62 ${cxBase + 10},69`}
        stroke={INK} strokeWidth={4} fill="none" strokeLinecap="round"
      />
    );
  }
  if (exp.eyes === 'sleepy') {
    return (
      <path
        d={`M${cxBase - 9},67 Q${cxBase},71 ${cxBase + 9},67`}
        stroke={INK} strokeWidth={3.5} fill="none" strokeLinecap="round"
      />
    );
  }
  const p = side === 'L' ? exp.pupilL : exp.pupilR;
  if (!p) return null;
  const dx = eyeDir === 'left' ? -2 : eyeDir === 'right' ? 2 : 0;
  return <circle cx={p.cx + dx} cy={p.cy} r={p.r * 1.3} fill={INK} />;
}

function Brow({ side, exp }) {
  const d = side === 'L' ? exp.browL : exp.browR;
  if (!d) return null;
  const w = exp.browWeight || 5.5;
  return <path d={d} stroke={INK} strokeWidth={w} fill="none" strokeLinecap="round" />;
}

function Mouth({ exp }) {
  if (!exp.mouth) return null;
  return <path d={exp.mouth} stroke={INK} strokeWidth={5} fill="none" strokeLinecap="round" />;
}

// 세라피스트 안경 — 클라이언트와 차별화
function TherapistGlasses() {
  return (
    <g>
      <circle cx={104} cy={66} r={12} stroke={INK} strokeWidth={3} fill="none" />
      <circle cx={136} cy={66} r={12} stroke={INK} strokeWidth={3} fill="none" />
      <line x1={116} y1={66} x2={124} y2={66} stroke={INK} strokeWidth={3} strokeLinecap="round" />
    </g>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// 사람 — 알약 몸 + 손/발 + 큰 머리
function Person({
  expression = 'depression',
  lean = 'center',     // 'right' | 'left' | 'center'
  width = 280,
  bodyColor = '#ffffff',
  initial,             // 'T' | 'B' | 'N' | 'M' — 가슴 배지
  initialColor,        // 배지 색 (사이트 액센트)
  role,                // 'therapist' 면 안경
  seated = false,      // true면 무릇 굽힌 다리 + 발 (viewBox 연장)
  style = {},
}) {
  const exp = EXPRESSIONS[expression] || EXPRESSIONS.depression;
  const bodyTilt = 0;
  // 얼굴은 파트너 쪽으로 살짝 (몸은 똑바로 안락)
  const headTilt = lean === 'right' ? -4 : lean === 'left' ? 4 : 0;
  const eyeDir   = lean === 'right' ? 'right' : lean === 'left' ? 'left' : 'center';

  const viewH = seated ? 360 : 280;

  return (
    <svg
      viewBox={`0 0 240 ${viewH}`}
      width={width}
      height={(width * viewH) / 240}
      style={{ display: 'block', overflow: 'visible', ...style }}
      role="img"
      aria-label={`person-${expression}`}
    >
      <g transform={`rotate(${bodyTilt} 120 ${seated ? 320 : 260})`}>
        {/* 앉은 다리 — 무릇 굽힌, 굵은 선 */}
        {seated && (
          <g>
            {/* 좌 다리 — 허벅지 살짝 바깥+아래, 종아리 수직 (90° 굽힘) */}
            <path d="M104,232 L88,278 L88,332"
              stroke={INK} strokeWidth={9} fill="none" strokeLinecap="round" strokeLinejoin="round" />
            <circle cx={88} cy={278} r={4} fill={INK} />
            <ellipse cx={88} cy={342} rx={16} ry={7} stroke={INK} strokeWidth={4} fill="#ffffff" />
            {/* 우 다리 */}
            <path d="M136,232 L152,278 L152,332"
              stroke={INK} strokeWidth={9} fill="none" strokeLinecap="round" strokeLinejoin="round" />
            <circle cx={152} cy={278} r={4} fill={INK} />
            <ellipse cx={152} cy={342} rx={16} ry={7} stroke={INK} strokeWidth={4} fill="#ffffff" />
          </g>
        )}
        {/* 기존 차단 다리 (seated일 때는 임시 숨김) */}
        {!seated && <path d="M106,228 Q102,250 104,268" stroke={INK} strokeWidth={6} fill="none" strokeLinecap="round" />}
        {!seated && <path d="M134,228 Q138,250 136,268" stroke={INK} strokeWidth={6} fill="none" strokeLinecap="round" />}
        {!seated && <ellipse cx={104} cy={272} rx={9} ry={4} stroke={INK} strokeWidth={3.5} fill="#ffffff" />}
        {!seated && <ellipse cx={136} cy={272} rx={9} ry={4} stroke={INK} strokeWidth={3.5} fill="#ffffff" />}

        {/* 몸 — 알약 (어깨~허리 둥글게) */}
        <path
          d="M86,128 Q86,118 98,118 L142,118 Q154,118 154,128 L154,222 Q154,232 144,232 L96,232 Q86,232 86,222 Z"
          stroke={INK} strokeWidth={6} fill={bodyColor} strokeLinejoin="round"
        />
        {/* 옷깃 (단순 V) */}
        <path d="M104,118 L120,128 L136,118"
          stroke={INK} strokeWidth={3} fill="none" strokeLinejoin="round" strokeLinecap="round" />

        {/* 이니셔얼 배지 (트스 아래 가슴) */}
        {initial && (() => {
          const txt = String(initial);
          const isLong = txt.length > 1;
          const w = isLong ? Math.max(34, txt.length * 13) : 26;
          return (
            <g>
              <rect x={120 - w/2} y={145} width={w} height={26} rx={13}
                stroke={INK} strokeWidth={3} fill={initialColor || '#ffffff'} />
              <text
                x={120} y={163}
                fontFamily='"Pretendard","Inter",sans-serif'
                fontSize={isLong ? 12 : 14} fontWeight={800} fill="#ffffff"
                textAnchor="middle" letterSpacing="-0.02em"
              >
                {txt}
              </text>
            </g>
          );
        })()}

        {/* 팔 — 어깨에서 무릎 쪽으로 자연스럽게 */}
        <path d="M90,135 Q78,180 96,222"
          stroke={INK} strokeWidth={6} fill="none" strokeLinecap="round" />
        <path d="M150,135 Q162,180 144,222"
          stroke={INK} strokeWidth={6} fill="none" strokeLinecap="round" />
        {/* 손 — 작은 원 */}
        <circle cx={96}  cy={224} r={6} stroke={INK} strokeWidth={4} fill="#ffffff" />
        <circle cx={144} cy={224} r={6} stroke={INK} strokeWidth={4} fill="#ffffff" />

        {/* 목 */}
        <line x1={120} y1={106} x2={120} y2={122} stroke={INK} strokeWidth={6} strokeLinecap="round" />

        {/* 머리 (살짝 기울임) */}
        <g transform={`rotate(${headTilt} 120 66)`}>
          <circle cx={120} cy={66} r={44} stroke={INK} strokeWidth={7} fill="#ffffff" />
          {/* 미세 음영 — 입체감 */}
          <ellipse cx={120} cy={80} rx={32} ry={4} fill={INK} opacity={0.05} />

          {/* 얼굴 */}
          <Brow side="L" exp={exp} />
          <Brow side="R" exp={exp} />
          {role === 'therapist' && <TherapistGlasses />}
          <Eye side="L" exp={exp} eyeDir={eyeDir} />
          <Eye side="R" exp={exp} eyeDir={eyeDir} />
          <Mouth exp={exp} />
        </g>
      </g>
    </svg>
  );
}

// 호환성 alias
function TCCharacter({ expression, width, eyeDir, style }) {
  const lean = eyeDir === 'left' ? 'left' : eyeDir === 'right' ? 'right' : 'center';
  return <Person expression={expression} lean={lean} width={width} style={style} />;
}

// ─────────────────────────────────────────────────────────────────────────────
// 서있는 사람 — 부엌·트래킹·발표 등 standing 자세
//
// Props:
//   expression, lean, width, bodyColor, initial, initialColor
//   armRaise — 'left' | 'right' | 'both' | null   (한 팔을 위로 들어 가리킴)
//   walking  — true | false                       (다리 비대칭, 걸음)
function PersonStanding({
  expression = 'depression',
  lean = 'center',
  width = 220,
  bodyColor = '#ffffff',
  initial,
  initialColor,
  role,                // 'therapist' 면 안경
  armRaise,
  walking = false,
  style = {},
}) {
  const exp = EXPRESSIONS[expression] || EXPRESSIONS.depression;
  const bodyTilt = lean === 'right' ? 2 : lean === 'left' ? -2 : 0;
  const headTilt = lean === 'right' ? -2 : lean === 'left' ? 2 : 0;
  const eyeDir   = lean === 'right' ? 'right' : lean === 'left' ? 'left' : 'center';

  // 다리 paths — walking 시 비대칭
  const legL = walking ? 'M104,228 Q92,278 88,348' : 'M104,228 Q100,278 96,350';
  const legR = walking ? 'M136,228 Q148,280 156,350' : 'M136,228 Q140,278 144,350';
  const footL = walking ? { cx: 86, cy: 356 } : { cx: 94, cy: 356 };
  const footR = walking ? { cx: 158, cy: 356 } : { cx: 146, cy: 356 };

  // 팔 paths — armRaise 시 위로
  const armL = (armRaise === 'left' || armRaise === 'both')
    ? 'M90,135 Q70,100 64,52'
    : 'M90,135 Q78,180 96,220';
  const armR = (armRaise === 'right' || armRaise === 'both')
    ? 'M150,135 Q170,100 176,52'
    : 'M150,135 Q162,180 144,220';
  const handL = (armRaise === 'left' || armRaise === 'both')
    ? { cx: 62, cy: 48 } : { cx: 96, cy: 222 };
  const handR = (armRaise === 'right' || armRaise === 'both')
    ? { cx: 178, cy: 48 } : { cx: 144, cy: 222 };

  return (
    <svg
      viewBox="0 0 240 380"
      width={width}
      height={(width * 380) / 240}
      style={{ display: 'block', overflow: 'visible', ...style }}
      role="img"
      aria-label={`standing-${expression}`}
    >
      <g transform={`rotate(${bodyTilt} 120 360)`}>
        {/* 그림자 */}
        <ellipse cx={120} cy={368} rx={48} ry={4} fill="rgba(31,29,26,0.12)" />

        {/* 다리 */}
        <path d={legL} stroke={INK} strokeWidth={6} fill="none" strokeLinecap="round" />
        <path d={legR} stroke={INK} strokeWidth={6} fill="none" strokeLinecap="round" />
        <ellipse cx={footL.cx} cy={footL.cy} rx={10} ry={4.5} stroke={INK} strokeWidth={3.5} fill="#ffffff" />
        <ellipse cx={footR.cx} cy={footR.cy} rx={10} ry={4.5} stroke={INK} strokeWidth={3.5} fill="#ffffff" />

        {/* 몸 알약 */}
        <path
          d="M86,128 Q86,118 98,118 L142,118 Q154,118 154,128 L154,222 Q154,232 144,232 L96,232 Q86,232 86,222 Z"
          stroke={INK} strokeWidth={6} fill={bodyColor} strokeLinejoin="round"
        />
        <path d="M104,118 L120,128 L136,118"
          stroke={INK} strokeWidth={3} fill="none" strokeLinejoin="round" strokeLinecap="round" />
        {initial && (
          <g>
            <circle cx={120} cy={158} r={13} stroke={INK} strokeWidth={3} fill={initialColor || '#ffffff'} />
            <text x={120} y={163} fontFamily='"Inter","Pretendard",sans-serif'
              fontSize={14} fontWeight={800} fill="#ffffff"
              textAnchor="middle" letterSpacing="-0.02em">{initial}</text>
          </g>
        )}

        {/* 팔 + 손 */}
        <path d={armL} stroke={INK} strokeWidth={6} fill="none" strokeLinecap="round" />
        <path d={armR} stroke={INK} strokeWidth={6} fill="none" strokeLinecap="round" />
        <circle cx={handL.cx} cy={handL.cy} r={6} stroke={INK} strokeWidth={4} fill="#ffffff" />
        <circle cx={handR.cx} cy={handR.cy} r={6} stroke={INK} strokeWidth={4} fill="#ffffff" />

        {/* 목 */}
        <line x1={120} y1={106} x2={120} y2={122} stroke={INK} strokeWidth={6} strokeLinecap="round" />

        {/* 머리 */}
        <g transform={`rotate(${headTilt} 120 66)`}>
          <circle cx={120} cy={66} r={44} stroke={INK} strokeWidth={7} fill="#ffffff" />
          <ellipse cx={120} cy={80} rx={32} ry={4} fill={INK} opacity={0.05} />
          <Brow side="L" exp={exp} />
          <Brow side="R" exp={exp} />
          {role === 'therapist' && <TherapistGlasses />}
          <Eye side="L" exp={exp} eyeDir={eyeDir} />
          <Eye side="R" exp={exp} eyeDir={eyeDir} />
          <Mouth exp={exp} />
        </g>
      </g>
    </svg>
  );
}

Object.assign(window, {
  Person,
  PersonStanding,
  TCCharacter,
  SITE_COLORS,
  SITE_PALETTES,
  SITE_THEMES,
  EXPRESSIONS,
  EXPRESSION_KEYS,
  INK,
});
