import {ANALYSIS_THEMES,analysisTheme,analysisAccent} from './statistics-analysis-themes.mjs'; import {renderAnalysisChart} from './statistics-analysis-chart.mjs'; import { isJournalStatistics, pullJournalRevision, pullJournalStatistics, websiteApiBase } from '../account/data/account-api.mjs'; import { loadAccountConfig } from '../account/domain/account-config.mjs'; import { getCurrentAccountSession } from '../account/ui/account-control.mjs'; import { getLocale, t } from '../../shared/i18n.mjs'; import { statisticsInitialDateRange } from './statistics-date.mjs'; import { clearStatisticsCache, readStatisticsCache, writeStatisticsCache } from './statistics-cache.mjs'; import { productiveMonthRange } from './statistics-monthly.mjs'; import { retainedStatisticsPlaceId, retainedStatisticsSpeciesId, } from './statistics-filter-state.mjs'; const elements = { disconnected: document.querySelector('#statistics-disconnected'), loading: document.querySelector('#statistics-loading'), error: document.querySelector('#statistics-error'), dashboard: document.querySelector('#statistics-dashboard'), retry: document.querySelector('#statistics-retry'), form: document.querySelector('#statistics-period-form'), place: document.querySelector('#statistics-place'), mode: document.querySelector('#statistics-period-mode'), dateFields: document.querySelector('#statistics-date-fields'), from: document.querySelector('#statistics-from'), to: document.querySelector('#statistics-to'), donut: document.querySelector('#statistics-donut'), fish: document.querySelector('#statistics-fish'), effortOutings: document.querySelector('#statistics-effort-outings'), success: document.querySelector('#statistics-success'), successRate: document.querySelector('#statistics-success-rate'), blanks: document.querySelector('#statistics-blanks'), blankRate: document.querySelector('#statistics-blank-rate'), effort: document.querySelector('#statistics-effort'), effortAverage: document.querySelector('#statistics-effort-average'), chart: document.querySelector('#statistics-chart'), bestMonth: document.querySelector('#statistics-best-month'), bestMonthCopy: document.querySelector('#statistics-best-month-copy'), averageDelta: document.querySelector('#statistics-average-delta'), productivePeriod: document.querySelector('#statistics-productive-period'), speciesGrid: document.querySelector('#statistics-species-grid'), speciesCount: document.querySelector('#statistics-species-count'), speciesReset: document.querySelector('#statistics-species-reset'), speciesStatus: document.querySelector('#statistics-species-status'), monthlyScope: document.querySelector('#statistics-monthly-scope'), monthlySpecies: document.querySelector('#statistics-monthly-species'), speciesEmpty: document.querySelector('#statistics-species-empty'), analysisGrid: document.querySelector('#statistics-analysis-grid'), analysisEmpty: document.querySelector('#statistics-analysis-empty'), analysisTabs: document.querySelector('#statistics-analysis-tabs'), }; const SPECIES_NAMES = { 'ablette': { fr: 'Ablette', en: 'Bleak' }, 'breme-commune': { fr: 'Brème commune', en: 'Common bream' }, 'brochet': { fr: 'Brochet', en: 'Northern pike' }, 'common-carp': { fr: 'Carpe commune', en: 'Common carp' }, 'carpe-commune': { fr: 'Carpe commune', en: 'Common carp' }, 'gardon': { fr: 'Gardon', en: 'Roach' }, 'goujon': { fr: 'Goujon', en: 'Gudgeon' }, 'perche-commune': { fr: 'Perche commune', en: 'European perch' }, 'tanche': { fr: 'Tanche', en: 'Tench' }, }; let activeSession = null; let activeAccountId = null; let activeRequest = 0; let activeRequestController = null; let lastStatistics = null; let apiBasePromise = null; let refreshTimer = null; let backgroundRefreshes = 0; let unchangedRefreshes = 0; let lastJournalRevision = null; let lastStatisticsQuery = null; const statisticsQueryResults = new Map(); let renderGeneration = 0; let lastStatisticsSignature = null; let selectedAnalysisTheme = 'airTemperature'; let selectedSpeciesId = null; let selectedPlaceId = null; const ANALYSIS_TITLES = { pressure: { fr: 'Pression atmosphérique', en: 'Atmospheric pressure' }, airTemperature: { fr: 'Température de l’air', en: 'Air temperature' }, waterTemperature: { fr: 'Température de l’eau', en: 'Water temperature' }, windSpeed: { fr: 'Vitesse du vent', en: 'Wind speed' }, windDirection: { fr: 'Direction du vent', en: 'Wind direction' }, windGust: { fr: 'Rafales', en: 'Wind gusts' }, precipitation: { fr: 'Précipitations', en: 'Precipitation' }, cloudCover: { fr: 'Nébulosité', en: 'Cloud cover' }, humidity: { fr: 'Humidité', en: 'Humidity' }, hour: { fr: 'Heure de pêche', en: 'Fishing time' }, dayPeriod: { fr: 'Luminosité jour / nuit', en: 'Day / night light' }, }; const FAST_BACKGROUND_REFRESH_DELAY_MS = 8_000; const IDLE_BACKGROUND_REFRESH_DELAY_MS = 60_000; const MAX_INITIAL_FAST_REFRESHES = 60; const MAX_UNCHANGED_REFRESHES = 12; function apiBase() { apiBasePromise ??= loadAccountConfig().then((config) => websiteApiBase(window.location, config.apiBase)); return apiBasePromise; } function showState(name) { for (const key of ['disconnected', 'loading', 'error', 'dashboard']) { elements[key].hidden = key !== name; } } function period() { return elements.mode.value === 'custom' ? { from: elements.from.value, to: elements.to.value } : null; } function localeTag() { return getLocale() === 'en' ? 'en-GB' : 'fr-FR'; } function number(value, maximumFractionDigits = 0) { return new Intl.NumberFormat(localeTag(), { maximumFractionDigits }).format(value); } function hours(minutes) { if (minutes < 60) return t('statistics.minutes', { value: number(minutes) }); const value = minutes / 60; return t('statistics.hours', { value: number(value, value < 10 && value % 1 ? 1 : 0) }); } function percentage(part, total) { return total > 0 ? Math.round((part / total) * 100) : 0; } function monthName(month, style = 'short') { return new Intl.DateTimeFormat(localeTag(), { month: style, timeZone: 'UTC' }) .format(new Date(Date.UTC(2026, month - 1, 1))).replace('.', ''); } function speciesName(speciesId) { return SPECIES_NAMES[speciesId]?.[getLocale()] ?? speciesId.replaceAll('-', ' ').replace(/^./, (letter) => letter.toUpperCase()); } function speciesArtwork(speciesId) { return new URL(`../../assets/fish/${encodeURIComponent(speciesId)}.png`, import.meta.url).href; } function renderSummary(statistics) { const { summary } = statistics; const completedOutings = summary.successfulOutings + summary.blankOutings; const successRate = percentage(summary.successfulOutings, completedOutings); elements.fish.textContent = number(summary.fish); elements.effortOutings.textContent = t('statistics.effortOutings', { effort: hours(summary.effortMinutes), outings: number(summary.outings), }); elements.success.textContent = number(summary.successfulOutings); elements.successRate.textContent = t('statistics.successRate', { value: successRate }); elements.blanks.textContent = number(summary.blankOutings); elements.blankRate.textContent = t('statistics.rate', { value: percentage(summary.blankOutings, completedOutings), }); elements.effort.textContent = hours(summary.effortMinutes); elements.effortAverage.textContent = t('statistics.effortAverage', { value: summary.outings > 0 ? hours(Math.round(summary.effortMinutes / summary.outings)) : hours(0), }); elements.donut.style.setProperty('--success-angle', `${successRate * 3.6}deg`); } function productiveRange(monthly, average) { const range = productiveMonthRange(monthly, average); if (!range) return null; return range.start === range.end ? monthName(range.start, 'long') : `${monthName(range.start, 'short')} → ${monthName(range.end, 'short')}`; } function renderChart(statistics) { const filtered = statistics.filters.speciesId !== null; const globalQuery = JSON.stringify([statistics.period.from === null ? null : statistics.period, statistics.filters.placeId, null]); const reference = filtered ? statisticsQueryResults.get(activeSession?.user.id + '/' + globalQuery)?.statistics : statistics; const totals = reference?.monthly ?? null; const totalFor = entry => totals?.find(month => month.month === entry.month)?.fish ?? null; elements.chart.dataset.filtered = String(filtered); document.querySelector('#statistics-monthly-total-heading').hidden = !filtered; const legend = document.querySelector('#statistics-monthly-legend'); legend.dataset.filtered = String(filtered); legend.querySelector('[data-selected-species]').textContent = filtered ? speciesName(statistics.filters.speciesId) : ''; const table = document.querySelector('#statistics-monthly-table tbody'); table.replaceChildren(); for (const entry of statistics.monthly) { const row = document.createElement('tr'); const label = document.createElement('th'); label.scope = 'row'; label.textContent = monthName(entry.month, 'long'); const count = document.createElement('td'); count.textContent = number(entry.fish); const total = document.createElement('td'); total.textContent = totals ? number(totalFor(entry)) : '—'; total.hidden = !filtered; row.append(label, count, total); table.append(row); } const maximum = Math.max(...statistics.monthly.map((entry) => entry.fish), ...(totals ?? []).map(entry => entry.fish), 0); const filteredMaximum = Math.max(...statistics.monthly.map(entry => entry.fish),0); const best = statistics.monthly.find((entry) => entry.fish === filteredMaximum) ?? null; elements.chart.replaceChildren(); for (const entry of statistics.monthly) { const column = document.createElement('div'); column.className = 'statistics-bar-column'; column.dataset.best = String(entry.fish > 0 && entry.fish === filteredMaximum); const value = document.createElement('strong'); value.textContent = number(entry.fish); const track = document.createElement('div'); track.className = 'statistics-bar-track'; const bar = document.createElement('span'); bar.className = 'statistics-bar'; bar.style.setProperty('--bar-height', `${maximum > 0 ? (filtered ? entry.fish / maximum * 100 : Math.max(2, entry.fish / maximum * 100)) : 0}%`); bar.title = t('statistics.chart.point', { month: monthName(entry.month, 'long'), fish: entry.fish }); if (filtered && totals) { const background = document.createElement('span');background.className = 'statistics-bar-total'; background.style.setProperty('--bar-height', (maximum > 0 ? totalFor(entry) / maximum * 100 : 0) + '%'); background.title = (getLocale() === 'en' ? 'All species: ' : 'Toutes espèces : ') + number(totalFor(entry)); const totalCount = document.createElement('small');totalCount.className = 'statistics-bar-total-count';totalCount.textContent = number(totalFor(entry)); track.append(background,totalCount); } track.append(bar); const label = document.createElement('span'); label.className = 'statistics-bar-label'; label.textContent = monthName(entry.month); column.append(value, track, label); elements.chart.append(column); } const documented = statistics.monthly.filter((entry) => entry.fish > 0); const average = documented.length ? documented.reduce((sum, entry) => sum + entry.fish, 0) / documented.length : 0; elements.bestMonth.textContent = best && best.fish > 0 ? t('statistics.bestMonth', { month: monthName(best.month, 'long') }) : '—'; elements.bestMonthCopy.textContent = best ? t('statistics.fishCount', { value: number(best.fish) }) : t('statistics.fishCount', { value: 0 }); const delta = best && average > 0 ? Math.round((best.fish / average - 1) * 100) : 0; elements.averageDelta.textContent = delta > 0 ? `+${number(delta)} %` : '—'; elements.productivePeriod.textContent = productiveRange(statistics.monthly, average) ?? '—'; } function renderSpecies(statistics) { elements.speciesGrid.replaceChildren(); const allSpecies = document.createElement('option'); allSpecies.value = ''; allSpecies.textContent = getLocale() === 'en' ? 'All species in your logbook' : 'Toutes les espèces de votre carnet'; elements.monthlySpecies.replaceChildren(allSpecies); for (const species of statistics.species) { const option = document.createElement('option');option.value = species.speciesId;option.textContent = speciesName(species.speciesId);elements.monthlySpecies.append(option); } elements.monthlySpecies.value = selectedSpeciesId ?? ''; elements.speciesCount.textContent = number(statistics.species.length); elements.speciesEmpty.hidden = statistics.species.length > 0 || selectedSpeciesId !== null; elements.speciesReset.hidden = selectedSpeciesId === null; const selectedMissing = selectedSpeciesId !== null && !statistics.species.some((species) => species.speciesId === selectedSpeciesId); const displaySpecies = selectedMissing ? [{ speciesId: selectedSpeciesId, fish: 0, favorite: false }, ...statistics.species] : statistics.species; for (const species of displaySpecies) { const card = document.createElement('button'); card.type = 'button'; card.className = 'statistics-species-card'; const selected = species.speciesId === selectedSpeciesId; card.dataset.selected = String(selected); card.setAttribute('aria-pressed', String(selected)); card.setAttribute('aria-label', t('statistics.species.filter', { species: speciesName(species.speciesId), })); if (species.favorite) { const favorite = document.createElement('span'); favorite.className = 'species-favorite'; favorite.setAttribute('aria-label', t('statistics.favorite')); favorite.textContent = '★'; card.append(favorite); } const mark = document.createElement('span'); mark.className = 'species-mark'; mark.setAttribute('aria-hidden', 'true'); mark.textContent = '≈'; const artwork = document.createElement('img'); artwork.className = 'species-artwork'; artwork.alt = ''; artwork.loading = 'lazy'; artwork.decoding = 'async'; artwork.src = speciesArtwork(species.speciesId); artwork.addEventListener('error', () => { card.dataset.artworkError = 'true'; }, { once: true }); const name = document.createElement('b'); name.textContent = speciesName(species.speciesId); const count = document.createElement('small'); count.textContent = t('statistics.fishCount', { value: number(species.fish) }); card.append(artwork, mark, name, count); card.addEventListener('click', () => { selectedSpeciesId = selected ? null : species.speciesId; if (lastStatistics) renderSpecies(lastStatistics); void loadStatistics(activeSession, { preserve: true }); }); elements.speciesGrid.append(card); } } function renderPlaces(statistics) { const previousSelectedLabel = elements.place.selectedOptions[0]?.textContent ?? null; const all = document.createElement('option'); all.value = ''; all.textContent = t('statistics.place.all'); elements.place.replaceChildren(all); for (const place of statistics.places) { const option = document.createElement('option'); option.value = place.placeId; option.textContent = `${place.label} · ${t('statistics.fishCount', { value: number(place.fish) })}`; elements.place.append(option); } if (selectedPlaceId !== null && !statistics.places.some((place) => place.placeId === selectedPlaceId)) { const selected = document.createElement('option'); selected.value = selectedPlaceId; selected.textContent = previousSelectedLabel || selectedPlaceId; elements.place.append(selected); } elements.place.value = selectedPlaceId ?? ''; } function renderAnalyses(statistics) { elements.analysisGrid.replaceChildren(); const analysisOrder = ANALYSIS_THEMES.flatMap(theme => theme.metrics); const analyses = [...statistics.analyses].sort((a,b) => analysisOrder.indexOf(a.id) - analysisOrder.indexOf(b.id)); elements.analysisGrid.hidden = false; const speciesPanel = document.querySelector('.statistics-lower-grid'); speciesPanel.hidden = false; for (const button of elements.analysisTabs.querySelectorAll('button')) { const theme = button.dataset.analysisTarget ?? (button.hasAttribute('data-analysis-species') ? 'species' : 'all'); button.setAttribute('aria-pressed', String(theme === selectedAnalysisTheme)); } elements.analysisEmpty.hidden = analyses.some((analysis) => analysis.documentedFish > 0); const groups = new Map(); const orderedThemes = [...ANALYSIS_THEMES].sort((a,b) => Number(b.id === selectedAnalysisTheme) - Number(a.id === selectedAnalysisTheme)); for (const theme of orderedThemes) { if (!analyses.some(analysis => theme.metrics.includes(analysis.id))) continue; const section = document.createElement('section'), heading = document.createElement('h3'), grid = document.createElement('div'); section.className = 'statistics-theme'; section.dataset.theme = theme.id; section.dataset.selected = String(theme.id === selectedAnalysisTheme); section.style.setProperty('--theme-color', theme.color); heading.className = 'statistics-theme-heading'; heading.textContent = theme.label[getLocale() === 'en' ? 1 : 0]; grid.className = 'statistics-theme-grid';section.append(heading, grid);elements.analysisGrid.append(section);groups.set(theme.id,grid); } const windGroup = document.createElement('section'); windGroup.className = 'statistics-wind-group'; windGroup.setAttribute('aria-label', getLocale() === 'en' ? 'Wind analyses' : 'Analyses du vent'); const windStack = document.createElement('div'); windStack.className = 'statistics-wind-stack'; windGroup.append(windStack); const windIds = new Set(['windSpeed', 'windDirection', 'windGust']); let windInserted = false; for (const analysis of analyses) { const card = document.createElement('article'); card.className = `statistics-analysis-card statistics-analysis-${analysis.id}`; card.id = `statistics-analysis-${analysis.id}`; card.style.setProperty('--analysis-color', analysisAccent(analysis.id)); const heading = document.createElement('header'); const title = document.createElement('h3'); title.textContent = ANALYSIS_TITLES[analysis.id]?.[getLocale()] ?? analysis.id; const coverage = document.createElement('small'); coverage.textContent = t('statistics.analysis.coverage', { value: number(analysis.documentedFish), }); heading.append(title, coverage); const chart = renderAnalysisChart(analysis,{document,locale:getLocale()}); card.dataset.chart=analysis.id==='windDirection'?'radar':'bar'; card.dataset.wide=String(analysis.id==='windDirection'||analysis.buckets.length>6); card.append(heading, chart); const insight = document.createElement('p'); insight.className = 'statistics-analysis-insight'; const best = analysis.buckets.reduce((winner, bucket) => !winner || bucket.fish > winner.fish ? bucket : winner, null); insight.textContent = best && analysis.documentedFish > 0 ? `${number(best.sharePercent)} % · ${best.label}${analysis.id!=='windDirection' && analysis.unit && !best.label.includes(analysis.unit) ? ` ${analysis.unit}` : ''}` : t('statistics.analysis.empty'); card.append(insight); if (windIds.has(analysis.id)) { if (!windInserted) { groups.get('windSpeed').append(windGroup); windInserted = true; } if (analysis.id === 'windDirection') windGroup.append(card); else windStack.append(card); } else groups.get(analysisTheme(analysis.id).id)?.append(card); } } function render(statistics) { lastStatistics = statistics; renderSummary(statistics); renderChart(statistics); renderPlaces(statistics); renderSpecies(statistics); const generation = ++renderGeneration; elements.dashboard.dataset.analysisPending = 'true'; const completeAnalyses = () => { if (generation !== renderGeneration || lastStatistics !== statistics || !activeSession) return; renderAnalyses(statistics); elements.dashboard.dataset.analysisPending = 'false'; }; if (typeof window.requestAnimationFrame === 'function') { window.requestAnimationFrame(() => window.setTimeout(completeAnalyses, 0)); } else completeAnalyses(); elements.dashboard.dataset.filterPending = 'false'; elements.chart.setAttribute('aria-busy','false'); const scope = selectedSpeciesId === null ? (getLocale() === 'en' ? 'All species in your logbook' : 'Toutes les espèces de votre carnet') : speciesName(selectedSpeciesId); elements.speciesStatus.textContent = scope; elements.monthlyScope.textContent = scope; showState('dashboard'); } function cancelBackgroundRefresh({ reset = true } = {}) { if (refreshTimer !== null) window.clearTimeout(refreshTimer); refreshTimer = null; if (reset) { backgroundRefreshes = 0; unchangedRefreshes = 0; lastStatisticsSignature = null; } } function statisticsSignature(statistics) { return JSON.stringify([statistics.summary, statistics.monthly, statistics.species, statistics.places, statistics.analyses]); } function waitingForInitialJournalSync() { return selectedSpeciesId === null && selectedPlaceId === null && elements.mode.value === 'all' && lastStatistics !== null && lastStatistics.summary.fish === 0 && lastStatistics.summary.outings === 0 && lastStatistics.summary.effortMinutes === 0; } function scheduleBackgroundRefresh() { if (!activeSession || document.hidden) return; cancelBackgroundRefresh({ reset: false }); const keepWatchingInitialSync = waitingForInitialJournalSync() && backgroundRefreshes < MAX_INITIAL_FAST_REFRESHES; const delay = keepWatchingInitialSync || unchangedRefreshes < MAX_UNCHANGED_REFRESHES ? FAST_BACKGROUND_REFRESH_DELAY_MS : IDLE_BACKGROUND_REFRESH_DELAY_MS; refreshTimer = window.setTimeout(() => { refreshTimer = null; void loadStatistics(activeSession, { background: true }); }, delay); } async function loadStatistics(session = activeSession, { background = false, preserve = false } = {}) { const requestId = ++activeRequest; activeRequestController?.abort(); activeRequestController = null; if (!background) cancelBackgroundRefresh(); else backgroundRefreshes = Math.min(backgroundRefreshes + 1, MAX_INITIAL_FAST_REFRESHES); activeSession = session; if (session) activeAccountId = session.user.id; if (!background && !preserve) lastStatistics = null; if (!session) { try { clearStatisticsCache(window.sessionStorage); } catch {} cancelBackgroundRefresh(); showState('disconnected'); return; } const selectedPeriod = period(); const cacheQuery = JSON.stringify([selectedPeriod, selectedPlaceId, selectedSpeciesId]); if (preserve && lastStatistics && cacheQuery !== lastStatisticsQuery) { elements.dashboard.dataset.filterPending = 'true'; elements.chart.setAttribute('aria-busy','true'); const scope = selectedSpeciesId === null ? (getLocale() === 'en' ? 'All species' : 'Toutes les espèces') : speciesName(selectedSpeciesId); const pending = (getLocale() === 'en' ? 'Updating: ' : 'Calcul en cours : ') + scope + '…'; elements.speciesStatus.textContent = pending; elements.monthlyScope.textContent = pending; const globalQuery = JSON.stringify([selectedPeriod, selectedPlaceId, null]); const baseline = statisticsQueryResults.get(session.user.id + '/' + globalQuery)?.statistics; if (baseline) renderChart(baseline); } if (selectedPeriod && (!selectedPeriod.from || !selectedPeriod.to || selectedPeriod.from > selectedPeriod.to)) { showState('error'); return; } if ((!background && !preserve) || !lastStatistics) showState('loading'); let restored = false; if (!lastStatistics) { try { const cached = readStatisticsCache(window.sessionStorage, session.user.id, cacheQuery); if (cached && isJournalStatistics(cached.statistics)) { render(cached.statistics); lastJournalRevision = cached.revision; lastStatisticsQuery = cacheQuery; restored = true; } } catch { clearStatisticsCache(window.sessionStorage); lastStatistics = null; } } const controller = new AbortController(); activeRequestController = controller; try { const baseUrl = await apiBase(); // Capture the journal revision before the expensive calculation. A mutation // committed afterwards is then necessarily observed by the next probe. let journalRevision = null; try { journalRevision = (await pullJournalRevision(baseUrl, session.accessToken, { signal: controller.signal })).revision; } catch (error) { // The probe is an optimization. During a rolling deployment, an older // API may not expose it yet; keep the former full-refresh behaviour. if (error instanceof Error && ['request-cancelled', 'algofish-server-401'] .includes(error.message)) throw error; } if (requestId !== activeRequest || session.accessToken !== activeSession?.accessToken) return; const cachedResult = statisticsQueryResults.get(session.user.id + '/' + cacheQuery); if (cachedResult && journalRevision !== null && cachedResult.revision === journalRevision) { lastStatisticsQuery = cacheQuery; lastJournalRevision = journalRevision; render(cachedResult.statistics); scheduleBackgroundRefresh(); return; } if ((background || restored) && lastStatistics !== null && journalRevision !== null && journalRevision === lastJournalRevision && lastStatisticsQuery === cacheQuery) { unchangedRefreshes = Math.min(unchangedRefreshes + 1, MAX_UNCHANGED_REFRESHES); if (elements.dashboard.dataset.filterPending === 'true') render(lastStatistics); scheduleBackgroundRefresh(); return; } if (background) unchangedRefreshes = 0; const statistics = await pullJournalStatistics(baseUrl, session.accessToken, selectedPeriod, { speciesId: selectedSpeciesId, placeId: selectedPlaceId, signal: controller.signal }); if (requestId !== activeRequest || session.accessToken !== activeSession?.accessToken) return; const retainedPlaceId = retainedStatisticsPlaceId(selectedPlaceId, statistics.places, statistics.filters?.placeId ?? null); if (retainedPlaceId !== selectedPlaceId) { selectedPlaceId = retainedPlaceId; await loadStatistics(session, { preserve: true }); return; } const retainedSpeciesId = retainedStatisticsSpeciesId(selectedSpeciesId, statistics.species, statistics.filters?.speciesId ?? null); if (retainedSpeciesId !== selectedSpeciesId) { selectedSpeciesId = retainedSpeciesId; await loadStatistics(session, { preserve: true }); return; } const signature = statisticsSignature(statistics); if (background && journalRevision === null) { unchangedRefreshes = signature === lastStatisticsSignature ? unchangedRefreshes + 1 : 0; } if (journalRevision !== null) lastJournalRevision = journalRevision; lastStatisticsSignature = signature; lastStatisticsQuery = cacheQuery; if (journalRevision !== null) { const resultKey = session.user.id + '/' + cacheQuery; statisticsQueryResults.delete(resultKey); statisticsQueryResults.set(resultKey, {revision:journalRevision,statistics}); while (statisticsQueryResults.size > 32) statisticsQueryResults.delete(statisticsQueryResults.keys().next().value); } try { writeStatisticsCache(window.sessionStorage, session.user.id, cacheQuery, statistics, journalRevision); } catch {} render(statistics); // A newly selected period/place may not have its all-species comparison yet. // Fill that background independently, without delaying the selected results. const referenceQuery = JSON.stringify([selectedPeriod, selectedPlaceId, null]); const referenceKey = session.user.id + '/' + referenceQuery; if (selectedSpeciesId !== null && !statisticsQueryResults.has(referenceKey)) { const referencePlaceId = selectedPlaceId; void pullJournalStatistics(baseUrl, session.accessToken, selectedPeriod, { speciesId:null, placeId:referencePlaceId, signal:controller.signal }).then(reference => { if (requestId !== activeRequest || session.accessToken !== activeSession?.accessToken) return; statisticsQueryResults.set(referenceKey,{revision:journalRevision,statistics:reference}); while (statisticsQueryResults.size > 32) statisticsQueryResults.delete(statisticsQueryResults.keys().next().value); if (lastStatistics === statistics) renderChart(statistics); }).catch(() => { /* Selected statistics stay usable if comparison is unavailable. */ }); } scheduleBackgroundRefresh(); } catch (error) { if (requestId !== activeRequest) return; if (error instanceof Error && error.message === 'request-cancelled') return; if (error instanceof Error && error.message === 'algofish-server-401') { window.dispatchEvent(new CustomEvent('algofish:sessionexpired', { detail: { accountId: session.user.id }, })); activeSession = null; try { clearStatisticsCache(window.sessionStorage); } catch {} cancelBackgroundRefresh(); showState('disconnected'); return; } if (!background || !lastStatistics) showState('error'); else scheduleBackgroundRefresh(); } finally { if (activeRequestController === controller) activeRequestController = null; } } function initializeDates() { const range = statisticsInitialDateRange(); elements.to.value = range.to; elements.to.max = range.maximum; elements.from.value = range.from; elements.from.max = range.maximum; } elements.mode.addEventListener('change', () => { const custom = elements.mode.value === 'custom'; elements.dateFields.hidden = !custom; if (!custom) void loadStatistics(); }); elements.form.addEventListener('submit', (event) => { event.preventDefault(); void loadStatistics(); }); elements.place.addEventListener('change', () => { selectedPlaceId = elements.place.value || null; void loadStatistics(activeSession, { preserve: true }); }); elements.retry.addEventListener('click', () => void loadStatistics()); elements.monthlySpecies.addEventListener('change', () => { selectedSpeciesId = elements.monthlySpecies.value || null; if (lastStatistics) renderSpecies(lastStatistics); void loadStatistics(activeSession, { preserve: true }); }); elements.speciesReset.addEventListener('click', () => { selectedSpeciesId = null; if (lastStatistics) renderSpecies(lastStatistics); void loadStatistics(activeSession, { preserve: true }); }); elements.analysisTabs.addEventListener('click', (event) => { const button = event.target instanceof Element ? event.target.closest('button') : null; if (!button) return; selectedAnalysisTheme = button.dataset.analysisTarget ?? (button.hasAttribute('data-analysis-species') ? 'species' : 'all'); if (lastStatistics) renderAnalyses(lastStatistics); }); window.addEventListener('algofish:accountchange', (event) => { const nextSession = event.detail?.session ?? null; const nextAccountId = nextSession?.user.id ?? null; const sameAccount = nextAccountId !== null && nextAccountId === activeAccountId; if (!sameAccount) { statisticsQueryResults.clear(); renderGeneration += 1; // Startup authentication has no previous account: keep the saved preview. // readStatisticsCache separately verifies the exact account and filters. if (activeAccountId !== null) { try { clearStatisticsCache(window.sessionStorage); } catch {} } selectedSpeciesId = null; selectedPlaceId = null; selectedAnalysisTheme = 'airTemperature'; lastJournalRevision = null; } activeAccountId = nextAccountId; void loadStatistics(nextSession, { preserve: sameAccount }); }); window.addEventListener('algofish:localechange', () => { if (lastStatistics) render(lastStatistics); }); document.addEventListener('visibilitychange', () => { if (document.hidden) cancelBackgroundRefresh({ reset: false }); else if (activeSession) void loadStatistics(activeSession, { background: true }); }); initializeDates(); document.querySelector('#statistics-chart-views').addEventListener('click', (event) => { const button = event.target instanceof Element ? event.target.closest('button[data-view]') : null; if (!button) return; const table = button.dataset.view === 'table'; elements.chart.hidden = table; document.querySelector('#statistics-monthly-table').hidden = !table; for (const control of document.querySelectorAll('#statistics-chart-views button')) { control.setAttribute('aria-pressed', String(control === button)); } }); const initialSession = getCurrentAccountSession(); if (initialSession) void loadStatistics(initialSession);