-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
308 lines (265 loc) · 10.8 KB
/
script.js
File metadata and controls
308 lines (265 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
// Global variables
let allCountries = [];
let filteredCountries = [];
let currentTheme = 'light';
// DOM elements
const themeToggle = document.getElementById('themeToggle');
const searchInput = document.getElementById('searchInput');
const regionFilter = document.getElementById('regionFilter');
const countriesGrid = document.getElementById('countriesGrid');
const loading = document.getElementById('loading');
const error = document.getElementById('error');
const countryModal = document.getElementById('countryModal');
const countryDetail = document.getElementById('countryDetail');
const backButton = document.getElementById('backButton');
// API endpoints
const REST_COUNTRIES_API = 'https://restcountries.com/v2/all';
const LOCAL_DATA_PATH = './data.json';
// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
initializeTheme();
setupEventListeners();
loadCountries();
});
// Theme management
function initializeTheme() {
const savedTheme = localStorage.getItem('theme') || 'light';
setTheme(savedTheme);
}
function setTheme(theme) {
currentTheme = theme;
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem('theme', theme);
const themeIcon = themeToggle.querySelector('i');
const themeText = themeToggle.querySelector('span');
if (theme === 'dark') {
themeIcon.className = 'fas fa-sun';
themeText.textContent = 'Light Mode';
} else {
themeIcon.className = 'fas fa-moon';
themeText.textContent = 'Dark Mode';
}
}
function toggleTheme() {
const newTheme = currentTheme === 'light' ? 'dark' : 'light';
setTheme(newTheme);
}
// Event listeners
function setupEventListeners() {
themeToggle.addEventListener('click', toggleTheme);
searchInput.addEventListener('input', handleSearch);
regionFilter.addEventListener('change', handleRegionFilter);
backButton.addEventListener('click', closeCountryDetail);
// Close modal when clicking outside
countryModal.addEventListener('click', function(e) {
if (e.target === countryModal) {
closeCountryDetail();
}
});
// Close modal with Escape key
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape' && countryModal.classList.contains('active')) {
closeCountryDetail();
}
});
}
// Data loading
async function loadCountries() {
showLoading();
try {
// Try to fetch from REST Countries API first
const response = await fetch(REST_COUNTRIES_API);
if (!response.ok) {
throw new Error('API request failed');
}
allCountries = await response.json();
} catch (apiError) {
console.warn('Failed to fetch from API, falling back to local data:', apiError);
try {
// Fallback to local data
const response = await fetch(LOCAL_DATA_PATH);
if (!response.ok) {
throw new Error('Local data request failed');
}
allCountries = await response.json();
} catch (localError) {
console.error('Failed to load local data:', localError);
showError();
return;
}
}
filteredCountries = [...allCountries];
hideLoading();
renderCountries();
}
// UI state management
function showLoading() {
loading.style.display = 'block';
error.style.display = 'none';
countriesGrid.style.display = 'none';
}
function hideLoading() {
loading.style.display = 'none';
countriesGrid.style.display = 'grid';
}
function showError() {
loading.style.display = 'none';
error.style.display = 'block';
countriesGrid.style.display = 'none';
}
// Search and filter functionality
function handleSearch(e) {
const searchTerm = e.target.value.toLowerCase().trim();
applyFilters(searchTerm, regionFilter.value);
}
function handleRegionFilter(e) {
const selectedRegion = e.target.value;
applyFilters(searchInput.value.toLowerCase().trim(), selectedRegion);
}
function applyFilters(searchTerm, selectedRegion) {
filteredCountries = allCountries.filter(country => {
const matchesSearch = !searchTerm ||
country.name.toLowerCase().includes(searchTerm) ||
(country.capital && country.capital.toLowerCase().includes(searchTerm));
const matchesRegion = !selectedRegion || country.region === selectedRegion;
return matchesSearch && matchesRegion;
});
renderCountries();
}
// Rendering functions
function renderCountries() {
if (filteredCountries.length === 0) {
countriesGrid.innerHTML = `
<div class="no-results">
<p>No countries found matching your criteria.</p>
</div>
`;
return;
}
countriesGrid.innerHTML = filteredCountries.map(country => createCountryCard(country)).join('');
// Add click event listeners to country cards
const countryCards = document.querySelectorAll('.country-card');
countryCards.forEach((card, index) => {
card.addEventListener('click', () => showCountryDetail(filteredCountries[index]));
});
}
function createCountryCard(country) {
const flagUrl = country.flags?.png || country.flag || 'https://via.placeholder.com/320x160?text=No+Flag';
const countryName = country.name || 'Unknown Country';
const population = formatNumber(country.population);
const region = country.region || 'Unknown Region';
const capital = country.capital || 'N/A';
return `
<div class="country-card">
<img src="${flagUrl}" alt="${countryName} flag" class="country-flag" loading="lazy" onerror="this.src='https://via.placeholder.com/320x160?text=No+Flag'">
<div class="country-info">
<h3 class="country-name">${countryName}</h3>
<div class="country-details">
<p class="country-detail-item">
<span class="country-detail-label">Population:</span> ${population}
</p>
<p class="country-detail-item">
<span class="country-detail-label">Region:</span> ${region}
</p>
<p class="country-detail-item">
<span class="country-detail-label">Capital:</span> ${capital}
</p>
</div>
</div>
</div>
`;
}
// Country detail modal
function showCountryDetail(country) {
const detailHTML = createCountryDetailHTML(country);
countryDetail.innerHTML = detailHTML;
countryModal.classList.add('active');
document.body.style.overflow = 'hidden';
// Add event listeners to border country buttons
const borderButtons = document.querySelectorAll('.border-country');
borderButtons.forEach(button => {
button.addEventListener('click', () => {
const borderCode = button.dataset.code;
const borderCountry = allCountries.find(c => c.alpha3Code === borderCode);
if (borderCountry) {
showCountryDetail(borderCountry);
}
});
});
}
function closeCountryDetail() {
countryModal.classList.remove('active');
document.body.style.overflow = 'auto';
}
function createCountryDetailHTML(country) {
const flagUrl = country.flags?.png || country.flag || 'https://via.placeholder.com/560x315?text=No+Flag';
const countryName = country.name || 'Unknown Country';
const nativeName = country.nativeName || country.name || 'Unknown';
const population = formatNumber(country.population);
const region = country.region || 'Unknown Region';
const subregion = country.subregion || 'N/A';
const capital = country.capital || 'N/A';
const currencies = country.currencies ?
country.currencies.map(c => c.name).join(', ') : 'N/A';
const languages = country.languages ?
country.languages.map(l => l.name).join(', ') : 'N/A';
const topLevelDomain = country.topLevelDomain ?
country.topLevelDomain.join(', ') : 'N/A';
const borderCountries = country.borders ?
country.borders.map(borderCode => {
const borderCountry = allCountries.find(c => c.alpha3Code === borderCode);
return borderCountry ?
`<button class="border-country" data-code="${borderCode}">${borderCountry.name}</button>` : '';
}).filter(Boolean).join('') : '';
return `
<div class="country-detail">
<img src="${flagUrl}" alt="${countryName} flag" class="country-detail-flag" onerror="this.src='https://via.placeholder.com/560x315?text=No+Flag'">
<div class="country-detail-info">
<h2>${countryName}</h2>
<div class="country-detail-content">
<div class="country-detail-section">
<p class="country-detail-item">
<span class="country-detail-label">Native Name:</span> ${nativeName}
</p>
<p class="country-detail-item">
<span class="country-detail-label">Population:</span> ${population}
</p>
<p class="country-detail-item">
<span class="country-detail-label">Region:</span> ${region}
</p>
<p class="country-detail-item">
<span class="country-detail-label">Sub Region:</span> ${subregion}
</p>
<p class="country-detail-item">
<span class="country-detail-label">Capital:</span> ${capital}
</p>
</div>
<div class="country-detail-section">
<p class="country-detail-item">
<span class="country-detail-label">Top Level Domain:</span> ${topLevelDomain}
</p>
<p class="country-detail-item">
<span class="country-detail-label">Currencies:</span> ${currencies}
</p>
<p class="country-detail-item">
<span class="country-detail-label">Languages:</span> ${languages}
</p>
</div>
</div>
${borderCountries ? `
<div class="border-countries">
<h3>Border Countries:</h3>
<div class="border-list">
${borderCountries}
</div>
</div>
` : ''}
</div>
</div>
`;
}
// Utility functions
function formatNumber(num) {
if (typeof num !== 'number') return 'N/A';
return num.toLocaleString();
}