import { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { Calendar, Music2, Clock, X, ChevronLeft, ChevronRight, Download } from 'lucide-react';
function AlbumDetail() {
const { name } = useParams();
const navigate = useNavigate();
const [album, setAlbum] = useState(null);
const [loading, setLoading] = useState(true);
const [lightbox, setLightbox] = useState({ open: false, images: [], index: 0 });
const [slideDirection, setSlideDirection] = useState(0);
const [imageLoaded, setImageLoaded] = useState(false);
// 라이트박스 네비게이션 함수
const goToPrev = useCallback(() => {
if (lightbox.images.length <= 1) return;
setImageLoaded(false);
setSlideDirection(-1);
setLightbox(prev => ({
...prev,
index: (prev.index - 1 + prev.images.length) % prev.images.length
}));
}, [lightbox.images.length]);
const goToNext = useCallback(() => {
if (lightbox.images.length <= 1) return;
setImageLoaded(false);
setSlideDirection(1);
setLightbox(prev => ({
...prev,
index: (prev.index + 1) % prev.images.length
}));
}, [lightbox.images.length]);
const closeLightbox = useCallback(() => {
setLightbox(prev => ({ ...prev, open: false }));
}, []);
// 이미지 다운로드 함수
const downloadImage = useCallback(async () => {
const imageUrl = lightbox.images[lightbox.index];
if (!imageUrl) return;
try {
const response = await fetch(imageUrl);
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `fromis9_photo_${String(lightbox.index + 1).padStart(2, '0')}.webp`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
} catch (error) {
console.error('다운로드 오류:', error);
}
}, [lightbox.images, lightbox.index]);
// 키보드 이벤트 핸들러
useEffect(() => {
if (!lightbox.open) return;
const handleKeyDown = (e) => {
switch (e.key) {
case 'ArrowLeft':
goToPrev();
break;
case 'ArrowRight':
goToNext();
break;
case 'Escape':
closeLightbox();
break;
default:
break;
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [lightbox.open, goToPrev, goToNext, closeLightbox]);
// 이미지 프리로딩 (이전/다음 이미지)
useEffect(() => {
if (!lightbox.open || lightbox.images.length <= 1) return;
const preloadImages = [];
const prevIdx = (lightbox.index - 1 + lightbox.images.length) % lightbox.images.length;
const nextIdx = (lightbox.index + 1) % lightbox.images.length;
[prevIdx, nextIdx].forEach(idx => {
const img = new Image();
img.src = lightbox.images[idx];
preloadImages.push(img);
});
}, [lightbox.open, lightbox.index, lightbox.images]);
useEffect(() => {
fetch(`/api/albums/by-name/${name}`)
.then(res => res.json())
.then(data => {
setAlbum(data);
setLoading(false);
})
.catch(error => {
console.error('앨범 데이터 로드 오류:', error);
setLoading(false);
});
}, [name]);
// URL 헬퍼 함수는 더 이상 필요 없음 - API에서 직접 제공
// 날짜 포맷팅
const formatDate = (dateStr) => {
if (!dateStr) return '';
const date = new Date(dateStr);
return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`;
};
// 총 재생 시간 계산
const getTotalDuration = () => {
if (!album?.tracks) return '';
let totalSeconds = 0;
album.tracks.forEach(track => {
if (track.duration) {
const parts = track.duration.split(':');
totalSeconds += parseInt(parts[0]) * 60 + parseInt(parts[1]);
}
});
const mins = Math.floor(totalSeconds / 60);
const secs = totalSeconds % 60;
return `${mins}:${String(secs).padStart(2, '0')}`;
};
// 뒤로가기
const handleBack = () => {
navigate('/album');
};
if (loading) {
return (
앨범을 찾을 수 없습니다.
타이틀곡: {album.tracks?.find(t => t.is_title_track === 1)?.title || album.tracks?.[0]?.title}
Official Teaser
{album.description}