'use client';
import { useState, useEffect, useRef } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { SajuIcon, SECTION_ICON_ORDER } from './SajuIcons';
interface BirthKey {
birth_year: number;
birth_month: number;
birth_day: number;
birth_hour?: number;
gender: string;
}
interface SajuAISectionProps {
hasPaid: boolean;
savedInterpretation: string | null;
sajuData: object;
daeun: object | null;
daeunList: object[];
gender: string;
birthKey: BirthKey;
currentUrl: string;
engineData?: {
interactions?: any[];
shinsal?: any[];
gongmang?: any;
hiddenStems?: any[];
};
}
// ── 섹션별 메타 (뱃지 라벨) — 아이콘은 SECTION_ICON_ORDER에서 동일 인덱스로 조회 ──
const SECTION_META: { badgeText: string }[] = [
{ badgeText: '기질' },
{ badgeText: '오행' },
{ badgeText: '지지' },
{ badgeText: '신살' },
{ badgeText: '재물' },
{ badgeText: '직업' },
{ badgeText: '애정' },
{ badgeText: '건강' },
{ badgeText: '대운' },
{ badgeText: '세운' },
{ badgeText: '황금기' },
{ badgeText: '종합' },
];
// ── 마크다운 → 섹션 파싱 ──────────────────────────────────────────────
interface ParsedSection {
number: number;
title: string;
content: string;
}
function parseInterpretation(text: string): ParsedSection[] {
// "## 숫자. 제목" 패턴으로 분리
const parts = text.split(/\n(?=##\s+\d+[\.\s])/).filter(Boolean);
const sections: ParsedSection[] = [];
for (const part of parts) {
const lines = part.trim().split('\n');
const headerLine = lines[0] ?? '';
const match = headerLine.match(/^##\s+(\d+)[.\s]\s*(.+)$/);
if (match) {
sections.push({
number: parseInt(match[1], 10),
title: match[2].trim(),
content: lines.slice(1).join('\n').trim(),
});
}
}
// 파싱 실패 시 전체를 하나의 섹션으로
if (sections.length === 0 && text.trim()) {
sections.push({ number: 0, title: 'AI 해석', content: text.trim() });
}
return sections;
}
// ── 섹션 카드 컴포넌트 ────────────────────────────────────────────────
function SectionCard({ section, meta, iconName, isOpen, onToggle }: {
section: ParsedSection;
meta: typeof SECTION_META[0];
iconName: (typeof SECTION_ICON_ORDER)[number];
isOpen: boolean;
onToggle: () => void;
}) {
return (
{/* 헤더 */}
{/* 내용 (아코디언) */}
{isOpen && (
{children}
,
h2: ({ children }) => {children}
,
h3: ({ children }) => {children}
,
p: ({ children }) => {children}
,
strong: ({ children }) => {children},
em: ({ children }) => {children},
ul: ({ children }) => ,
ol: ({ children }) => {children}
,
li: ({ children }) => {children},
blockquote: ({ children }) => (
{children}
),
hr: () =>
,
code: ({ children }) => (
{children}
),
}}
>
{section.content}
)}
);
}
// mock 데이터 여부 감지 (저장된 해석이 예시 데이터인 경우 재생성 필요)
function isMockInterpretation(text: string | null): boolean {
if (!text) return false;
return (
text.includes('API 키 문제 또는 할당량 초과') ||
text.includes('GEMINI_API_KEY 환경변수를 설정') ||
text.includes('예시 데이터를 보여드립니다') ||
text.includes('API 설정이 필요합니다')
);
}
// ── 메인 컴포넌트 ──────────────────────────────────────────────────────
export default function SajuAISection({
hasPaid,
savedInterpretation,
sajuData,
daeun,
daeunList,
gender,
birthKey,
currentUrl,
engineData,
}: SajuAISectionProps) {
const pathname = usePathname();
const searchParams = useSearchParams();
const search = searchParams.toString();
const loginHref = `/login?next=${encodeURIComponent(`${pathname}${search ? `?${search}` : ''}`)}`;
// 저장된 해석이 mock 데이터면 재생성 필요
const isMock = isMockInterpretation(savedInterpretation);
const validSaved = savedInterpretation && !isMock ? savedInterpretation : null;
const [status, setStatus] = useState<'idle' | 'loading' | 'done' | 'error'>(
validSaved ? 'done' : 'idle'
);
const [interpretation, setInterpretation] = useState(validSaved ?? '');
const [openSections, setOpenSections] = useState>(new Set([0]));
const [errorMessage, setErrorMessage] = useState(null);
const called = useRef(false);
const sections = parseInterpretation(interpretation);
const toggleSection = (idx: number) => {
setOpenSections(prev => {
const next = new Set(prev);
if (next.has(idx)) next.delete(idx);
else next.add(idx);
return next;
});
};
const expandAll = () => setOpenSections(new Set(sections.map((_, i) => i)));
const collapseAll = () => setOpenSections(new Set());
// 재생성: called ref 초기화 후 다시 API 호출
const handleRegenerate = () => {
called.current = false;
setStatus('idle');
setInterpretation('');
// idle → useEffect가 다시 실행되도록 상태 전환 트리거
setTimeout(() => {
called.current = false;
setStatus('loading');
setErrorMessage(null);
fetch('/api/saju/analyze', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ saju: sajuData, daeun, daeunList, gender, engineData }),
})
.then(async r => {
if (r.status === 429) return { __rateLimited: true };
return r.json();
})
.then(data => {
if (data.__rateLimited) {
setErrorMessage('오늘 무료 횟수를 모두 사용했습니다. 내일 다시 시도해주세요.');
setStatus('error');
return;
}
if (data.interpretation && !isMockInterpretation(data.interpretation)) {
setInterpretation(data.interpretation);
setStatus('done');
setOpenSections(new Set([0]));
// DB에 실제 해석으로 덮어쓰기
const { birth_year, birth_month, birth_day } = birthKey;
if (typeof birth_year === 'number' && typeof birth_month === 'number' && typeof birth_day === 'number') {
fetch('/api/saju/save-interpretation', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ interpretation: data.interpretation, birthKey }),
}).catch(() => {});
}
} else {
setStatus('error');
}
})
.catch(() => setStatus('error'));
}, 0);
};
useEffect(() => {
if (!hasPaid || validSaved || called.current) return;
called.current = true;
setStatus('loading');
setErrorMessage(null);
fetch('/api/saju/analyze', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ saju: sajuData, daeun, daeunList, gender, engineData }),
})
.then(async r => {
if (r.status === 429) return { __rateLimited: true };
return r.json();
})
.then(data => {
if (data.__rateLimited) {
setErrorMessage('오늘 무료 횟수를 모두 사용했습니다. 내일 다시 시도해주세요.');
setStatus('error');
return;
}
if (data.interpretation) {
setInterpretation(data.interpretation);
setStatus('done');
// 첫 번째 섹션 자동 열기
setOpenSections(new Set([0]));
const { birth_year, birth_month, birth_day } = birthKey;
if (
typeof birth_year === 'number' && !isNaN(birth_year) &&
typeof birth_month === 'number' && !isNaN(birth_month) &&
typeof birth_day === 'number' && !isNaN(birth_day)
) {
fetch('/api/saju/save-interpretation', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ interpretation: data.interpretation, birthKey }),
}).catch(() => {});
}
} else {
setStatus('error');
}
})
.catch(() => setStatus('error'));
}, [hasPaid]);
// ── 미로그인 ────────────────────────────────────────────────────────
if (!hasPaid) {
return (
AI PREMIUM
AI 상세 해석 (12개 항목)
성격, 재물운, 직업 적성, 애정운, 건강운, 대운 분석 등
Gemini 2.5 Pro가 생성하는 맞춤형 사주 해석을 받아보세요.
{/* 미리보기 섹션 목록 */}
{SECTION_META.map((meta, i) => (
{meta.badgeText}
))}
로그인하고 AI 상세 해석 무료로 받기
로그인 회원은 하루 1회 무료 · 저장된 해석은 언제든 다시 보기
);
}
// ── 로딩 ──────────────────────────────────────────────────────────
if (status === 'loading') {
return (
AI가 사주를 분석하는 중입니다...
약 20~30초 소요될 수 있습니다
{SECTION_META.map((meta, i) => (
{meta.badgeText}
))}
);
}
// ── 오류 ──────────────────────────────────────────────────────────
if (status === 'error') {
return (
{errorMessage ?? 'AI 해석 생성에 실패했습니다.'}
{!errorMessage && (
)}
);
}
// ── 해석 완료 ─────────────────────────────────────────────────────
return (
{/* 헤더 */}
AI 상세 해석
12개 항목 · 클릭해서 펼쳐보세요
{/* 섹션 컨트롤 + 목록 */}
{/* 전체 펼치기/접기 */}
{sections.length > 1 && (
총 {sections.length}개 항목
)}
{/* 섹션 카드 목록 */}
{sections.map((section, idx) => {
const metaIdx = section.number > 0 ? Math.min(section.number - 1, SECTION_META.length - 1) : idx % SECTION_META.length;
const meta = SECTION_META[metaIdx];
return (
toggleSection(idx)}
/>
);
})}
{/* 하단 안내 */}
{sections.length > 0 && (
해석은 사주 데이터를 기반으로 AI가 생성한 내용입니다. 참고용으로 활용해주세요.
)}
);
}