import { useEffect, useRef, useState, type ReactNode } from 'react' import { useNavigate } from 'react-router' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { matchMutation, myLevelQueryKey } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import { reading } from '@nalssigak/shared/api/client/sdk.gen' import type { ResSaju, ResSajuMatch, SajuCard, SajuLock } from '@nalssigak/shared/api/client/types.gen' import { track } from '../lib/analytics' import { cx } from '../lib/utils' import { useAuth } from './authContext' import { progress, useLevel } from './level' import { useRegion } from './regionContext' import { BIRTH_PLACES, placeLon, useAccountBirth, useBirth, useSaveBirth, validBirth, type Birth } from './sajuBirth' import { useSheet } from './sheetContext' import { Ic, TAP44 } from './ui' const SEEN_KEY = 'nalssigak.b.sajuSeen' const EL_COLOR: Record = { 木: ['#2f8a4c', '#e3f6ea'], 火: ['#d9442f', '#ffe6e0'], 土: ['#a8761a', '#fbf0d6'], 金: ['#6b7486', '#eef0f4'], 水: ['#2d4a8a', '#e3ebfb'] } const CARD_ICON: Record = { when: 'alarm_clock', do: 'check_mark_button', avoid: 'warning', good: 'sparkles', wear: 'tshirt' } const POS_WORD: Record = { hour: '시', day: '일', month: '월', year: '연' } const EL_WORD: Record = { 木: '나무', 火: '불', 土: '흙', 金: '쇠', 水: '물' } const EL_ART: Record = { 木: 'wood', 火: 'fire', 土: 'earth', 金: 'metal', 水: 'water' } const STRENGTH_WORD: Record = { 신강: '나를 돕는 기운이 센 사주. 태어난 달(월령)의 힘을 먼저 봐요', 중화: '나를 돕는 기운과 다른 기운이 비슷한 사주', 신약: '나를 돕는 기운이 약한 사주', } const TEN_GOD_WORD: Record = { 비견: '나와 같은 기운', 겁재: '나와 같지만 겨루는 기운', 식신: '내가 만들어 내는 기운', 상관: '내가 드러내는 기운', 편재: '내가 크게 굴리는 재물', 정재: '내가 차곡차곡 모으는 재물', 편관: '나를 세게 다잡는 기운', 정관: '나를 바르게 이끄는 기운', 편인: '나를 돕는 남다른 지혜', 정인: '나를 돕는 배움·도움', } const HOURS = Array.from({ length: 24 }, (_, i) => i) const MINUTES = Array.from({ length: 60 }, (_, i) => i) const dayWord = (iso: string, weekday: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}(${weekday})` const toBody = (b: Birth) => ({ birth_date: `${b.y}-${String(b.m).padStart(2, '0')}-${String(b.d).padStart(2, '0')}`, birth_time: b.hour != null ? `${String(b.hour).padStart(2, '0')}:${String(b.minute ?? 0).padStart(2, '0')}` : undefined, longitude: placeLon(b.place), }) /** 오늘 아이콘 줄의 빨간 점: 오늘 날씨 사주를 아직 안 봤는지 */ export function sajuSeenToday() { try { return localStorage.getItem(SEEN_KEY) === new Date().toDateString() } catch { // 저장소를 못 쓰면 점을 보이지 않는다 return true } } function markSeen() { try { localStorage.setItem(SEEN_KEY, new Date().toDateString()) } catch (e) { console.warn('[saju] 본 날을 저장하지 못함', e) } } /** 날씨 사주 페이지(/saju): 오늘 점수와 할 일, 내 기운, 레벨로 열리는 이번 주·금전·연애·궁합·이달·올해 */ export function SajuPage() { const navigate = useNavigate() const birth = useBirth() const loading = useAccountBirth() const [editing, setEditing] = useState(false) const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/')) return (

날씨 사주

{loading && !birth ? (

내 생년월일을 불러오는 중이에요…

) : !birth || editing ? ( setEditing(false)} onCancel={birth ? () => setEditing(false) : undefined} /> ) : ( setEditing(true)} /> )}
) } function BirthForm({ initial, onDone, onCancel }: { initial: Birth | null; onDone: () => void; onCancel?: () => void }) { const { loggedIn } = useAuth() const save = useSaveBirth() const [y, setY] = useState(initial ? String(initial.y) : '') const [m, setM] = useState(initial ? String(initial.m) : '') const [d, setD] = useState(initial ? String(initial.d) : '') const [hour, setHour] = useState(initial?.hour != null ? String(initial.hour) : '') const [minute, setMinute] = useState(initial?.minute != null ? String(initial.minute) : '0') const [place, setPlace] = useState(initial?.place ?? 'seoul') const [error, setError] = useState('') const box = 'w-full min-w-0 rounded-2xl border-[1.5px] border-(--line) bg-white px-2 py-3 text-center text-[17px] font-bold' const pick = cx(box, 'cursor-pointer appearance-none bg-[url("data:image/svg+xml,%3Csvg%20xmlns=%27http://www.w3.org/2000/svg%27%20width=%2712%27%20height=%278%27%3E%3Cpath%20d=%27M1%201l5%205%205-5%27%20fill=%27none%27%20stroke=%27%238a93a6%27%20stroke-width=%272%27/%3E%3C/svg%3E")] bg-[length:12px_8px] bg-[position:right_14px_center] bg-no-repeat pr-8') const num = (set: (v: string) => void, max: number) => (e: { target: { value: string } }) => (set(e.target.value.replace(/\D/g, '').slice(0, max)), setError('')) const submit = () => { const [yy, mm, dd] = [Number(y), Number(m), Number(d)] if (!y || !m || !d) return setError('생년월일을 모두 넣어 주세요') if (!validBirth(yy, mm, dd)) return setError('없는 날짜예요. 다시 확인해 주세요') const hh = hour === '' ? null : Number(hour) save({ y: yy, m: mm, d: dd, hour: hh, minute: hh == null ? null : Number(minute), place, gender: initial?.gender ?? null }) track('saju_input', { with_time: hh != null }) onDone() } return (

내 사주와 오늘 날씨로
오늘 하루를 봐요

생년월일 (양력)
태어난 시각 (모르면 '모름')
{error &&

{error}

} {onCancel && ( )}

{loggedIn ? '내 계정에 저장돼요. 내 정보에서 언제든 지울 수 있어요.' : '이 기기에만 저장돼요. 로그인하면 계정에 저장해 어느 기기에서든 바로 볼 수 있어요.'}

) } function Reading({ birth, onEdit }: { birth: Birth; onEdit: () => void }) { const { region } = useRegion() const { loggedIn } = useAuth() const queryClient = useQueryClient() const level = useLevel().data?.level const body = { ...toBody(birth), region_code: region.code, gender: birth.gender === 'M' ? ('male' as const) : birth.gender === 'F' ? ('female' as const) : undefined } // 레벨이 오르면 키가 바뀌어 새로 열린 칸까지 다시 받는다. 사주를 보면 각이 쌓이니 레벨도 새로 받는다 const q = useQuery({ queryKey: ['saju', body, loggedIn, level], staleTime: 10 * 60_000, queryFn: async () => { const { data } = await reading({ body }) if (!data.result?.success) throw new Error(data.result?.desc ?? 'saju') if (loggedIn) queryClient.invalidateQueries({ queryKey: myLevelQueryKey() }) return data }, }) const shot = useRef(null) const { open } = useSheet() const r = q.data useEffect(() => { if (!r?.today || !window.location.hash) return document.getElementById(window.location.hash.slice(1))?.scrollIntoView({ behavior: 'smooth', block: 'start' }) }, [r]) useEffect(() => { if (!r?.today) return markSeen() track('saju_view', { scene: r.me?.scene ?? '', score: r.today.score, strength: r.me?.strength ?? '', top_element: r.me?.top_element ?? '' }) }, [r]) if (q.isPending) return

사주를 풀고 있어요…

if (!r?.today || !r.me) return (

결과를 불러오지 못했어요.

) const t = r.today const lock = (key: string) => r.locks?.find((l) => l.key === key) return (

{Number(t.day.slice(5, 7))}월 {Number(t.day.slice(8, 10))}일 {t.pillar}일 · 오늘의 점수

{t.title}

{t.weather_points != null && ( = 0 ? '#1f7a4f' : '#e8663a'} signed /> )}
{(t.why?.length ?? 0) > 0 && (
    {t.why!.map((w) => (
  • {w}
  • ))}
)}
{t.cards.map((c) => ( ))}
{r.week && } {r.money && ( {[...r.money.map((l) => ['money_bag', l]), ...(r.work ?? []).map((l) => ['briefcase', l])].map(([icon, l]) => (

{l}

))}
)} {r.love && } {lock('saju_match')?.unlocked && } {r.month && } {r.year && } !l.unlocked)} />
재미로 보는 날씨 사주
) } function DecisionCard({ c }: { c: SajuCard }) { return (

{c.kind === 'when' ? '내 기운에 맞는 시간' : c.title}

{c.kind === 'when' ? `${c.title} · ${c.sub}` : c.body}

{c.kind === 'when' ? c.body : c.sub}

) } function ScoreRing({ score }: { score: number }) { const r = 46 const len = 2 * Math.PI * r return (
{score} 오늘의 점수
) } function ScoreBar({ label, value, width, color, signed }: { label: string; value: number; width: number; color: string; signed?: boolean }) { return (

{label} {signed ? (value >= 0 ? '+' : '−') : ''} {Math.abs(value)}점

) } function MeCard({ r, onEdit }: { r: ResSaju; onEdit: () => void }) { const me = r.me! const cols = [...me.pillars].reverse() const els = Object.entries(me.elements ?? {}) const total = els.reduce((a, [, v]) => a + v, 0) const gods = [...new Set(me.pillars.flatMap((p) => [p.stem_ten_god, p.branch_ten_god]).filter((g): g is string => !!g && g in TEN_GOD_WORD))] const strength = me.strength ?? (me.strong == null ? null : me.strong ? '신강' : '신약') return ( 생년월일 바꾸기}> {me.top_element && strength && (

{EL_WORD[me.top_element]}({me.top_element}) 기운이 가장 센 {strength} 사주

나를 돕는 기운 {Math.round((me.support ?? 0) * 100)}% · {me.scene}

)} {total > 0 && ( <>
`${k} ${Math.round(v)}`).join(', ')}> {els.map(([k, v]) => ( ))}
{els.map(([k, v]) => ( {k} {Math.round(v)} ))}
)}
{(me.hour_known ? cols : [null, ...cols]).map((p, i) => (
{p ? `${POS_WORD[p.position]}주` : '시주'} {p ? ( <> {p.position === 'day' ? '나' : p.stem_ten_god} {p.branch_ten_god} {p.position === 'month' && 월령} ) : ( 시각 모름 )}
))}
    {strength && (
  • {strength} = {STRENGTH_WORD[strength]}
  • )} {gods.map((g) => (
  • {g} = {TEN_GOD_WORD[g]}
  • ))}
  • 월령 = 태어난 달의 계절 기운. 명식에서 가장 크게 봐요
{(me.need?.length ?? 0) > 0 &&

내 기운에 좋은 날씨: {me.need!.join(' · ')}

} {me.jeol_warning &&

태어난 날에 절기가 바뀌어요. 태어난 시각을 넣어야 달 기둥이 정확해요.

}
) } function Char({ c, ko, el, me }: { c: string; ko: string; el: string; me?: boolean }) { const [fg, bg] = EL_COLOR[el] ?? ['#28304a', '#f3f6fb'] return ( {c} {ko} ) } function Panel({ id, icon, title, right, children }: { id?: string; icon: string; title: string; right?: ReactNode; children: ReactNode }) { return (

{title}

{right && {right}}
{children}
) } /** 아직 안 열린 것: 다음에 열릴 하나를 크게, 나머지는 한 줄로. 로그인 전이면 로그인부터 */ function Locked({ locks }: { locks: SajuLock[] }) { const { loggedIn } = useAuth() const { open } = useSheet() const level = useLevel().data if (!locks.length) return null const [next, ...rest] = [...locks].sort((a, b) => a.level - b.level) const close = loggedIn && level && level.next_points != null && level.level + 1 === next.level return (

{loggedIn ? `다음은 ${next.name}` : '각을 모으면 더 볼 수 있어요'}

{loggedIn ? (close ? `${level.next_points! - level.points}각 더 모으면 열려요` : `Lv.${next.level}이 되면 열려요`) : "로그인하고 출석·사주 보기·좋아요를 하면 활동 포인트 '각'이 쌓여요"}

{close && ( )}
    {(loggedIn ? rest : [next, ...rest]).map((l) => (
  • Lv.{l.level} {l.name}
  • ))}
) } function Week({ r }: { r: ResSaju }) { return (
    {r.week!.map((d) => (
  1. {dayWord(d.day, d.weekday)} {d.icon && } {d.temp_max != null ? `${d.temp_min}~${d.temp_max}°` : ''} {d.title} {d.score}
  2. ))}

점수는 그날 사주와 예보로 계산해요. 주황색은 7일 중 점수가 가장 높은 날이에요.

) } function Love({ r, birth }: { r: ResSaju; birth: Birth }) { const love = r.love! const save = useSaveBirth() const pick = (g: 'M' | 'F' | null) => save({ ...birth, gender: g }) const chip = 'cursor-pointer rounded-full bg-[#f3f6fb] px-2.5 py-1' return ( {love.good ? (

연애 기운이 좋은 날

{dayWord(love.good.day, love.good.weekday)} {love.good.word ? ` · ${love.good.word} ${love.good.temp_max ?? ''}°` : ''}

{love.good.body}

{love.good.why}

) : (

앞으로 7일 중엔 연애 기운이 두드러지는 날이 없어요.

)} {love.caution && (

조심할 날 {dayWord(love.caution.day, love.caution.weekday)}: {love.caution.body} · {love.caution.why}

)} {love.gender_known ? (

{birth.gender === 'M' ? '남성' : '여성'} 기준으로 이성 인연(재성·관성)까지 봤어요 ·{' '}

) : (
성별을 고르면 이성 인연(재성·관성)까지 봐요
)}
) } function Period({ id, icon, p }: { id: string; icon: string; p: NonNullable }) { return (

{p.title} ({p.ten_god})

{p.body}

{(p.months?.length ?? 0) > 0 &&

{p.label.includes('미리') ? '내 사주와 잘 맞는 달' : '남은 달 중 잘 맞는 달'}: {p.months!.map((m) => `${m}월`).join(' · ')}

} {p.notes?.map((n) => (

{n}

))}
) } function Match({ birth }: { birth: Birth }) { const { region } = useRegion() const [y, setY] = useState('') const [m, setM] = useState('') const [d, setD] = useState('') const [error, setError] = useState('') const run = useMutation({ ...matchMutation() }) const res: ResSajuMatch | undefined = run.data?.result?.success ? run.data : undefined const input = 'w-full min-w-0 rounded-xl border-[1.5px] border-(--line) bg-white px-1 py-2 text-center text-[15px] font-bold' const go = () => { const [yy, mm, dd] = [Number(y), Number(m), Number(d)] if (!y || !m || !d) return setError('상대 생년월일을 모두 넣어 주세요') if (!validBirth(yy, mm, dd)) return setError('없는 날짜예요. 다시 확인해 주세요') setError('') run.mutate({ body: { region_code: region.code, me: toBody(birth), friend: { birth_date: `${yy}-${String(mm).padStart(2, '0')}-${String(dd).padStart(2, '0')}`, longitude: 126.98 } } }) } return ( {res ? ( <>

상대 {y}.{m}.{d}생

{res.title} {res.score}점

{res.lines?.map((l) => (

{l}

))} {res.day && (

앞으로 7일 중 같이 나가기 좋은 날: {dayWord(res.day.day, res.day.weekday)} {res.day.word ? ` · ${res.day.word} ${res.day.temp_max ?? ''}°` : ''}

)}

상대 기운: {res.friend_scene}

) : ( <>

상대 생년월일(양력)을 넣으면 두 사람 사주가 어떻게 맞는지와 앞으로 7일 중 같이 나가기 좋은 날을 봐요.

setY(e.target.value.replace(/\D/g, '').slice(0, 4))} className={input} aria-label="상대 년" /> setM(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 월" /> setD(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 일" />
{error &&

{error}

} {(run.isError || (run.data && !run.data.result?.success)) &&

궁합을 불러오지 못했어요. 다시 눌러 주세요.

}

상대 생년월일은 저장하지 않아요.

)}
) }