// Global state let currentSearchResults = []; let currentNewsSource = ''; // DOM Elements const searchForm = document.getElementById('searchForm'); const searchInput = document.getElementById('searchInput'); const resultsSection = document.getElementById('resultsSection'); const newsSection = document.getElementById('newsSection'); const searchResults = document.getElementById('searchResults'); const newsResults = document.getElementById('newsResults'); const loading = document.getElementById('loading'); const backToSearch = document.getElementById('backToSearch'); const backToResults = document.getElementById('backToResults'); const newsTitle = document.getElementById('newsTitle'); // Event Listeners document.addEventListener('DOMContentLoaded', function() { searchForm.addEventListener('submit', handleSearch); backToSearch.addEventListener('click', showSearchView); backToResults.addEventListener('click', showResultsView); // Focus search input on page load searchInput.focus(); }); // Search handler async function handleSearch(e) { e.preventDefault(); const query = searchInput.value.trim(); if (!query) return; showLoading(); hideAllSections(); try { const results = await performSearch(query); currentSearchResults = results; displaySearchResults(results); showResultsSection(); } catch (error) { console.error('Search error:', error); showError('Failed to perform search. Please try again.'); } finally { hideLoading(); } } // Perform search using DuckDuckGo Instant Answer API async function performSearch(query) { const response = await fetch(`https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_html=1&skip_disambig=1`); const data = await response.json(); let results = []; // Use RelatedTopics if available if (data.RelatedTopics && data.RelatedTopics.length > 0) { results = data.RelatedTopics .filter(topic => topic.FirstURL && topic.Text) .map(topic => ({ title: topic.Text, url: topic.FirstURL, description: topic.Text })) .slice(0, 10); } // Fallback to Abstract results if (results.length === 0 && data.Abstract) { results.push({ title: data.Heading || query, url: data.AbstractURL || `https://duckduckgo.com/?q=${encodeURIComponent(query)}`, description: data.Abstract }); } return results; } // Display search results function displaySearchResults(results) { searchResults.innerHTML = ''; if (results.length === 0) { searchResults.innerHTML = `
No results found. Try a different search term.
${result.description}
${message}