import React, { useState, useRef } from 'react'; import { Track, usePlayerStore, songToTrack } from '../store/playerStore'; import { Play, Music, Star, X, Trash2, Save, FolderOpen, Shuffle, Infinity, Waves, MicVocal, ListMusic, Check, ListPlus } from 'lucide-react'; import { buildCoverArtUrl, getAlbum, getPlaylists, getPlaylist, createPlaylist, updatePlaylist, deletePlaylist, SubsonicPlaylist } from '../api/subsonic'; import { useEffect } from 'react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; import { useAuthStore } from '../store/authStore'; import { useLyricsStore } from '../store/lyricsStore'; import { useDragDrop } from '../contexts/DragDropContext'; import LyricsPane from './LyricsPane'; function formatTime(seconds: number): string { if (!seconds || isNaN(seconds)) return '0:00'; const m = Math.floor(seconds / 60); const s = Math.floor(seconds % 60); return `${m}:${s.toString().padStart(2, '0')}`; } function renderStars(rating?: number) { if (!rating) return null; const stars = []; for (let i = 1; i <= 5; i++) { stars.push( ); } return
{stars}
; } function SavePlaylistModal({ onClose, onSave }: { onClose: () => void, onSave: (name: string) => void }) { const { t } = useTranslation(); const [name, setName] = useState(''); return (
e.stopPropagation()} style={{ maxWidth: '400px' }}>

{t('queue.savePlaylist')}

setName(e.target.value)} autoFocus onKeyDown={e => e.key === 'Enter' && name.trim() && onSave(name.trim())} style={{ width: '100%', marginBottom: '1rem', padding: '10px 16px' }} />
); } function LoadPlaylistModal({ onClose, onLoad }: { onClose: () => void, onLoad: (id: string, name: string, mode: 'replace' | 'append') => void }) { const { t } = useTranslation(); const [playlists, setPlaylists] = useState([]); const [loading, setLoading] = useState(true); const [filter, setFilter] = useState(''); const [confirmDelete, setConfirmDelete] = useState<{ id: string; name: string } | null>(null); const fetchPlaylists = () => { setLoading(true); getPlaylists().then(data => { setPlaylists(data); setLoading(false); }).catch(e => { console.error(e); setLoading(false); }); }; useEffect(() => { fetchPlaylists(); }, []); const handleDelete = async (id: string, name: string) => { setConfirmDelete({ id, name }); }; const confirmDeletePlaylist = async () => { if (!confirmDelete) return; await deletePlaylist(confirmDelete.id); setConfirmDelete(null); fetchPlaylists(); }; return ( <>
e.stopPropagation()} style={{ maxWidth: '560px', width: '90vw' }}>

{t('queue.loadPlaylist')}

{!loading && playlists.length > 0 && ( setFilter(e.target.value)} autoFocus style={{ width: '100%', marginBottom: '0.75rem', padding: '8px 14px' }} /> )} {loading ? (

{t('queue.loading')}

) : playlists.length === 0 ? (

{t('queue.noPlaylists')}

) : (
{playlists.filter(p => p.name.toLowerCase().includes(filter.toLowerCase())).map(p => (
{p.name}
))}
)}
{confirmDelete && (
setConfirmDelete(null)} role="dialog" aria-modal="true">
e.stopPropagation()} style={{ maxWidth: '360px' }}>

{t('queue.delete')}

{t('queue.deleteConfirm', { name: confirmDelete.name })}

)} ); } export default function QueuePanel() { const { t } = useTranslation(); const navigate = useNavigate(); const queue = usePlayerStore(s => s.queue); const queueIndex = usePlayerStore(s => s.queueIndex); const currentTrack = usePlayerStore(s => s.currentTrack); const currentTime = usePlayerStore(s => s.currentTime); const isQueueVisible = usePlayerStore(s => s.isQueueVisible); const playTrack = usePlayerStore(s => s.playTrack); const toggleQueue = usePlayerStore(s => s.toggleQueue); const clearQueue = usePlayerStore(s => s.clearQueue); const reorderQueue = usePlayerStore(s => s.reorderQueue); const shuffleQueue = usePlayerStore(s => s.shuffleQueue); const enqueue = usePlayerStore(s => s.enqueue); const enqueueAt = usePlayerStore(s => s.enqueueAt); const contextMenu = usePlayerStore(s => s.contextMenu); const crossfadeEnabled = useAuthStore(s => s.crossfadeEnabled); const crossfadeSecs = useAuthStore(s => s.crossfadeSecs); const gaplessEnabled = useAuthStore(s => s.gaplessEnabled); const setCrossfadeEnabled = useAuthStore(s => s.setCrossfadeEnabled); const setCrossfadeSecs = useAuthStore(s => s.setCrossfadeSecs); const setGaplessEnabled = useAuthStore(s => s.setGaplessEnabled); const activeTab = useLyricsStore(s => s.activeTab); const setTab = useLyricsStore(s => s.setTab); const [showRemainingTime, setShowRemainingTime] = useState(false); const [showCrossfadePopover, setShowCrossfadePopover] = useState(false); const crossfadeBtnRef = useRef(null); const crossfadePopoverRef = useRef(null); useEffect(() => { if (!showCrossfadePopover) return; const handle = (e: MouseEvent) => { if ( crossfadeBtnRef.current?.contains(e.target as Node) || crossfadePopoverRef.current?.contains(e.target as Node) ) return; setShowCrossfadePopover(false); }; document.addEventListener('mousedown', handle); return () => document.removeEventListener('mousedown', handle); }, [showCrossfadePopover]); // Tracks which queue index is being psy-dragged for opacity visual feedback const psyDragFromIdxRef = useRef(null); const queueListRef = useRef(null); const asideRef = useRef(null); const { isDragging: isPsyDragging, startDrag } = useDragDrop(); useEffect(() => { if (!isPsyDragging) { externalDropTargetRef.current = null; setExternalDropTarget(null); } }, [isPsyDragging]); const [externalDropTarget, setExternalDropTarget] = useState<{ idx: number; before: boolean } | null>(null); const externalDropTargetRef = useRef<{ idx: number; before: boolean } | null>(null); // ── Mouse-event DnD: listen for psy-drop custom events ───────── useEffect(() => { const aside = asideRef.current; if (!aside) return; const onPsyDrop = async (e: Event) => { const detail = (e as CustomEvent).detail; if (!detail?.data) return; let parsedData: any = null; try { parsedData = JSON.parse(detail.data); } catch { return; } const dropTarget = externalDropTargetRef.current; externalDropTargetRef.current = null; setExternalDropTarget(null); const insertIdx = dropTarget ? (dropTarget.before ? dropTarget.idx : dropTarget.idx + 1) : usePlayerStore.getState().queue.length; if (parsedData.type === 'queue_reorder') { const fromIdx: number = parsedData.index; psyDragFromIdxRef.current = null; if (fromIdx !== insertIdx) reorderQueue(fromIdx, insertIdx); } else if (parsedData.type === 'song') { enqueueAt([parsedData.track], insertIdx); } else if (parsedData.type === 'album') { const albumData = await getAlbum(parsedData.id); const tracks: Track[] = albumData.songs.map((s: any) => ({ id: s.id, title: s.title, artist: s.artist, album: s.album, albumId: s.albumId, artistId: s.artistId, duration: s.duration, coverArt: s.coverArt, track: s.track, year: s.year, bitRate: s.bitRate, suffix: s.suffix, userRating: s.userRating, genre: s.genre, })); enqueueAt(tracks, insertIdx); } }; aside.addEventListener('psy-drop', onPsyDrop); return () => aside.removeEventListener('psy-drop', onPsyDrop); }, [enqueueAt]); const [activePlaylist, setActivePlaylist] = useState<{ id: string; name: string } | null>(null); const [saveState, setSaveState] = useState<'idle' | 'saving' | 'saved'>('idle'); const [saveModalOpen, setSaveModalOpen] = useState(false); const [loadModalOpen, setLoadModalOpen] = useState(false); const handleSave = async () => { if (queue.length === 0) return; if (activePlaylist) { setSaveState('saving'); try { await updatePlaylist(activePlaylist.id, queue.map(t => t.id)); setSaveState('saved'); setTimeout(() => setSaveState('idle'), 1500); } catch (e) { console.error('Failed to update playlist', e); setSaveState('idle'); } } else { setSaveModalOpen(true); } }; const handleLoad = () => { setLoadModalOpen(true); }; const handleClear = () => { clearQueue(); setActivePlaylist(null); }; return ( ); }