import { useParams, Link } from 'react-router-dom';
import { useQuery, keepPreviousData } from '@tanstack/react-query';
import { useEffect, useRef, useState } from 'react';
import { motion } from 'framer-motion';
import { Clock, Calendar, ExternalLink, ChevronRight, Link2, MapPin, Navigation } from 'lucide-react';
import { getSchedule, getXProfile } from '../../../api/public/schedules';
// 카카오맵 SDK 키
const KAKAO_MAP_KEY = import.meta.env.VITE_KAKAO_JS_KEY;
// 카테고리 ID 상수
const CATEGORY_ID = {
YOUTUBE: 2,
X: 3,
ALBUM: 4,
FANSIGN: 5,
CONCERT: 6,
TICKET: 7,
};
// HTML 엔티티 디코딩 함수
const decodeHtmlEntities = (text) => {
if (!text) return '';
const textarea = document.createElement('textarea');
textarea.innerHTML = text;
return textarea.value;
};
// 유튜브 비디오 ID 추출
const extractYoutubeVideoId = (url) => {
if (!url) return null;
const shortMatch = url.match(/youtu\.be\/([a-zA-Z0-9_-]{11})/);
if (shortMatch) return shortMatch[1];
const watchMatch = url.match(/youtube\.com\/watch\?v=([a-zA-Z0-9_-]{11})/);
if (watchMatch) return watchMatch[1];
const shortsMatch = url.match(/youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/);
if (shortsMatch) return shortsMatch[1];
return null;
};
// 날짜 포맷팅
const formatFullDate = (dateStr) => {
if (!dateStr) return '';
const date = new Date(dateStr);
const dayNames = ['일', '월', '화', '수', '목', '금', '토'];
return `${date.getFullYear()}. ${date.getMonth() + 1}. ${date.getDate()}. (${dayNames[date.getDay()]})`;
};
// 시간 포맷팅
const formatTime = (timeStr) => {
if (!timeStr) return null;
return timeStr.slice(0, 5);
};
// X용 날짜/시간 포맷팅 (오후 2:30 · 2026년 1월 15일)
const formatXDateTime = (dateStr, timeStr) => {
if (!dateStr) return '';
const date = new Date(dateStr);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
let result = `${year}년 ${month}월 ${day}일`;
if (timeStr) {
const [hours, minutes] = timeStr.split(':').map(Number);
const period = hours < 12 ? '오전' : '오후';
const hour12 = hours === 0 ? 12 : hours > 12 ? hours - 12 : hours;
result = `${period} ${hour12}:${String(minutes).padStart(2, '0')} · ${result}`;
}
return result;
};
// 영상 정보 컴포넌트 (공통)
function VideoInfo({ schedule, isShorts }) {
return (
{/* 제목 */}
{decodeHtmlEntities(schedule.title)}
{/* 메타 정보 */}
{/* 날짜 */}
{formatFullDate(schedule.date)}
{/* 시간 */}
{schedule.time && (
<>
{formatTime(schedule.time)}
>
)}
{/* 채널명 */}
{schedule.source_name && (
<>
{schedule.source_name}
>
)}
{/* 유튜브에서 보기 버튼 */}
);
}
// 유튜브 섹션 컴포넌트
function YoutubeSection({ schedule }) {
const videoId = extractYoutubeVideoId(schedule.source_url);
const isShorts = schedule.source_url?.includes('/shorts/');
if (!videoId) return null;
// 숏츠: 가로 레이아웃 (영상 + 정보)
if (isShorts) {
return (
{/* 영상 임베드 */}
VIDEO
{/* 영상 정보 카드 */}
);
}
// 일반 영상: 세로 레이아웃 (영상 위, 정보 아래)
return (
{/* 영상 임베드 */}
VIDEO
{/* 영상 정보 카드 */}
);
}
// X URL에서 username 추출
const extractXUsername = (url) => {
if (!url) return null;
const match = url.match(/(?:twitter\.com|x\.com)\/([^/]+)/);
return match ? match[1] : null;
};
// X(트위터) 섹션 컴포넌트
function XSection({ schedule }) {
const username = extractXUsername(schedule.source_url);
// 프로필 정보 조회
const { data: profile } = useQuery({
queryKey: ['x-profile', username],
queryFn: () => getXProfile(username),
enabled: !!username,
staleTime: 1000 * 60 * 60, // 1시간
});
const displayName = profile?.displayName || schedule.source_name || username || 'Unknown';
const avatarUrl = profile?.avatarUrl;
return (
{/* X 스타일 카드 */}
{/* 헤더 */}
{/* 프로필 이미지 */}
{avatarUrl ? (
) : (
{displayName.charAt(0).toUpperCase()}
)}
{username && (
@{username}
)}
{/* 본문 */}
{decodeHtmlEntities(schedule.description || schedule.title)}
{/* 이미지 */}
{schedule.image_url && (
)}
{/* 날짜/시간 */}
{formatXDateTime(schedule.date, schedule.time)}
{/* X에서 보기 버튼 */}
);
}
// 카카오맵 컴포넌트
function KakaoMap({ lat, lng, name }) {
const mapRef = useRef(null);
const [mapLoaded, setMapLoaded] = useState(false);
const [mapError, setMapError] = useState(false);
useEffect(() => {
// API 키가 없으면 에러
if (!KAKAO_MAP_KEY) {
setMapError(true);
return;
}
// 카카오맵 SDK 동적 로드
if (!window.kakao?.maps) {
const script = document.createElement('script');
script.src = `//dapi.kakao.com/v2/maps/sdk.js?appkey=${KAKAO_MAP_KEY}&autoload=false`;
script.onload = () => {
window.kakao.maps.load(() => setMapLoaded(true));
};
script.onerror = () => setMapError(true);
document.head.appendChild(script);
} else {
setMapLoaded(true);
}
}, []);
useEffect(() => {
if (!mapLoaded || !mapRef.current || mapError) return;
try {
const position = new window.kakao.maps.LatLng(lat, lng);
const map = new window.kakao.maps.Map(mapRef.current, {
center: position,
level: 3,
});
// 마커 추가
const marker = new window.kakao.maps.Marker({
position,
map,
});
// 인포윈도우 추가
if (name) {
const infowindow = new window.kakao.maps.InfoWindow({
content: `${name}
`,
});
infowindow.open(map, marker);
}
} catch (e) {
setMapError(true);
}
}, [mapLoaded, lat, lng, name, mapError]);
// 에러 시 정적 이미지 또는 링크로 대체
if (mapError) {
return (
);
}
return (
);
}
// 콘서트 섹션 컴포넌트
function ConcertSection({ schedule }) {
const hasLocation = schedule.location_lat && schedule.location_lng;
const hasPoster = schedule.images?.length > 0;
const relatedDates = schedule.related_dates || [];
const hasMultipleDates = relatedDates.length > 1;
// 개별 날짜 포맷팅
const formatSingleDate = (dateStr, timeStr) => {
const date = new Date(dateStr);
const dayNames = ['일', '월', '화', '수', '목', '금', '토'];
const month = date.getMonth() + 1;
const day = date.getDate();
const weekday = dayNames[date.getDay()];
let result = `${month}월 ${day}일 (${weekday})`;
if (timeStr) {
result += ` ${timeStr.slice(0, 5)}`;
}
return result;
};
return (
{/* 상단: 포스터 + 정보 카드 (가로 배치) */}
{/* 포스터 이미지 */}
{hasPoster && (
)}
{/* 정보 카드 */}
{/* 헤더 */}
{decodeHtmlEntities(schedule.title)}
{/* 정보 목록 */}
{/* 공연 일정 목록 */}
{hasMultipleDates ? (
{relatedDates.map((item, index) => {
const isCurrentDate = item.id === schedule.id;
return (
{index + 1}회차
{formatSingleDate(item.date, item.time)}
);
})}
) : (
{formatSingleDate(schedule.date, schedule.time)}
)}
{/* 장소 */}
{schedule.location_name && (
{schedule.location_name}
{schedule.location_address && (
{schedule.location_address}
)}
)}
{/* 설명 */}
{schedule.description && (
{decodeHtmlEntities(schedule.description)}
)}
{/* 버튼 영역 */}
{schedule.source_url && (
)}
{/* 하단: 지도 */}
{schedule.location_name && hasLocation && (
위치 안내
{schedule.location_name}
길찾기
)}
{/* 해외 공연 등 좌표 없는 경우 */}
{schedule.location_name && !hasLocation && (
{schedule.location_name}
{schedule.location_address && (
{schedule.location_address}
)}
{schedule.location_detail && (
{schedule.location_detail}
)}
)}
);
}
// 기본 섹션 컴포넌트 (다른 카테고리용)
function DefaultSection({ schedule }) {
return (
{/* 제목 */}
{decodeHtmlEntities(schedule.title)}
{/* 메타 정보 */}
{formatFullDate(schedule.date)}
{schedule.time && (
{formatTime(schedule.time)}
)}
{/* 설명 */}
{schedule.description && (
{decodeHtmlEntities(schedule.description)}
)}
{/* 원본 링크 */}
{schedule.source_url && (
원본 보기
)}
);
}
function ScheduleDetail() {
const { id } = useParams();
const { data: schedule, isLoading, error, isFetching } = useQuery({
queryKey: ['schedule', id],
queryFn: () => getSchedule(id),
placeholderData: keepPreviousData,
});
if (isLoading) {
return (
);
}
if (error || !schedule) {
return (
);
}
// 카테고리별 섹션 렌더링
const renderCategorySection = () => {
switch (schedule.category_id) {
case CATEGORY_ID.YOUTUBE:
return ;
case CATEGORY_ID.X:
return ;
case CATEGORY_ID.CONCERT:
return ;
default:
return ;
}
};
const isYoutube = schedule.category_id === CATEGORY_ID.YOUTUBE;
const isX = schedule.category_id === CATEGORY_ID.X;
const isConcert = schedule.category_id === CATEGORY_ID.CONCERT;
const hasCustomLayout = isYoutube || isX || isConcert;
return (
{/* 브레드크럼 네비게이션 */}
일정
{schedule.category_name}
{decodeHtmlEntities(schedule.title)}
{/* 메인 컨텐츠 */}
{renderCategorySection()}
);
}
export default ScheduleDetail;