aboutsummaryrefslogtreecommitdiff
path: root/script.js
blob: 19e5011b147f30a5c8aa92a5a21b8e867245d9f0 (plain)
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
/**
 * @typedef {Object} WordleData
 * @property {number} id
 * @property {string} solution
 * @property {string} print_date
 * @property {number} [days_since_launch]
 * @property {string} [editor]
 */

const moonIconPath = 'M21.752 15.002A9.72 9.72 0 0 1 18 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 0 0 3 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 0 0 9.002-5.998Z';
const sunIconPath = 'M12 3v2.25m6.364.386-1.591 1.591M21 12h-2.25m-.386 6.364-1.591-1.591M12 18.75V21m-4.773-4.227-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0Z';

const themeToggle = document.getElementById('themeToggle');
const themeIcon = document.getElementById('themeIcon');
const themeText = document.getElementById('themeText');
const html = document.documentElement;

/**
 * @param {string} theme
 * @returns {void}
 */
function setTheme(theme) {
    html.setAttribute('data-theme', theme);
    localStorage.setItem('theme', theme);
    if (theme === 'dark') {
        themeIcon.innerHTML = `<path stroke-linecap="round" stroke-linejoin="round" d="${sunIconPath}"/>`;
        themeText.textContent = 'Light Mode';
    } else {
        themeIcon.innerHTML = `<path stroke-linecap="round" stroke-linejoin="round" d="${moonIconPath}"/>`;
        themeText.textContent = 'Dark Mode';
    }
}

/**
 * @returns {string}
 */
function getInitialTheme() {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) return savedTheme;
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
        return 'dark';
    }
    return 'light';
}

setTheme(getInitialTheme());

if (window.matchMedia) {
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
        if (!localStorage.getItem('theme')) {
            setTheme(e.matches ? 'dark' : 'light');
        }
    });
}

themeToggle.addEventListener('click', () => {
    const currentTheme = html.getAttribute('data-theme');
    setTheme(currentTheme === 'dark' ? 'light' : 'dark');
});

/**
 * @param {Date} date
 * @returns {string}
 */
function formatDateForAPI(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

/**
 * @param {Date} date
 * @returns {string}
 */
function formatDateForDisplay(date) {
    return date.toLocaleDateString('en-US', { 
        weekday: 'long', 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric' 
    });
}

/**
 * @param {string} dateStr
 * @returns {Date|null}
 */
function parseDateParam(dateStr) {
    const parts = dateStr.split('-');
    if (parts.length !== 3) return null;
    const [day, month, year] = parts.map(Number);
    if (isNaN(day) || isNaN(month) || isNaN(year)) return null;
    return new Date(year, month - 1, day);
}

/**
 * @returns {Date}
 */
function getMaxAllowedDate() {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const maxDate = new Date(today);
    maxDate.setDate(maxDate.getDate() + 21);
    return maxDate;
}

/**
 * @returns {Date}
 */
function getWordleLaunchDate() {
    const launchDate = new Date(2021, 5, 19);
    launchDate.setHours(0, 0, 0, 0);
    return launchDate;
}

/**
 * @param {Date} date
 * @returns {boolean}
 */
function isDateAllowed(date) {
    const maxDate = getMaxAllowedDate();
    const launchDate = getWordleLaunchDate();
    return date >= launchDate && date <= maxDate;
}

const urlParams = new URLSearchParams(window.location.search);
const dateParam = urlParams.get('date');
let selectedDate = dateParam ? parseDateParam(dateParam) : new Date();
if (!selectedDate || isNaN(selectedDate.getTime())) {
    selectedDate = new Date();
}
selectedDate.setHours(0, 0, 0, 0);

let currentCalendarMonth = new Date(selectedDate);
currentCalendarMonth.setDate(1);

/** @type {WordleData|null} */
let currentAnswer = null;

const months = ['January', 'February', 'March', 'April', 'May', 'June', 
               'July', 'August', 'September', 'October', 'November', 'December'];

const monthSelect = document.getElementById('monthSelect');
const monthDisplay = document.getElementById('monthDisplay');
const monthDropdown = document.getElementById('monthDropdown');
const yearSelect = document.getElementById('yearSelect');
const yearDisplay = document.getElementById('yearDisplay');
const yearDropdown = document.getElementById('yearDropdown');

months.forEach((month, idx) => {
    const option = document.createElement('div');
    option.className = 'select-option';
    option.textContent = month;
    option.dataset.value = idx.toString();
    option.addEventListener('click', () => {
        currentCalendarMonth.setMonth(idx);
        monthDisplay.textContent = month;
        closeAllDropdowns();
        renderCalendar();
    });
    monthDropdown.appendChild(option);
});

const launchYear = getWordleLaunchDate().getFullYear();
const maxAllowedYear = getMaxAllowedDate().getFullYear();
for (let year = launchYear; year <= maxAllowedYear; year++) {
    const option = document.createElement('div');
    option.className = 'select-option';
    option.textContent = year.toString();
    option.dataset.value = year.toString();
    option.addEventListener('click', () => {
        currentCalendarMonth.setFullYear(year);
        yearDisplay.textContent = year.toString();
        closeAllDropdowns();
        renderCalendar();
    });
    yearDropdown.appendChild(option);
}

monthSelect.querySelector('.select-display').addEventListener('click', (e) => {
    e.stopPropagation();
    const isOpen = monthDropdown.classList.contains('open');
    closeAllDropdowns();
    if (!isOpen) {
        monthDropdown.classList.add('open');
        monthSelect.querySelector('.select-display').classList.add('open');
    }
});

yearSelect.querySelector('.select-display').addEventListener('click', (e) => {
    e.stopPropagation();
    const isOpen = yearDropdown.classList.contains('open');
    closeAllDropdowns();
    if (!isOpen) {
        yearDropdown.classList.add('open');
        yearSelect.querySelector('.select-display').classList.add('open');
    }
});

/**
 * @returns {void}
 */
function closeAllDropdowns() {
    monthDropdown.classList.remove('open');
    yearDropdown.classList.remove('open');
    monthSelect.querySelector('.select-display').classList.remove('open');
    yearSelect.querySelector('.select-display').classList.remove('open');
}

document.addEventListener('click', closeAllDropdowns);

/**
 * @param {Date} date
 * @returns {Promise<WordleData>}
 */
async function fetchWordleAnswer(date) {
    const apiDate = formatDateForAPI(date);
    const url = `https://www.nytimes.com/svc/wordle/v2/${apiDate}.json`;
    
    const response = await fetch(url);
    if (!response.ok) {
        throw new Error('Answer not available for this date');
    }
    return await response.json();
}

/**
 * @param {WordleData} data
 * @param {Date} date
 * @returns {void}
 */
function displayAnswer(data, date) {
    const dateLabel = document.getElementById('dateLabel');
    const answerDisplay = document.getElementById('answerDisplay');
    const metaInfo = document.getElementById('metaInfo');
    const errorContainer = document.getElementById('errorContainer');
    const answerPreview = document.getElementById('answerPreview');

    errorContainer.innerHTML = '';
    dateLabel.textContent = formatDateForDisplay(date);
    currentAnswer = data;

    const letters = data.solution.toUpperCase().split('');
    answerDisplay.innerHTML = letters.map(letter => 
        `<div class="letter-box">${letter}</div>`
    ).join('');

    answerPreview.textContent = data.solution.toUpperCase();

    const daysSinceLaunch = data.days_since_launch !== undefined ? data.days_since_launch : 0;
    const editor = data.editor || '---';

    metaInfo.innerHTML = `
        <div class="meta-item">
            <div class="meta-label">Puzzle #</div>
            <div class="meta-value">${data.id}</div>
        </div>
        <div class="meta-item">
            <div class="meta-label">Days Since Launch</div>
            <div class="meta-value">${daysSinceLaunch}</div>
        </div>
        <div class="meta-item">
            <div class="meta-label">Editor</div>
            <div class="meta-value">${editor}</div>
        </div>
    `;
}

/**
 * @param {string} message
 * @returns {void}
 */
function showError(message) {
    const errorContainer = document.getElementById('errorContainer');
    errorContainer.innerHTML = `<div class="error">⚠️ ${message}</div>`;
}

/**
 * @param {string} message
 * @returns {void}
 */
function showToast(message) {
    const toast = document.createElement('div');
    toast.className = 'success-toast';
    toast.innerHTML = `
        <svg style="width: 20px; height: 20px; stroke: currentColor; fill: none; stroke-width: 1.5;" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" d="m4.5 12.75 6 6 9-13.5" />
        </svg>
        ${message}
    `;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 3000);
}

/**
 * @param {WordleData} data
 * @param {Date} date
 * @returns {Promise<void>}
 */
async function updateMetaTags(data, date) {
    const isToday = date.toDateString() === new Date().toDateString();
    const dateStr = formatDateForDisplay(date);
    const answer = data.solution.toUpperCase();
    
    let title, description;
    if (isToday) {
        title = `Today's Wordle Answer is ${answer} - Unwordled`;
        description = `Today's Wordle #${data.id} answer is ${answer}! Find daily Wordle solutions on Unwordled.`;
    } else {
        title = `Wordle Answer for ${dateStr} is ${answer} - Unwordled`;
        description = `Wordle #${data.id} answer for ${dateStr} is ${answer}. Discover past and future Wordle answers on Unwordled.`;
    }

    document.title = title;
    document.querySelector('meta[property="og:title"]').setAttribute('content', title);
    document.querySelector('meta[property="og:description"]').setAttribute('content', description);
    document.querySelector('meta[name="twitter:title"]').setAttribute('content', title);
    document.querySelector('meta[name="twitter:description"]').setAttribute('content', description);
    document.querySelector('meta[name="description"]').setAttribute('content', description);
    
    if (typeof window.generateOGImage === 'function') {
        const ogImageDataUrl = await window.generateOGImage(data, date);
        document.querySelector('meta[property="og:image"]').setAttribute('content', ogImageDataUrl);
        document.querySelector('meta[name="twitter:image"]').setAttribute('content', ogImageDataUrl);
    }
}

/**
 * @param {Date} date
 * @returns {Promise<void>}
 */
async function loadAnswer(date) {
    try {
        const data = await fetchWordleAnswer(date);
        displayAnswer(data, date);
        await updateMetaTags(data, date);
    } catch (error) {
        showError(error.message);
        document.getElementById('answerDisplay').innerHTML = 
            '<div class="loading">Unable to load answer</div>';
    }
}

/**
 * @returns {void}
 */
function updateURL() {
    const day = String(selectedDate.getDate()).padStart(2, '0');
    const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
    const year = selectedDate.getFullYear();
    const dateStr = `${day}-${month}-${year}`;
    const newUrl = `${window.location.pathname}?date=${dateStr}`;
    window.history.pushState({}, '', newUrl);
}

document.getElementById('shareBtn').addEventListener('click', async () => {
    if (!currentAnswer) return;

    const day = String(selectedDate.getDate()).padStart(2, '0');
    const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
    const year = selectedDate.getFullYear();
    const dateStr = `${day}-${month}-${year}`;
    const shareUrl = `${window.location.origin}${window.location.pathname}?date=${dateStr}`;
    const shareText = `Wordle #${currentAnswer.id} answer: ${currentAnswer.solution.toUpperCase()} - Found on Unwordled`;

    if (navigator.share) {
        try {
            await navigator.share({
                title: 'Unwordled',
                text: shareText,
                url: shareUrl
            });
        } catch (err) {
            if (err.name !== 'AbortError') {
                copyToClipboard(shareUrl);
            }
        }
    } else {
        copyToClipboard(shareUrl);
    }
});

document.getElementById('copyAnswerBtn').addEventListener('click', () => {
    if (!currentAnswer) return;
    const text = currentAnswer.solution.toUpperCase();
    copyToClipboard(text);
});

/**
 * @param {string} text
 * @returns {void}
 */
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        showToast('Copied to clipboard!');
    }).catch(() => {
        showToast('Failed to copy');
    });
}

/**
 * @returns {void}
 */
function renderCalendar() {
    const calendarDays = document.getElementById('calendarDays');

    const year = currentCalendarMonth.getFullYear();
    const month = currentCalendarMonth.getMonth();

    monthDisplay.textContent = months[month];
    yearDisplay.textContent = year.toString();

    const firstDay = new Date(year, month, 1).getDay();
    const daysInMonth = new Date(year, month + 1, 0).getDate();
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const maxDate = getMaxAllowedDate();
    const launchDate = getWordleLaunchDate();

    calendarDays.innerHTML = '';

    for (let i = 0; i < firstDay; i++) {
        calendarDays.innerHTML += '<div class="day-cell empty"></div>';
    }

    for (let day = 1; day <= daysInMonth; day++) {
        const cellDate = new Date(year, month, day);
        cellDate.setHours(0, 0, 0, 0);
        const isSelected = cellDate.getTime() === selectedDate.getTime();
        const isToday = cellDate.getTime() === today.getTime();
        const isDisabled = cellDate > maxDate || cellDate < launchDate;

        const classes = ['day-cell'];
        if (isSelected) classes.push('selected');
        if (isToday) classes.push('today');
        if (isDisabled) classes.push('disabled');

        const dayCell = document.createElement('div');
        dayCell.className = classes.join(' ');
        dayCell.textContent = day.toString();
        
        if (!isDisabled) {
            dayCell.addEventListener('click', () => {
                selectedDate = new Date(year, month, day);
                selectedDate.setHours(0, 0, 0, 0);
                loadAnswer(selectedDate);
                renderCalendar();
                updateURL();
            });
        }

        calendarDays.appendChild(dayCell);
    }
}

document.getElementById('prevMonth').addEventListener('click', () => {
    currentCalendarMonth.setMonth(currentCalendarMonth.getMonth() - 1);
    renderCalendar();
});

document.getElementById('nextMonth').addEventListener('click', () => {
    currentCalendarMonth.setMonth(currentCalendarMonth.getMonth() + 1);
    renderCalendar();
});

document.getElementById('todayBtn').addEventListener('click', () => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    selectedDate = today;
    currentCalendarMonth = new Date(today);
    currentCalendarMonth.setDate(1);
    loadAnswer(selectedDate);
    renderCalendar();
    updateURL();
});

loadAnswer(selectedDate);
renderCalendar();