// 하루결 — 목표 설정 + 칭찬

function GoalsScreen({ navigate }) {
  const s = useStore();
  const [openAdd, setOpenAdd] = React.useState(false);
  const [praise, setPraise] = React.useState(null);

  const goals = s.goals || [];
  const active = goals.filter(g => !g.done);
  const completed = goals.filter(g => g.done).slice(0, 10);

  const toggleGoal = (g) => {
    const next = goals.map(x => x.id === g.id
      ? { ...x, done: !x.done, completedAt: !x.done ? new Date().toISOString() : null }
      : x);
    Store.save(K.goals, next);
    if (!g.done) {
      // 막 완료된 것
      setPraise({ goal: g, msg: getPraise(goals.length + g.id.length) });
    }
  };

  const addGoal = (g) => {
    const next = [...goals, { ...g, id: 'g' + Date.now(), done: false, createdAt: new Date().toISOString() }];
    Store.save(K.goals, next);
    showToast('목표 추가됨');
    setOpenAdd(false);
  };

  const removeGoal = (id) => {
    Store.save(K.goals, goals.filter(g => g.id !== id));
    showToast('삭제됨');
  };

  const periodLabel = (p) => p === 'daily' ? '오늘' : p === 'weekly' ? '이번 주' : '이번 주기';

  const catTone = (cat) => ({
    '몸':   { c: 'var(--hg-clay)',  bg: 'var(--hg-clay-tint)' },
    '식사': { c: 'var(--hg-sage)',  bg: 'var(--hg-sage-tint)' },
    '운동': { c: 'var(--hg-honey)', bg: 'var(--hg-honey-tint)' },
    '마음': { c: 'var(--hg-mist)',  bg: 'var(--hg-mist-tint)' },
    '진료': { c: 'var(--hg-clay-dark)', bg: 'var(--hg-clay-tint)' },
  })[cat] || { c: 'var(--hg-clay)', bg: 'var(--hg-clay-tint)' };

  return (
    <>
      <ScreenHeader
        title="나의 목표"
        sub="작게 시작해도 충분해요"
        back onBack={() => navigate('more')}
        action={<FAB onClick={() => setOpenAdd(true)} />}
      />

      {/* 진행 카드 */}
      <div style={{ padding: '6px 22px 0' }}>
        <Panel style={{
          padding: 18,
          background: 'linear-gradient(135deg, #2A241D 0%, #4A4137 100%)',
          color: '#fff', position: 'relative', overflow: 'hidden', borderColor: 'transparent',
        }}>
          <div style={{ position: 'absolute', right: -30, top: -30, width: 120, height: 120, borderRadius: '50%', background: 'rgba(217,166,108,0.18)' }}/>
          <div style={{ position: 'relative' }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--hg-honey)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>지금까지 완료</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 6, marginBottom: 4 }}>
              <span className="hg-serif" style={{ fontSize: 44, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1 }}>
                {goals.filter(g => g.done).length}
              </span>
              <span style={{ fontSize: 14, opacity: 0.7 }}>개 목표</span>
            </div>
            <div style={{ fontSize: 12, opacity: 0.75, marginTop: 6 }}>작은 한 걸음이 모여 큰 회복이 돼요</div>
          </div>
        </Panel>
      </div>

      {/* 진행 중 목표 */}
      <div style={{ padding: '14px 22px 0' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--hg-ink)' }}>진행 중</div>
          <span style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600 }}>{active.length}개</span>
        </div>
        {active.length === 0 ? (
          <div style={{ padding: 24, textAlign: 'center', color: 'var(--hg-muted)', fontSize: 13, background: 'var(--hg-surface)', borderRadius: 16, border: '1px dashed var(--hg-line)' }}>
            아직 목표가 없어요. 작은 것부터 시작해보세요.
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {active.map((g) => {
              const t = catTone(g.cat);
              return (
                <div key={g.id} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: 14, borderRadius: 16,
                  background: 'var(--hg-surface)',
                  border: '1px solid var(--hg-line-soft)',
                }}>
                  <button onClick={() => toggleGoal(g)} aria-label="완료" style={{
                    width: 32, height: 32, borderRadius: '50%',
                    background: 'transparent',
                    border: `2px solid ${t.c}`,
                    flexShrink: 0,
                  }}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2, flexWrap: 'wrap' }}>
                      <Chip bg={t.bg} color={t.c}>{g.cat}</Chip>
                      <span style={{ fontSize: 10, color: 'var(--hg-muted)', fontWeight: 700 }}>{periodLabel(g.period)}</span>
                    </div>
                    <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--hg-ink)', lineHeight: 1.4 }}>
                      {g.icon} {g.title}
                    </div>
                  </div>
                  <button onClick={() => removeGoal(g.id)} style={{ width: 24, height: 24, color: 'var(--hg-muted)', fontSize: 11 }}>✕</button>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* 완료된 목표 */}
      {completed.length > 0 && (
        <div style={{ padding: '20px 22px 0' }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--hg-muted)', marginBottom: 10 }}>최근 완료한 것</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {completed.map((g) => {
              const t = catTone(g.cat);
              return (
                <div key={g.id} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: 14, borderRadius: 16,
                  background: 'var(--hg-bg-deeper)',
                  border: '1px solid var(--hg-line-soft)',
                  opacity: 0.75,
                }}>
                  <button onClick={() => toggleGoal(g)} aria-label="취소" style={{
                    width: 32, height: 32, borderRadius: '50%',
                    background: t.c, color: '#fff',
                    display: 'grid', placeItems: 'center',
                    flexShrink: 0,
                  }}>
                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                      <path d="M3 8l4 4 6-8" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </button>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--hg-muted)', textDecoration: 'line-through' }}>
                      {g.icon} {g.title}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      <div style={{ height: 30 }}/>

      {openAdd && <AddGoalSheet onClose={() => setOpenAdd(false)} onAdd={addGoal} />}
      {praise && <PraiseModal praise={praise} onClose={() => setPraise(null)} />}
    </>
  );
}

function AddGoalSheet({ onClose, onAdd }) {
  const [tab, setTab] = React.useState('template'); // template | custom
  const [custom, setCustom] = React.useState({ title: '', cat: '몸', period: 'daily', icon: '💧' });

  return (
    <Sheet title="목표 추가" onClose={onClose}>
      <div style={{
        display: 'flex', gap: 6, padding: 4,
        background: 'var(--hg-bg-deeper)',
        borderRadius: 12, marginBottom: 14,
      }}>
        <button onClick={() => setTab('template')} style={{
          flex: 1, padding: '9px 0', borderRadius: 9,
          background: tab === 'template' ? 'var(--hg-surface-2)' : 'transparent',
          color: tab === 'template' ? 'var(--hg-ink)' : 'var(--hg-muted)',
          fontSize: 12, fontWeight: 700,
        }}>추천</button>
        <button onClick={() => setTab('custom')} style={{
          flex: 1, padding: '9px 0', borderRadius: 9,
          background: tab === 'custom' ? 'var(--hg-surface-2)' : 'transparent',
          color: tab === 'custom' ? 'var(--hg-ink)' : 'var(--hg-muted)',
          fontSize: 12, fontWeight: 700,
        }}>직접 입력</button>
      </div>

      {tab === 'template' ? (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {GOAL_TEMPLATES.map((tpl, i) => (
            <button key={i} onClick={() => onAdd(tpl)} style={{
              width: '100%', textAlign: 'left',
              padding: 14, borderRadius: 14,
              background: 'var(--hg-surface)',
              border: '1px solid var(--hg-line-soft)',
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <span style={{ fontSize: 22, lineHeight: 1 }}>{tpl.icon}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--hg-ink)' }}>{tpl.title}</div>
                <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600, marginTop: 2 }}>{tpl.cat} · {tpl.period === 'daily' ? '매일' : tpl.period === 'weekly' ? '주간' : '주기'}</div>
              </div>
              <span style={{ color: 'var(--hg-clay)', fontSize: 18 }}>＋</span>
            </button>
          ))}
        </div>
      ) : (
        <>
          <label className="hg-label">목표</label>
          <input className="hg-input" placeholder="예: 오늘 30분 산책하기" value={custom.title} onChange={(e) => setCustom({ ...custom, title: e.target.value })}/>

          <label className="hg-label" style={{ marginTop: 14 }}>이모지</label>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {['💧','🥚','🚶','🌿','✏️','📅','🌱','🧾','🔬','☕','💪','🍵','📖','🌸','🤍'].map(emoji => (
              <button key={emoji} onClick={() => setCustom({ ...custom, icon: emoji })} style={{
                width: 42, height: 42, borderRadius: 12,
                background: custom.icon === emoji ? 'var(--hg-clay-tint)' : 'var(--hg-bg-deeper)',
                border: '1px solid ' + (custom.icon === emoji ? 'var(--hg-clay)' : 'var(--hg-line-soft)'),
                fontSize: 20,
              }}>{emoji}</button>
            ))}
          </div>

          <label className="hg-label" style={{ marginTop: 14 }}>분류</label>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {['몸','식사','운동','마음','진료'].map(c => (
              <button key={c} onClick={() => setCustom({ ...custom, cat: c })} style={{
                padding: '8px 14px', borderRadius: 999,
                background: custom.cat === c ? 'var(--hg-clay)' : 'var(--hg-bg-deeper)',
                color: custom.cat === c ? '#fff' : 'var(--hg-ink-2)',
                fontSize: 12, fontWeight: 700,
              }}>{c}</button>
            ))}
          </div>

          <label className="hg-label" style={{ marginTop: 14 }}>기간</label>
          <div style={{ display: 'flex', gap: 6 }}>
            {[{ v: 'daily', l: '오늘' }, { v: 'weekly', l: '이번 주' }, { v: 'cycle', l: '이번 주기' }].map(p => (
              <button key={p.v} onClick={() => setCustom({ ...custom, period: p.v })} style={{
                flex: 1, padding: '10px 0', borderRadius: 12,
                background: custom.period === p.v ? 'var(--hg-clay)' : 'var(--hg-bg-deeper)',
                color: custom.period === p.v ? '#fff' : 'var(--hg-ink-2)',
                fontSize: 12, fontWeight: 700,
              }}>{p.l}</button>
            ))}
          </div>

          <div style={{ marginTop: 18 }}>
            <PrimaryButton disabled={!custom.title} onClick={() => onAdd(custom)}>저장</PrimaryButton>
          </div>
        </>
      )}
    </Sheet>
  );
}

// ════════════════════════════════════════════════════════════
// 완료 칭찬 모달
// ════════════════════════════════════════════════════════════
function PraiseModal({ praise, onClose }) {
  React.useEffect(() => {
    const t = setTimeout(() => onClose(), 4500);
    return () => clearTimeout(t);
  }, [onClose]);

  return (
    <div className="hg-overlay" onClick={onClose} style={{
      background: 'rgba(42,36,29,0.6)',
      animation: 'hg-fade 220ms ease',
    }}>
      <div style={{
        width: 'calc(100% - 40px)', maxWidth: 360,
        background: 'var(--hg-surface-2)',
        borderRadius: 28,
        padding: '36px 26px 28px',
        position: 'relative', overflow: 'hidden',
        margin: 'auto',
        animation: 'hg-pop 420ms cubic-bezier(0.34, 1.56, 0.64, 1)',
      }}>
        {/* 풍선 장식 */}
        <Confetti/>

        <div style={{ position: 'relative', textAlign: 'center' }}>
          <div style={{
            width: 72, height: 72, borderRadius: '50%',
            background: 'linear-gradient(135deg, var(--hg-honey), var(--hg-clay))',
            display: 'grid', placeItems: 'center', margin: '0 auto 18px',
            boxShadow: '0 12px 28px rgba(217,166,108,0.4)',
            animation: 'hg-pulse 1.4s ease infinite',
          }}>
            <svg width="38" height="38" viewBox="0 0 38 38" fill="none">
              <path d="M19 5l3.5 8.5L31 14l-6.5 6 1.5 9-7-4.5L12 29l1.5-9L7 14l8.5-.5z" fill="#fff"/>
            </svg>
          </div>

          <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--hg-clay)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 8 }}>
            오늘 하나 완료
          </div>
          <div className="hg-serif" style={{ fontSize: 26, fontWeight: 500, letterSpacing: '-0.02em', lineHeight: 1.3, color: 'var(--hg-ink)', marginBottom: 14 }}>
            {praise.msg.t}!
          </div>
          <div style={{ fontSize: 13, color: 'var(--hg-ink-2)', fontWeight: 500, lineHeight: 1.7, marginBottom: 18 }}>
            {praise.msg.s}
          </div>

          {praise.goal && (
            <div style={{
              padding: '12px 14px', borderRadius: 12,
              background: 'var(--hg-clay-tint)',
              border: '1px solid var(--hg-clay-soft)',
              fontSize: 13, fontWeight: 700, color: 'var(--hg-clay-dark)',
              marginBottom: 20,
            }}>
              {praise.goal.icon} {praise.goal.title}
            </div>
          )}

          <button onClick={onClose} style={{
            width: '100%', minHeight: 50,
            background: 'var(--hg-clay)', color: '#fff',
            fontSize: 14, fontWeight: 700,
            borderRadius: 14,
            boxShadow: '0 6px 16px rgba(181,117,90,0.28)',
          }}>고마워요</button>
        </div>
      </div>

      <style>{`
        @keyframes hg-pop {
          from { opacity: 0; transform: scale(0.85); }
          to { opacity: 1; transform: scale(1); }
        }
        @keyframes hg-pulse {
          0%, 100% { transform: scale(1); }
          50% { transform: scale(1.06); }
        }
        @keyframes hg-confetti {
          0% { transform: translateY(-20px) rotate(0); opacity: 0; }
          15% { opacity: 1; }
          100% { transform: translateY(400px) rotate(720deg); opacity: 0; }
        }
      `}</style>
    </div>
  );
}

function Confetti() {
  const colors = ['var(--hg-clay)', 'var(--hg-honey)', 'var(--hg-sage)', 'var(--hg-mist)', 'var(--hg-rose)'];
  const pieces = Array.from({ length: 14 }, (_, i) => ({
    left: `${(i / 14) * 100}%`,
    delay: `${(i % 5) * 0.15}s`,
    duration: `${2 + (i % 3) * 0.4}s`,
    color: colors[i % colors.length],
    size: 5 + (i % 3) * 3,
  }));

  return (
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden' }}>
      {pieces.map((p, i) => (
        <div key={i} style={{
          position: 'absolute',
          left: p.left, top: -10,
          width: p.size, height: p.size * 1.4, borderRadius: 1,
          background: p.color,
          animation: `hg-confetti ${p.duration} ease ${p.delay} infinite`,
        }}/>
      ))}
    </div>
  );
}

Object.assign(window, { GoalsScreen, AddGoalSheet, PraiseModal });
