Files
o2o-weather/frontend/src/b/SajuPage.tsx
T

527 lines
27 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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<string, [string, string]> = { 木: ['#2f8a4c', '#e3f6ea'], 火: ['#d9442f', '#ffe6e0'], 土: ['#a8761a', '#fbf0d6'], 金: ['#6b7486', '#eef0f4'], 水: ['#2d4a8a', '#e3ebfb'] }
const CARD_ICON: Record<string, string> = { when: 'alarm_clock', do: 'check_mark_button', avoid: 'warning', good: 'sparkles', wear: 'tshirt' }
const POS_WORD: Record<string, string> = { hour: '시', day: '일', month: '월', year: '연' }
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 (
<div className="pb-8">
<div className="flex items-center gap-1 px-3 pt-1">
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
‹
</button>
<h2 className="m-0 flex items-center gap-1.5 px-1 font-jua text-[24px] font-normal">
<Ic name="yin_yang" className="size-7" />
날씨 사주
</h2>
</div>
{loading && !birth ? (
<p className="m-0 px-4 py-16 text-center font-semibold text-(--ink2)">내 생년월일을 불러오는 중이에요…</p>
) : !birth || editing ? (
<BirthForm initial={birth} onDone={() => setEditing(false)} onCancel={birth ? () => setEditing(false) : undefined} />
) : (
<Reading birth={birth} onEdit={() => setEditing(true)} />
)}
</div>
)
}
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 (
<div className="mx-4 mt-4 flex flex-col gap-4 rounded-[24px] bg-white p-5 shadow-[inset_0_-5px_0_var(--shade)]">
<div className="text-center">
<Ic name="yin_yang" className="mx-auto size-14" />
<p className="m-0 mt-2 font-jua text-[20px] leading-snug">
내 사주와 오늘 날씨로
<br />
오늘 하루를 봐요
</p>
</div>
<fieldset className="m-0 flex min-w-0 flex-col gap-1.5 border-0 p-0">
<legend className="mb-1.5 p-0 text-[13px] font-extrabold text-(--ink2)">생년월일 (양력)</legend>
<div className="grid grid-cols-[1.5fr_1fr_1fr] gap-1.5">
<input inputMode="numeric" placeholder="연도" value={y} onChange={num(setY, 4)} className={box} aria-label="년" />
<input inputMode="numeric" placeholder="월" value={m} onChange={num(setM, 2)} className={box} aria-label="월" />
<input inputMode="numeric" placeholder="일" value={d} onChange={num(setD, 2)} className={box} aria-label="일" />
</div>
</fieldset>
<fieldset className="m-0 flex min-w-0 flex-col gap-1.5 border-0 p-0">
<legend className="mb-1.5 p-0 text-[13px] font-extrabold text-(--ink2)">태어난 시각 (모르면 '모름')</legend>
<div className="grid grid-cols-2 gap-1.5">
<select value={hour} onChange={(e) => setHour(e.target.value)} className={pick} aria-label="시">
<option value="">모름</option>
{HOURS.map((h) => (
<option key={h} value={h}>
{h}시
</option>
))}
</select>
<select value={minute} onChange={(e) => setMinute(e.target.value)} disabled={hour === ''} className={cx(pick, 'disabled:bg-[#f3f5f9] disabled:text-[#a0a8ba]')} aria-label="분">
{MINUTES.map((mi) => (
<option key={mi} value={mi}>
{mi}분
</option>
))}
</select>
</div>
</fieldset>
<label className="flex min-w-0 flex-col gap-1.5 text-[13px] font-extrabold text-(--ink2)">
태어난 지역
<select value={place} onChange={(e) => setPlace(e.target.value)} className={pick}>
{BIRTH_PLACES.map(([k, n]) => (
<option key={k} value={k}>
{n}
</option>
))}
</select>
<span className="text-xs font-semibold text-(--ink3)">지역마다 해가 뜨는 시각이 달라 태어난 시각을 그만큼 고쳐서 봐요.</span>
</label>
{error && <p className="m-0 text-center text-[13px] font-bold text-[#d9442f]">{error}</p>}
<button type="button" onClick={submit} className="cursor-pointer rounded-full bg-(--orange) py-3.5 text-[15px] font-extrabold text-white">
오늘 날씨 사주 보기
</button>
{onCancel && (
<button type="button" onClick={onCancel} className="-mt-2 cursor-pointer py-1 text-[13px] font-extrabold text-(--ink3)">
취소
</button>
)}
<p className="m-0 text-center text-xs font-semibold text-(--ink3)">
{loggedIn ? '내 계정에 저장돼요. 내 정보에서 언제든 지울 수 있어요.' : '이 기기에만 저장돼요. 로그인하면 계정에 저장해 어느 기기에서든 바로 볼 수 있어요.'}
</p>
</div>
)
}
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<HTMLDivElement>(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 })
}, [r])
if (q.isPending) return <p className="m-0 px-4 py-16 text-center font-semibold text-(--ink2)">사주를 풀고 있어요…</p>
if (!r?.today || !r.me)
return (
<div className="px-4 py-16 text-center">
<p className="m-0 font-semibold text-(--ink2)">결과를 불러오지 못했어요.</p>
<button type="button" onClick={() => q.refetch()} className="mt-3 cursor-pointer rounded-full bg-(--ink) px-4 py-2 text-[13px] font-extrabold text-white">
다시 시도
</button>
</div>
)
const t = r.today
const lock = (key: string) => r.locks?.find((l) => l.key === key)
return (
<div className="flex flex-col gap-3">
<div ref={shot} className="mx-4 mt-3 rounded-[26px] bg-white px-5 pt-4 pb-5 shadow-[inset_0_-5px_0_var(--shade)]">
<p className="m-0 text-center text-[12.5px] font-extrabold text-(--ink3)">
{Number(t.day.slice(5, 7))}월 {Number(t.day.slice(8, 10))}일 {t.pillar}일 · 오늘의 점수
</p>
<p className="m-0 text-center font-bagel text-[60px] leading-none">{t.score}</p>
<h3 className="m-0 mt-1.5 text-center font-jua text-[23px] leading-tight font-normal">{t.title}</h3>
<div className="mt-2.5 flex flex-wrap justify-center gap-1.5 text-[11.5px] font-extrabold">
<span className="rounded-full bg-[#f3f6fb] px-2.5 py-1">사주 {t.saju_score}점</span>
{t.weather_points != null && (
<span className={cx('rounded-full px-2.5 py-1', t.weather_points >= 0 ? 'bg-[#e3f6ea] text-[#1f7a4f]' : 'bg-[#ffe8dc] text-[#c2471b]')}>
날씨 영향 {t.weather_points >= 0 ? '+' : '−'}
{Math.abs(t.weather_points)}점
</span>
)}
</div>
{(t.why?.length ?? 0) > 0 && (
<details className="mt-2 text-center">
<summary className="cursor-pointer text-xs font-bold text-(--ink3)">왜 이 점수인가요? (↑ 올린 것 · ↓ 내린 것)</summary>
<ul className="m-0 mt-1.5 list-none p-0 text-xs font-semibold text-(--ink2)">
{t.why!.map((w) => (
<li key={w}>{w}</li>
))}
</ul>
</details>
)}
</div>
<section aria-label="오늘의 결정" className="mx-4 flex flex-col gap-2">
{t.cards.map((c) => (
<DecisionCard key={c.kind} c={c} />
))}
</section>
<MeCard r={r} onEdit={onEdit} />
{r.week && <Week r={r} />}
{r.money && (
<Panel id="saju_money" icon="money_bag" title="금전운 · 일운">
{[...r.money.map((l) => ['money_bag', l]), ...(r.work ?? []).map((l) => ['briefcase', l])].map(([icon, l]) => (
<p key={l} className="m-0 mt-1.5 flex gap-2 text-[14px] font-semibold first:mt-0">
<Ic name={icon} className="mt-px size-5 shrink-0" />
{l}
</p>
))}
</Panel>
)}
{r.love && <Love r={r} birth={birth} />}
{lock('saju_match')?.unlocked && <Match birth={birth} />}
{r.month && <Period id="saju_month" icon="spiral_calendar" p={r.month} />}
{r.year && <Period id="saju_year" icon="sunrise" p={r.year} />}
<Locked locks={(r.locks ?? []).filter((l) => !l.unlocked)} />
<div className="mx-4 flex items-center justify-between">
<span className="text-xs font-semibold text-(--ink3)">재미로 보는 날씨 사주</span>
<button
type="button"
onClick={() => shot.current && open({ type: 'share', share: { title: `오늘 내 날씨 사주 ${t.score}점 · ${t.title}`, slides: [shot.current] } })}
className="cursor-pointer rounded-full bg-(--ink) px-4 py-2 text-[13px] font-extrabold text-white"
>
공유
</button>
</div>
</div>
)
}
function DecisionCard({ c }: { c: SajuCard }) {
return (
<div className="flex gap-3 rounded-[20px] bg-white px-4 py-3 shadow-[inset_0_-4px_0_var(--shade)]">
<Ic name={CARD_ICON[c.kind] ?? 'sparkles'} className="mt-0.5 size-8 shrink-0" />
<div className="min-w-0">
<p className="m-0 text-[12px] font-extrabold text-(--orange)">{c.kind === 'when' ? '내 기운에 맞는 시간' : c.title}</p>
<p className="m-0 font-jua text-[17px] leading-snug whitespace-pre-line">{c.kind === 'when' ? `${c.title} · ${c.sub}` : c.body}</p>
<p className="m-0 mt-0.5 text-[12px] leading-snug font-semibold text-(--ink3)">{c.kind === 'when' ? c.body : c.sub}</p>
</div>
</div>
)
}
function MeCard({ r, onEdit }: { r: ResSaju; onEdit: () => void }) {
const me = r.me!
const cols = [...me.pillars].reverse()
return (
<Panel icon={me.scene_icon} title={`내 기운 · ${me.scene.replace(/ 기운$/, '')}`} right={<button type="button" onClick={onEdit} className="cursor-pointer text-xs font-extrabold text-(--orange)">생년월일 바꾸기</button>}>
<p className="m-0 text-[14px] font-semibold text-(--ink2)">{me.scene_desc}</p>
<div className="mt-3 grid grid-cols-4 gap-1.5 text-center">
{(me.hour_known ? cols : [null, ...cols]).map((p, i) => (
<div key={p?.position ?? `none-${i}`} className="flex flex-col gap-1">
<span className="text-[11px] font-extrabold text-(--ink3)">{p ? POS_WORD[p.position] : '시'}</span>
{p ? (
<>
<Char c={p.stem} ko={p.stem_ko} el={p.stem_element} />
<Char c={p.branch} ko={p.branch_ko} el={p.branch_element} />
</>
) : (
<>
<span className="grid flex-1 place-items-center rounded-xl bg-[#f1f3f7] text-[12px] font-extrabold text-[#a0a8ba]">시각 모름</span>
</>
)}
</div>
))}
</div>
<p className="m-0 mt-2 text-[11.5px] font-semibold text-(--ink3)">태어난 연·월·일·시의 여덟 글자(사주팔자)예요. 색은 나무·불·흙·쇠·물 다섯 기운이에요.</p>
{(me.need?.length ?? 0) > 0 && <p className="m-0 mt-2 text-[13px] font-bold">내 기운에 좋은 날씨: {me.need!.join(' · ')}</p>}
{me.jeol_warning && <p className="m-0 mt-1 text-xs font-semibold text-[#c2471b]">태어난 날에 절기가 바뀌어요. 태어난 시각을 넣어야 달 기둥이 정확해요.</p>}
</Panel>
)
}
function Char({ c, ko, el }: { c: string; ko: string; el: string }) {
const [fg, bg] = EL_COLOR[el] ?? ['#28304a', '#f3f6fb']
return (
<span className="rounded-xl py-1.5" style={{ background: bg, color: fg }}>
<b className="block font-batang text-[22px] leading-tight">{c}</b>
<small className="text-[10.5px] font-extrabold">{ko}</small>
</span>
)
}
function Panel({ id, icon, title, right, children }: { id?: string; icon: string; title: string; right?: ReactNode; children: ReactNode }) {
return (
<section id={id} className="mx-4 scroll-mt-20 rounded-[22px] bg-white px-4 py-3.5 shadow-[inset_0_-4px_0_var(--shade)]">
<div className="mb-2 flex items-center gap-2">
<Ic name={icon} className="size-7" />
<h3 className="m-0 font-jua text-[17px] font-normal">{title}</h3>
{right && <span className="ml-auto">{right}</span>}
</div>
{children}
</section>
)
}
/** 아직 안 열린 것: 다음에 열릴 하나를 크게, 나머지는 한 줄로. 로그인 전이면 로그인부터 */
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 (
<section className="mx-4 rounded-[22px] bg-[#eef1f7] px-4 py-3.5">
<div className="flex items-center gap-3">
<Ic name="locked" className="size-8 shrink-0" />
<div className="min-w-0 flex-1">
<p className="m-0 font-jua text-[16px]">{loggedIn ? `다음은 ${next.name}` : '각을 모으면 더 볼 수 있어요'}</p>
<p className="m-0 text-xs font-bold text-(--ink2)">
{loggedIn ? (close ? `${level.next_points! - level.points}각 더 모으면 열려요` : `Lv.${next.level}이 되면 열려요`) : "로그인하고 출석·사주 보기·좋아요를 하면 활동 포인트 '각'이 쌓여요"}
</p>
</div>
<button type="button" onClick={() => open(loggedIn ? { type: 'level' } : { type: 'login', why: 'level' })} className="shrink-0 cursor-pointer rounded-full bg-(--ink) px-3 py-1.5 text-xs font-extrabold text-white">
{loggedIn ? '각 모으는 법' : '로그인'}
</button>
</div>
{close && (
<span className="mt-2.5 block h-1.5 overflow-hidden rounded-full bg-white">
<span className="block h-full rounded-full bg-(--orange)" style={{ width: `${Math.round(progress(level) * 100)}%` }} />
</span>
)}
<ul className="m-0 mt-2.5 flex list-none flex-wrap gap-1.5 p-0">
{(loggedIn ? rest : [next, ...rest]).map((l) => (
<li key={l.key} className="rounded-full bg-white px-2.5 py-1 text-[11.5px] font-extrabold text-(--ink2)">
Lv.{l.level} {l.name}
</li>
))}
</ul>
</section>
)
}
function Week({ r }: { r: ResSaju }) {
return (
<Panel id="saju_week" icon="spiral_calendar" title="앞으로 7일 흐름">
<ol className="m-0 flex list-none flex-col gap-1 p-0">
{r.week!.map((d) => (
<li key={d.day} className={cx('flex items-center gap-2 rounded-xl px-2 py-1.5 text-[13px] font-bold', d.best && 'bg-[#fff6ef]')}>
<span className="w-[66px] shrink-0 whitespace-nowrap">{dayWord(d.day, d.weekday)}</span>
{d.icon && <Ic name={d.icon} className="size-6 shrink-0" />}
<span className="w-[52px] shrink-0 whitespace-nowrap text-(--ink2)">{d.temp_max != null ? `${d.temp_min}~${d.temp_max}°` : ''}</span>
<span className="min-w-0 flex-1 truncate text-[12.5px] text-(--ink2)">{d.title}</span>
<b className={cx('font-bagel text-[15px] font-normal', d.best ? 'text-(--orange)' : '')}>{d.score}</b>
</li>
))}
</ol>
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">점수는 그날 사주와 예보로 계산해요. 주황색은 7일 중 점수가 가장 높은 날이에요.</p>
</Panel>
)
}
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 (
<Panel id="saju_love" icon="red_heart" title="앞으로 7일 연애운">
{love.good ? (
<div className="rounded-xl bg-[#fff0f3] px-3 py-2.5">
<p className="m-0 text-xs font-extrabold text-[#d6457a]">연애 기운이 좋은 날</p>
<p className="m-0 font-jua text-[17px]">
{dayWord(love.good.day, love.good.weekday)}
{love.good.word ? ` · ${love.good.word} ${love.good.temp_max ?? ''}°` : ''}
</p>
<p className="m-0 text-[13px] font-semibold">{love.good.body}</p>
<p className="m-0 text-[11.5px] font-semibold text-(--ink3)">{love.good.why}</p>
</div>
) : (
<p className="m-0 text-[13px] font-semibold text-(--ink2)">앞으로 7일 중엔 연애 기운이 두드러지는 날이 없어요.</p>
)}
{love.caution && (
<p className="m-0 mt-2 text-[13px] font-semibold">
조심할 날 {dayWord(love.caution.day, love.caution.weekday)}: {love.caution.body} <span className="text-(--ink3)">· {love.caution.why}</span>
</p>
)}
{love.gender_known ? (
<p className="m-0 mt-2.5 text-xs font-bold text-(--ink3)">
{birth.gender === 'M' ? '남성' : '여성'} 기준으로 이성 인연(재성·관성)까지 봤어요 ·{' '}
<button type="button" onClick={() => pick(null)} className="cursor-pointer font-extrabold text-(--orange)">
빼고 보기
</button>
</p>
) : (
<div className="mt-2.5 flex flex-wrap items-center gap-1.5 text-xs font-bold text-(--ink2)">
성별을 고르면 이성 인연(재성·관성)까지 봐요
<button type="button" onClick={() => pick('M')} className={chip}>
남성
</button>
<button type="button" onClick={() => pick('F')} className={chip}>
여성
</button>
</div>
)}
</Panel>
)
}
function Period({ id, icon, p }: { id: string; icon: string; p: NonNullable<ResSaju['month']> }) {
return (
<Panel id={id} icon={icon} title={p.label}>
<p className="m-0 font-jua text-[17px]">
{p.title} <span className="text-[13px] text-(--ink3)">({p.ten_god})</span>
</p>
<p className="m-0 mt-0.5 text-[13.5px] font-semibold">{p.body}</p>
{(p.months?.length ?? 0) > 0 && <p className="m-0 mt-1.5 text-[13.5px] font-bold">{p.label.includes('미리') ? '내 사주와 잘 맞는 달' : '남은 달 중 잘 맞는 달'}: {p.months!.map((m) => `${m}월`).join(' · ')}</p>}
{p.notes?.map((n) => (
<p key={n} className="m-0 mt-1 text-xs font-semibold text-(--ink3)">
{n}
</p>
))}
</Panel>
)
}
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 (
<Panel id="saju_match" icon="two_hearts" title="궁합">
{res ? (
<>
<p className="m-0 mb-1 flex items-center justify-between text-xs font-bold text-(--ink3)">
상대 {y}.{m}.{d}생
<button type="button" onClick={() => run.reset()} className="cursor-pointer font-extrabold text-(--orange)">
다른 사람 보기
</button>
</p>
<p className="m-0 font-jua text-[19px]">
{res.title} <span className="font-bagel text-[17px] text-(--orange)">{res.score}점</span>
</p>
{res.lines?.map((l) => (
<p key={l} className="m-0 mt-1 text-[13.5px] font-semibold">
{l}
</p>
))}
{res.day && (
<p className="m-0 mt-2 rounded-xl bg-[#fff6ef] px-3 py-2 text-[13.5px] font-bold">
앞으로 7일 중 같이 나가기 좋은 날: {dayWord(res.day.day, res.day.weekday)}
{res.day.word ? ` · ${res.day.word} ${res.day.temp_max ?? ''}°` : ''}
</p>
)}
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">상대 기운: {res.friend_scene}</p>
</>
) : (
<>
<p className="m-0 mb-2 text-[13px] font-semibold text-(--ink2)">상대 생년월일(양력)을 넣으면 두 사람 사주가 어떻게 맞는지와 앞으로 7일 중 같이 나가기 좋은 날을 봐요.</p>
<div className="grid grid-cols-[1.5fr_1fr_1fr_auto] gap-1.5">
<input inputMode="numeric" placeholder="연도" value={y} onChange={(e) => setY(e.target.value.replace(/\D/g, '').slice(0, 4))} className={input} aria-label="상대 년" />
<input inputMode="numeric" placeholder="월" value={m} onChange={(e) => setM(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 월" />
<input inputMode="numeric" placeholder="일" value={d} onChange={(e) => setD(e.target.value.replace(/\D/g, '').slice(0, 2))} className={input} aria-label="상대 일" />
<button type="button" onClick={go} disabled={run.isPending} className="shrink-0 cursor-pointer rounded-xl bg-(--orange) px-3 text-[14px] font-extrabold text-white">
보기
</button>
</div>
{error && <p className="m-0 mt-1.5 text-xs font-bold text-[#d9442f]">{error}</p>}
{(run.isError || (run.data && !run.data.result?.success)) && <p className="m-0 mt-1.5 text-xs font-bold text-[#d9442f]">궁합을 불러오지 못했어요. 다시 눌러 주세요.</p>}
<p className="m-0 mt-1.5 text-xs font-semibold text-(--ink3)">상대 생년월일은 저장하지 않아요.</p>
</>
)}
</Panel>
)
}