// ============================================================
// tree.jsx  —  내면의 나무 (Inner Tree)
// DSI 자아분화 연동 · ACT 기반 마음챙김 · Lv.4 해금
// 3단계: 뿌리(현재순간) → 줄기(가치) → 가지(행동)
// ============================================================

const GT = {
  earth:'#6B4F3A', earthL:'#8B6B50', earthPale:'#F5EFE0',
  root:'#5A3E28', bark:'#7B5F4A', bark2:'#9A7A60',
  leaf:'#3A7A2A', leafL:'#5A9A4A', leafPale:'#E8F5E0',
  sky:'#4A7CC0', skyL:'#7AA8E0', skyPale:'#EAF0FA',
  amber:'#D4954A', amberL:'#E8C47A', amberPale:'#FEF3C7',
  muted:'#8A8A78', dark:'#2C2C20', cream:'#FDFCF7',
};

// ── DSI 점수 → 나무 초기 상태 ─────────────────────────────────
// DSI: 낮을수록 자아분화 낮음 → 나무가 불안정
function calcTreeState(dsiScore) {
  if (!dsiScore || dsiScore < 30)  return 'fragile';   // 흔들리는 나무
  if (dsiScore < 50)               return 'growing';   // 성장 중
  return 'rooted';                                      // 뿌리 단단
}

const TREE_THEME = {
  fragile: { desc:'뿌리가 흔들리고 있어요. 괜찮아요, 지금부터 함께 다져가요.', leafOpacity:0.5, trunkWidth:12 },
  growing: { desc:'나무가 자라는 중이에요. 꾸준히 돌보면 더 단단해져요.',     leafOpacity:0.75, trunkWidth:16 },
  rooted:  { desc:'뿌리가 단단한 나무예요. 자신을 신뢰하고 있군요.',          leafOpacity:1,  trunkWidth:20 },
};

// ── 3단계 질문 (ACT 기반) ─────────────────────────────────────
const STAGES = [
  {
    id: 'roots',
    title: '뿌리 — 현재 순간',
    emoji: '🌱',
    color: GT.earth,
    bg: GT.earthPale,
    desc: '뿌리는 지금 이 순간에 닿아있어요. 지금 여기에 존재하는 나를 느껴보세요.',
    questions: [
      { id:'r1', prompt:'지금 이 순간, 몸에서 느껴지는 감각이 있다면?', placeholder:'따뜻함, 긴장, 호흡...' },
      { id:'r2', prompt:'지금 내 마음속에 있는 감정은?',               placeholder:'불안, 평온, 기대...' },
    ],
  },
  {
    id: 'trunk',
    title: '줄기 — 나의 가치',
    emoji: '🌳',
    color: GT.bark,
    bg: GT.leafPale,
    desc: '줄기는 내가 중요하게 생각하는 것들로 이루어져요. 나에게 진정 소중한 것은 무엇인가요?',
    questions: [
      { id:'t1', prompt:'내가 가장 소중하게 여기는 가치는?',   placeholder:'관계, 성장, 자유, 창의...' },
      { id:'t2', prompt:'미래의 나에게 전하고 싶은 한 마디는?', placeholder:'포기하지 마, 넌 충분해...' },
    ],
  },
  {
    id: 'branches',
    title: '가지 — 나의 행동',
    emoji: '🌿',
    color: GT.leaf,
    bg: '#E8F5E0',
    desc: '가지는 가치를 향한 구체적인 행동이에요. 오늘 내가 할 수 있는 작은 한 걸음은?',
    questions: [
      { id:'b1', prompt:'오늘 내가 실천할 수 있는 작은 행동은?', placeholder:'5분 산책, 물 한 잔...' },
      { id:'b2', prompt:'이번 주 나에게 주고 싶은 선물은?',      placeholder:'충분한 잠, 좋아하는 음식...' },
    ],
  },
];

// ── 나무 SVG ─────────────────────────────────────────────────
function InnerTreeSVG({ stage = 0, answers = {}, treeState = 'growing' }) {
  const theme = TREE_THEME[treeState];
  const tw = theme.trunkWidth;
  const lo = theme.leafOpacity;

  // 뿌리 완성 여부
  const rootsDone   = stage >= 1;
  const trunkDone   = stage >= 2;
  const branchDone  = stage >= 3;

  const answered = Object.values(answers).filter(v => v && v.trim().length > 0).length;

  return (
    <svg viewBox="0 0 320 240" xmlns="http://www.w3.org/2000/svg" style={{ width:'100%', height:'100%' }}>
      <defs>
        <linearGradient id="skyBg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={GT.skyL} stopOpacity="0.6"/>
          <stop offset="100%" stopColor={GT.skyPale} stopOpacity="0.3"/>
        </linearGradient>
        <linearGradient id="groundGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={GT.earth}/>
          <stop offset="100%" stopColor={GT.root}/>
        </linearGradient>
        <filter id="softBlur"><feGaussianBlur stdDeviation="1.5"/></filter>
      </defs>

      {/* 하늘 */}
      <rect width="320" height="240" fill="url(#skyBg)"/>

      {/* 구름 (가지 완성 후 출현) */}
      {branchDone && (
        <g opacity="0.7">
          <ellipse cx="70" cy="40" rx="28" ry="13" fill="white" opacity="0.85"/>
          <ellipse cx="55" cy="45" rx="16" ry="10" fill="white" opacity="0.85"/>
          <ellipse cx="240" cy="30" rx="22" ry="11" fill="white" opacity="0.75"/>
        </g>
      )}

      {/* 지면 */}
      <ellipse cx="160" cy="225" rx="160" ry="25" fill="url(#groundGrad)"/>
      <rect x="0" y="215" width="320" height="25" fill={GT.root}/>

      {/* 뿌리 (rootsDone 이면 표시) */}
      {rootsDone && (
        <g opacity="0.9">
          <path d="M 150 215 Q 130 225 110 218" fill="none" stroke={GT.root} strokeWidth="5" strokeLinecap="round"/>
          <path d="M 155 215 Q 145 230 130 228" fill="none" stroke={GT.root} strokeWidth="4" strokeLinecap="round"/>
          <path d="M 170 215 Q 185 225 200 220" fill="none" stroke={GT.root} strokeWidth="5" strokeLinecap="round"/>
          <path d="M 165 215 Q 175 232 190 230" fill="none" stroke={GT.root} strokeWidth="3" strokeLinecap="round"/>
          {/* 뿌리 빛 (단단한 나무) */}
          {treeState === 'rooted' && (
            <ellipse cx="160" cy="220" rx="30" ry="5" fill={GT.amber} opacity="0.25"/>
          )}
        </g>
      )}

      {/* 나무 몸통 */}
      <rect x={160 - tw/2} y={120} width={tw} height={95} rx={tw/3}
        fill={GT.bark} opacity={rootsDone ? 1 : 0.4}
        style={{ transition:'opacity 0.8s' }}
      />
      {/* 몸통 음영 */}
      <rect x={160 - tw/2 + 3} y={130} width={tw * 0.4} height={80} rx={2}
        fill={GT.bark2} opacity={rootsDone ? 0.5 : 0.2}/>

      {/* 가지 (trunkDone) */}
      {trunkDone && (
        <g>
          <path d="M 160 155 Q 130 140 110 128" fill="none" stroke={GT.bark} strokeWidth="7" strokeLinecap="round"/>
          <path d="M 160 148 Q 188 135 205 125" fill="none" stroke={GT.bark} strokeWidth="7" strokeLinecap="round"/>
          <path d="M 160 140 Q 155 115 155 100" fill="none" stroke={GT.bark} strokeWidth="8" strokeLinecap="round"/>
          {/* 작은 가지 */}
          <path d="M 110 128 Q 95 115 85 108" fill="none" stroke={GT.bark} strokeWidth="4" strokeLinecap="round"/>
          <path d="M 205 125 Q 218 112 225 104" fill="none" stroke={GT.bark} strokeWidth="4" strokeLinecap="round"/>
        </g>
      )}

      {/* 잎 무리 */}
      {[
        { cx:160, cy:100, rx:45, ry:38, show: stage>=1 },
        { cx:105, cy:115, rx:30, ry:25, show: trunkDone },
        { cx:215, cy:112, rx:30, ry:24, show: trunkDone },
        { cx:84,  cy:100, rx:22, ry:18, show: branchDone },
        { cx:228, cy: 98, rx:22, ry:18, show: branchDone },
        { cx:160, cy: 78, rx:28, ry:22, show: branchDone },
      ].map((l, i) => l.show && (
        <ellipse key={i} cx={l.cx} cy={l.cy} rx={l.rx} ry={l.ry}
          fill={GT.leaf} opacity={lo * (0.85 + i * 0.02)}
          style={{ transition:'all 0.8s ease' }}
        />
      ))}

      {/* 꽃 (answers 수에 따라) */}
      {answered >= 2 && (
        <g filter="url(#softBlur)">
          {[{cx:100,cy:112},{cx:220,cy:108},{cx:155,cy:76}].slice(0, Math.floor(answered/2)).map((p,i)=>(
            <g key={i}>
              {[0,60,120,180,240,300].map(a=>(
                <ellipse key={a}
                  cx={p.cx + Math.cos(a*Math.PI/180)*7}
                  cy={p.cy + Math.sin(a*Math.PI/180)*7}
                  rx={5} ry={3.5}
                  fill={['#F9A8D4','#FCD34D','#86EFAC'][i%3]}
                  opacity="0.9"
                  transform={`rotate(${a},${p.cx + Math.cos(a*Math.PI/180)*7},${p.cy + Math.sin(a*Math.PI/180)*7})`}
                />
              ))}
              <circle cx={p.cx} cy={p.cy} r={3.5} fill="#FFF8A0"/>
            </g>
          ))}
        </g>
      )}

      {/* 작은 나비 (완성 후) */}
      {branchDone && answered >= 5 && (
        <g fill="#F9A8D4" opacity="0.8"
          style={{ animation:'float 3s ease-in-out infinite', transformOrigin:'75px 95px' }}>
          <path d="M 75 95 Q 65 88 68 80 Q 75 87 75 95"/>
          <path d="M 75 95 Q 85 88 82 80 Q 75 87 75 95"/>
          <line x1="75" y1="95" x2="75" y2="100" stroke="#8A5A5A" strokeWidth="1"/>
        </g>
      )}
    </svg>
  );
}

// ════════════════════════════════════════════════════════════
// TreeGame — 메인
// ════════════════════════════════════════════════════════════
function TreeGame({ onExit }) {
  const { useState, useEffect, useRef } = React;

  const [stageIdx, setStageIdx]    = useState(0);
  const [answers, setAnswers]      = useState({});
  const [qIdx, setQIdx]            = useState(0);        // 현재 질문 인덱스 (스테이지 내)
  const [confirming, setConfirming]= useState(false);
  const [screen, setScreen]        = useState('intro');  // intro | writing | done
  const [sessionSec, setSessionSec]= useState(0);
  const startRef = useRef(Date.now());
  const treeState = 'growing'; // DSI 점수 미연동 시 기본값

  useEffect(() => {
    if (screen !== 'writing') return;
    const t = setInterval(() => setSessionSec(Math.round((Date.now()-startRef.current)/1000)), 1000);
    return () => clearInterval(t);
  }, [screen]);

  const currentStage = STAGES[stageIdx];
  const currentQ     = currentStage?.questions[qIdx];
  const allAnswered  = currentStage?.questions.every(q => answers[q.id]?.trim().length > 0);

  const handleAnswerChange = (val) => {
    setAnswers(prev => ({ ...prev, [currentQ.id]: val }));
  };

  const handleNextQ = () => {
    if (qIdx < currentStage.questions.length - 1) {
      setQIdx(qIdx + 1);
    } else if (stageIdx < STAGES.length - 1) {
      setStageIdx(stageIdx + 1);
      setQIdx(0);
    } else {
      setScreen('done');
    }
  };

  const handleFinish = async () => {
    const filledCount = Object.values(answers).filter(v => v?.trim().length > 1).length;
    const score = filledCount * 20 + Math.min(sessionSec * 0.3, 30);
    try {
      const res = await GameEngine.saveSession({
        gameId: 'tree', moduleType: 'ACT',
        score: Math.round(score), durationSec: sessionSec,
        metadata: { stages_completed: stageIdx + 1, answers_filled: filledCount, tree_state: treeState },
      });
      onExit?.({
        score: Math.round(score),
        expGained: res.data?.expGained || 0,
        leveledUp: res.data?.leveledUp || false,
        newAchievements: res.data?.newAchievements || [],
      });
    } catch { onExit?.({ score: Math.round(score), expGained:0, leveledUp:false, newAchievements:[] }); }
  };

  // ── 인트로 ─────────────────────────────────────────────
  if (screen === 'intro') return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', background:`linear-gradient(160deg,${GT.earthPale},${GT.cream})` }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'12px 16px', background:'rgba(255,255,255,0.8)', backdropFilter:'blur(8px)', borderBottom:'1px solid rgba(0,0,0,.06)' }}>
        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
          <span style={{ fontSize:20 }}>🌳</span>
          <span style={{ fontSize:15, fontWeight:700, color:GT.dark, fontFamily:"'Noto Serif KR',serif" }}>내면의 나무</span>
        </div>
        <button onClick={()=>onExit(null)} style={{ fontFamily:"'Noto Sans KR',sans-serif", background:'rgba(0,0,0,.06)', color:GT.muted, border:'none', borderRadius:9, padding:'6px 13px', fontSize:12, cursor:'pointer' }}>허브로 →</button>
      </div>

      <div style={{ height:200 }}><InnerTreeSVG stage={0} treeState={treeState}/></div>

      <div style={{ flex:1, padding:'20px', overflowY:'auto' }}>
        <div style={{ background:'rgba(255,255,255,0.8)', borderRadius:18, padding:'18px', marginBottom:20, backdropFilter:'blur(8px)', border:'1px solid rgba(255,255,255,0.6)' }}>
          <h2 style={{ fontSize:18, fontWeight:700, color:GT.dark, marginBottom:8, fontFamily:"'Noto Serif KR',serif" }}>
            내 마음의 나무를 가꾸어요
          </h2>
          <p style={{ fontSize:13, color:GT.muted, lineHeight:1.8 }}>
            {TREE_THEME[treeState].desc}<br/>
            3단계에 걸쳐 뿌리·줄기·가지를 완성하며<br/>
            나만의 나무를 키워보세요.
          </p>
        </div>

        <div style={{ display:'flex', flexDirection:'column', gap:10, marginBottom:24 }}>
          {STAGES.map((s, i) => (
            <div key={s.id} style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 14px', background:'rgba(255,255,255,0.7)', borderRadius:12, border:'1px solid rgba(255,255,255,0.6)' }}>
              <span style={{ fontSize:22 }}>{s.emoji}</span>
              <div><div style={{ fontSize:13, fontWeight:700, color:GT.dark }}>{s.title}</div><div style={{ fontSize:11, color:GT.muted }}>{s.desc.slice(0,30)}...</div></div>
            </div>
          ))}
        </div>

        <button onClick={()=>{ startRef.current=Date.now(); setScreen('writing'); }}
          style={{ fontFamily:"'Noto Sans KR',sans-serif", width:'100%', padding:'14px', background:`linear-gradient(135deg,${GT.leaf},${GT.leafL})`, color:'white', border:'none', borderRadius:14, fontSize:15, fontWeight:700, cursor:'pointer', boxShadow:`0 4px 16px ${GT.leaf}40` }}>
          나무 가꾸기 시작 🌱
        </button>
      </div>
    </div>
  );

  // ── 글쓰기 ─────────────────────────────────────────────
  if (screen === 'writing') return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', background:`linear-gradient(160deg,${GT.earthPale},${GT.cream})` }}>
      {/* 나무 비주얼 */}
      <div style={{ height:200 }}>
        <InnerTreeSVG stage={stageIdx} answers={answers} treeState={treeState}/>
      </div>

      {/* 스테이지 인디케이터 */}
      <div style={{ display:'flex', justifyContent:'center', gap:10, padding:'8px 0' }}>
        {STAGES.map((s, i) => (
          <div key={s.id} style={{ display:'flex', alignItems:'center', gap:4 }}>
            <div style={{ width:8, height:8, borderRadius:'50%', background: i <= stageIdx ? s.color : 'rgba(0,0,0,.12)', transition:'background .4s' }}/>
            {i < STAGES.length-1 && <div style={{ width:16, height:1, background: i < stageIdx ? s.color : 'rgba(0,0,0,.1)' }}/>}
          </div>
        ))}
      </div>

      {/* 현재 스테이지 카드 */}
      <div style={{ flex:1, padding:'0 18px 24px', overflowY:'auto' }}>
        <div style={{ background:`${currentStage.bg}CC`, borderRadius:16, padding:'14px 16px', marginBottom:14, border:`1px solid ${currentStage.color}33` }}>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:6 }}>
            <span style={{ fontSize:20 }}>{currentStage.emoji}</span>
            <span style={{ fontSize:14, fontWeight:700, color:currentStage.color }}>{currentStage.title}</span>
            <span style={{ fontSize:11, color:GT.muted, marginLeft:'auto' }}>{qIdx+1}/{currentStage.questions.length}</span>
          </div>
        </div>

        {/* 현재 질문 */}
        <div style={{ marginBottom:12 }}>
          <div style={{ fontSize:13, fontWeight:600, color:GT.dark, marginBottom:8 }}>{currentQ?.prompt}</div>
          <textarea
            value={answers[currentQ?.id] || ''}
            onChange={e => handleAnswerChange(e.target.value)}
            placeholder={currentQ?.placeholder}
            rows={3}
            autoFocus
            style={{ width:'100%', padding:'11px 13px', border:`1.5px solid ${currentStage.color}44`, borderRadius:11, fontSize:13, fontFamily:"'Noto Sans KR',sans-serif", outline:'none', resize:'none', lineHeight:1.65, background:'rgba(255,255,255,0.9)', color:GT.dark }}
            onFocus={e => e.target.style.borderColor = currentStage.color}
            onBlur={e => e.target.style.borderColor = `${currentStage.color}44`}
          />
        </div>

        {/* 이전 답변 요약 */}
        {Object.keys(answers).length > 0 && (
          <div style={{ marginBottom:14 }}>
            {Object.entries(answers).filter(([k,v])=>v&&v.trim()).map(([k,v],i)=>(
              <div key={k} style={{ fontSize:11, color:GT.muted, padding:'4px 8px', background:'rgba(0,0,0,.04)', borderRadius:7, marginBottom:4, borderLeft:`2px solid ${STAGES[Math.floor(i/2)]?.color||GT.muted}` }}>
                {v}
              </div>
            ))}
          </div>
        )}

        <button
          onClick={handleNextQ}
          disabled={!(answers[currentQ?.id]?.trim().length > 0)}
          style={{ fontFamily:"'Noto Sans KR',sans-serif", width:'100%', padding:'12px', border:'none', borderRadius:12, fontSize:13, fontWeight:700, cursor: answers[currentQ?.id]?.trim().length > 0 ? 'pointer':'not-allowed', background: answers[currentQ?.id]?.trim().length > 0 ? `linear-gradient(135deg,${currentStage.color},${GT.leafL})` : 'rgba(0,0,0,.08)', color: answers[currentQ?.id]?.trim().length > 0 ? 'white' : GT.muted }}>
          {stageIdx === STAGES.length-1 && qIdx === currentStage.questions.length-1 ? '나무 완성하기 🌳' : '다음 →'}
        </button>
      </div>
    </div>
  );

  // ── 완료 화면 ───────────────────────────────────────────
  if (screen === 'done') return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', background:`linear-gradient(160deg,${GT.leafPale},${GT.cream})`, animation:'fadeUp .5s ease' }}>
      <div style={{ height:200 }}><InnerTreeSVG stage={3} answers={answers} treeState={treeState}/></div>
      <div style={{ flex:1, padding:'20px', overflowY:'auto', textAlign:'center' }}>
        <div style={{ fontSize:52, marginBottom:12 }}>🌳</div>
        <h2 style={{ fontSize:22, fontWeight:700, color:GT.dark, marginBottom:8, fontFamily:"'Noto Serif KR',serif" }}>내면의 나무가 완성되었어요</h2>
        <p style={{ fontSize:13, color:GT.muted, lineHeight:1.8, marginBottom:20 }}>뿌리·줄기·가지를 모두 채웠어요.<br/>이 글들이 당신의 마음 지도가 되길 바랍니다.</p>

        <div style={{ display:'flex', flexDirection:'column', gap:10, marginBottom:22, textAlign:'left' }}>
          {STAGES.map(s => (
            <div key={s.id} style={{ background:'white', borderRadius:13, padding:'13px 15px', boxShadow:'0 2px 8px rgba(0,0,0,.06)' }}>
              <div style={{ fontSize:11, fontWeight:700, color:s.color, marginBottom:7 }}>{s.emoji} {s.title}</div>
              {s.questions.map(q => answers[q.id] && (
                <div key={q.id} style={{ fontSize:13, color:GT.dark, lineHeight:1.6, marginBottom:4, paddingLeft:8, borderLeft:`2px solid ${s.color}` }}>
                  {answers[q.id]}
                </div>
              ))}
            </div>
          ))}
        </div>

        <button onClick={handleFinish}
          style={{ fontFamily:"'Noto Sans KR',sans-serif", width:'100%', padding:'14px', background:`linear-gradient(135deg,${GT.leaf},${GT.leafL})`, color:'white', border:'none', borderRadius:14, fontSize:15, fontWeight:700, cursor:'pointer' }}>
          경험치 받기 →
        </button>
      </div>
    </div>
  );

  return null;
}
