// main.js
import { downloadQueue } from './queue.js';
document.addEventListener('DOMContentLoaded', function() {
// DOM elements
const searchInput = document.getElementById('searchInput');
const searchButton = document.getElementById('searchButton');
const searchType = document.getElementById('searchType');
const resultsContainer = document.getElementById('resultsContainer');
const queueIcon = document.getElementById('queueIcon');
const emptyState = document.getElementById('emptyState');
const loadingResults = document.getElementById('loadingResults');
// Initialize the queue
if (queueIcon) {
queueIcon.addEventListener('click', () => {
downloadQueue.toggleVisibility();
});
}
// Add event listeners
if (searchButton) {
searchButton.addEventListener('click', performSearch);
}
if (searchInput) {
searchInput.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
performSearch();
}
});
// Auto-detect and handle pasted Spotify URLs
searchInput.addEventListener('input', function(e) {
const inputVal = e.target.value.trim();
if (isSpotifyUrl(inputVal)) {
const details = getSpotifyResourceDetails(inputVal);
if (details) {
searchType.value = details.type;
}
}
});
}
// Restore last search type if no URL override
const savedType = localStorage.getItem('lastSearchType');
if (savedType && ['track','album','playlist','artist'].includes(savedType)) {
searchType.value = savedType;
}
// Save last selection on change
if (searchType) {
searchType.addEventListener('change', () => {
localStorage.setItem('lastSearchType', searchType.value);
});
}
// Check for URL parameters
const urlParams = new URLSearchParams(window.location.search);
const query = urlParams.get('q');
const type = urlParams.get('type');
if (query) {
searchInput.value = query;
if (type && ['track', 'album', 'playlist', 'artist'].includes(type)) {
searchType.value = type;
}
performSearch();
} else {
// Show empty state if no query
showEmptyState(true);
}
/**
* Performs the search based on input values
*/
async function performSearch() {
const query = searchInput.value.trim();
if (!query) return;
// Handle direct Spotify URLs
if (isSpotifyUrl(query)) {
const details = getSpotifyResourceDetails(query);
if (details && details.id) {
// Redirect to the appropriate page
window.location.href = `/${details.type}/${details.id}`;
return;
}
}
// Update URL without reloading page
const newUrl = `${window.location.pathname}?q=${encodeURIComponent(query)}&type=${searchType.value}`;
window.history.pushState({ path: newUrl }, '', newUrl);
// Show loading state
showEmptyState(false);
showLoading(true);
resultsContainer.innerHTML = '';
try {
const url = `/api/search?q=${encodeURIComponent(query)}&search_type=${searchType.value}&limit=40`;
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
// Hide loading indicator
showLoading(false);
// Render results
if (data && data.items && data.items.length > 0) {
resultsContainer.innerHTML = '';
// Filter out items with null/undefined essential display parameters
const validItems = filterValidItems(data.items, searchType.value);
if (validItems.length === 0) {
// No valid items found after filtering
resultsContainer.innerHTML = `
No valid results found for "${query}"
`;
return;
}
validItems.forEach((item, index) => {
const cardElement = createResultCard(item, searchType.value, index);
// Store the item data directly on the button element
const downloadBtn = cardElement.querySelector('.download-btn');
if (downloadBtn) {
downloadBtn.dataset.itemIndex = index;
}
resultsContainer.appendChild(cardElement);
});
// Attach download handlers to the newly created cards
attachDownloadListeners(validItems);
} else {
// No results found
resultsContainer.innerHTML = `