let chartLine, chartBar, chartDonut;
let allMonths = [];
const MONTHS_TO_SHOW_DEFAULT = 6;
function formatMonthDisplay(monthCode) {
const monthNames = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
];
const year = monthCode.substring(0, 4);
const monthIdx = parseInt(monthCode.substring(5, 7)) - 1;
return `${monthNames[monthIdx]} ${year}`;
}
function getThemeColors() {
const theme = document.documentElement.getAttribute('data-theme');
const isDark = theme === 'tokyo';
return {
isDark,
textColor: isDark ? '#e8f4ff' : '#1a1d22',
gridColor: isDark ? 'rgba(100, 220, 255, 0.1)' : 'rgba(26, 29, 34, 0.1)',
accent: isDark ? '#64dcff' : '#2c5a7a',
secondary: isDark ? '#2c5a7a' : '#64dcff',
palette: isDark
? ['#64dcff', '#2c5a7a', '#a3b3cc', '#7886a0', '#d93d3d', '#dcad2b', '#4caf50', '#ff9800', '#9c27b0', '#00bcd4']
: ['#2c5a7a', '#64dcff', '#595f68', '#9299a2', '#a03030', '#8a6a10', '#4caf50', '#ff9800', '#9c27b0', '#00bcd4'],
bgTransparent: 'transparent',
};
}
function initCharts() {
if (chartLine) chartLine.dispose();
if (chartBar) chartBar.dispose();
if (chartDonut) chartDonut.dispose();
chartLine = echarts.init(document.getElementById('chart-line'));
chartBar = echarts.init(document.getElementById('chart-bar'));
chartDonut = echarts.init(document.getElementById('chart-donut'));
renderLineChart([], [], []);
renderBarChart([], []);
renderDonutChart([]);
window.addEventListener('resize', () => {
chartLine.resize();
chartBar.resize();
chartDonut.resize();
});
}
function renderLineChart(months, massData, valueData) {
const c = getThemeColors();
const formattedMonths = months.map(m => formatMonthDisplay(m));
// Show every nth month label to prevent crowding
const step = months.length > 24 ? 6 : (months.length > 12 ? 3 : 1);
const xLabels = formattedMonths.map((label, idx) =>
idx % step === 0 ? label : ''
);
chartLine.setOption({
backgroundColor: c.bgTransparent,
textStyle: { fontFamily: 'JetBrains Mono', color: c.textColor },
tooltip: {
trigger: 'axis',
axisPointer: { type: 'cross' }
},
legend: {
data: ['Mass (kg)', 'Value (DKK)'],
textStyle: { color: c.textColor },
top: 0
},
grid: { left: '3%', right: '4%', bottom: '10%', containLabel: true },
xAxis: {
type: 'category',
data: xLabels,
axisLine: { lineStyle: { color: c.gridColor } },
axisLabel: {
color: c.textColor,
interval: 0,
rotate: 0,
fontSize: 10
},
boundaryGap: false,
},
yAxis: [
{
type: 'value',
name: 'Mass (kg)',
position: 'left',
splitLine: { lineStyle: { color: c.gridColor } },
axisLabel: {
color: c.accent,
formatter: (val) => (val >= 1e6 ? (val / 1e6).toFixed(1) + 'M' : val.toLocaleString())
},
axisLine: { show: true, lineStyle: { color: c.accent } },
nameTextStyle: { color: c.accent, padding: [0, 0, 0, 0] }
},
{
type: 'value',
name: 'Value (DKK)',
position: 'right',
splitLine: { show: false },
axisLabel: {
color: c.secondary,
formatter: (val) => (val >= 1e6 ? (val / 1e6).toFixed(1) + 'M' : val.toLocaleString())
},
axisLine: { show: true, lineStyle: { color: c.secondary } },
nameTextStyle: { color: c.secondary }
}
],
series: [
{
name: 'Mass (kg)',
type: 'line',
yAxisIndex: 0,
smooth: true,
symbol: 'none',
lineStyle: { width: 2 },
itemStyle: { color: c.accent },
areaStyle: { opacity: 0.05 },
data: massData,
},
{
name: 'Value (DKK)',
type: 'line',
yAxisIndex: 1,
smooth: true,
symbol: 'none',
lineStyle: { width: 2 },
itemStyle: { color: c.secondary },
areaStyle: { opacity: 0.05 },
data: valueData,
},
],
});
}
function renderDonutChart(data) {
const c = getThemeColors();
// Limit to top 8 for clarity
const limitedData = data.slice(0, 8);
if (data.length > 8) {
const otherSum = data.slice(8).reduce((sum, d) => sum + (d.value || 0), 0);
if (otherSum > 0) {
limitedData.push({ name: 'Other', value: otherSum });
}
}
chartDonut.setOption({
backgroundColor: c.bgTransparent,
textStyle: { fontFamily: 'JetBrains Mono', color: c.textColor },
tooltip: {
trigger: 'item',
formatter: '{b}: {c} DKK'
},
legend: {
orient: 'horizontal',
bottom: 0,
textStyle: { color: c.textColor },
type: 'scroll',
padding: [20, 0, 0, 0]
},
grid: { bottom: '30%' },
series: [
{
type: 'pie',
radius: ['50%', '70%'],
avoidLabelOverlap: true,
itemStyle: {
borderRadius: 3,
borderColor: c.isDark ? '#07070d' : '#f4f1ec',
borderWidth: 1,
},
label: { show: false },
emphasis: {
label: { show: false },
},
data: limitedData,
color: c.palette,
},
],
});
}
function renderBarChart(months, seriesData) {
const c = getThemeColors();
const formattedMonths = months.map(m => formatMonthDisplay(m));
const step = months.length > 24 ? 6 : (months.length > 12 ? 3 : 1);
const xLabels = formattedMonths.map((label, idx) =>
idx % step === 0 ? label : ''
);
// Limit to top 5 species for readability
const limitedSeries = seriesData.slice(0, 5);
chartBar.setOption({
backgroundColor: c.bgTransparent,
textStyle: { fontFamily: 'JetBrains Mono', color: c.textColor },
tooltip: {
trigger: 'axis',
axisPointer: { type: 'shadow' },
},
legend: {
textStyle: { color: c.textColor },
top: 0,
type: 'scroll',
maxItems: 5
},
grid: { left: '3%', right: '4%', bottom: '10%', containLabel: true },
xAxis: {
type: 'category',
data: xLabels,
axisLine: { lineStyle: { color: c.gridColor } },
axisLabel: {
color: c.textColor,
interval: 0,
fontSize: 10,
rotate: 0
},
},
yAxis: {
type: 'value',
splitLine: { lineStyle: { color: c.gridColor } },
axisLabel: {
color: c.textColor,
formatter: (val) => val >= 1e6 ? (val / 1e6).toFixed(1) + 'M' : val.toLocaleString()
},
},
series: limitedSeries.map(s => ({
...s,
barMaxWidth: 30
})),
color: c.palette,
});
}
async function fetchData(endpoint) {
try {
const res = await fetch(endpoint);
if (!res.ok) throw new Error(`API Error: ${res.status}`);
return await res.json();
} catch (err) {
console.error(err);
return null;
}
}
function populateSelect(id, items, codeKey, labelKey) {
const sel = document.getElementById(id);
sel.innerHTML = '';
items.forEach((item) => {
const opt = document.createElement('option');
opt.value = item[codeKey];
opt.textContent = item[labelKey];
sel.appendChild(opt);
});
}
function populateMonthSelect(selectId, months) {
const sel = document.getElementById(selectId);
sel.innerHTML = '';
months.forEach((m) => {
const opt = document.createElement('option');
opt.value = m;
opt.textContent = formatMonthDisplay(m);
sel.appendChild(opt);
});
}
async function populateDropdowns() {
showLoading(true);
const [speciesList, zonesList, gearList, summaryData] = await Promise.all([
fetchData('/api/species'),
fetchData('/api/zones'),
fetchData('/api/gear'),
fetchData('/api/summary'),
]);
if (speciesList) {
populateSelect('species', speciesList, 'code', 'label');
}
if (zonesList) {
populateSelect('zone', zonesList, 'code', 'label');
}
if (gearList) {
populateSelect('gear', gearList, 'code', 'label');
}
if (summaryData && summaryData.monthly) {
allMonths = summaryData.monthly.map((m) => m.month).sort();
populateMonthSelect('month_from', allMonths);
populateMonthSelect('month_to', allMonths);
// Default to last 6 months
const fromIdx = Math.max(0, allMonths.length - MONTHS_TO_SHOW_DEFAULT);
document.getElementById('month_from').value = allMonths[fromIdx];
document.getElementById('month_to').value = allMonths[allMonths.length - 1];
}
showLoading(false);
}
async function updateCharts() {
showLoading(true);
hideEmptyState();
const species = document.getElementById('species').value;
const zone = document.getElementById('zone').value;
const gear = document.getElementById('gear').value;
const monthFrom = document.getElementById('month_from').value;
const monthTo = document.getElementById('month_to').value;
// Validation: prevent from > to
if (monthFrom && monthTo && monthFrom > monthTo) {
alert('From date cannot be greater than To date.');
showLoading(false);
return;
}
const landingsParams = new URLSearchParams();
if (species) landingsParams.append('species', species);
if (zone) landingsParams.append('zone', zone);
if (gear) landingsParams.append('gear', gear);
if (monthFrom) landingsParams.append('month_from', monthFrom);
if (monthTo) landingsParams.append('month_to', monthTo);
landingsParams.append('limit', '10000');
const summaryParams = new URLSearchParams();
if (species) summaryParams.append('species', species);
if (monthFrom) summaryParams.append('month_from', monthFrom);
if (monthTo) summaryParams.append('month_to', monthTo);
const [landings, summary] = await Promise.all([
fetchData(`/api/landings?${landingsParams.toString()}`),
fetchData(`/api/summary?${summaryParams.toString()}`),
]);
showLoading(false);
if ((!landings || landings.length === 0) && (!summary || !summary.monthly || summary.monthly.length === 0)) {
showEmptyState();
return;
}
hideEmptyState();
document.getElementById('charts-grid').style.display = 'grid';
setTimeout(() => {
chartLine.resize();
chartBar.resize();
chartDonut.resize();
}, 0);
// --- Line Chart ---
if (summary && summary.monthly) {
const months = summary.monthly.map((m) => m.month);
const massData = summary.monthly.map((m) => m.total_mass || 0);
const valueData = summary.monthly.map((m) => m.total_value || 0);
renderLineChart(months, massData, valueData);
} else {
renderLineChart([], [], []);
}
// --- Donut Chart ---
if (summary && summary.top_species && summary.top_species.length > 0) {
const donutData = summary.top_species.map((s) => ({
name: s.species_label,
value: s.total_value || 0,
}));
renderDonutChart(donutData);
} else {
renderDonutChart([]);
}
// --- Bar Chart ---
if (summary && summary.top_species && summary.top_species.length > 0 && landings && landings.length > 0) {
const months = [...new Set(landings.map((l) => l.month))].sort();
const topSpecies = summary.top_species;
const barSeries = topSpecies.map((sp) => ({
name: sp.species_label,
type: 'bar',
stack: 'total',
emphasis: { focus: 'series' },
data: months.map((m) => {
const row = landings.find(
(l) =>
l.month === m &&
l.species_code === sp.species_code &&
l.measure_code === 'VALUE'
);
return row && row.value ? row.value : 0;
}),
}));
renderBarChart(months, barSeries);
} else {
renderBarChart([], []);
}
}
function showLoading(show) {
const overlay = document.getElementById('loading-overlay');
if (show) {
overlay.classList.remove('hidden');
} else {
overlay.classList.add('hidden');
}
}
function showEmptyState() {
document.getElementById('charts-grid').style.display = 'none';
document.getElementById('empty-state').style.display = 'flex';
}
function hideEmptyState() {
document.getElementById('empty-state').style.display = 'none';
}
document.getElementById('apply-filters').addEventListener('click', updateCharts);
// Theme Logic
(() => {
function currentSystemTheme() {
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'tokyo'
: 'light';
}
const btn = document.getElementById('theme-toggle');
if (btn) {
btn.addEventListener('click', () => {
const current =
document.documentElement.getAttribute('data-theme') || 'light';
const next = current === 'light' ? 'tokyo' : 'light';
document.documentElement.setAttribute('data-theme', next);
localStorage.setItem('poc-theme', next);
initCharts();
updateCharts();
});
}
window
.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', () => {
if (!localStorage.getItem('poc-theme')) {
document.documentElement.setAttribute('data-theme', currentSystemTheme());
initCharts();
updateCharts();
}
});
})();
// Init
document.addEventListener('DOMContentLoaded', () => {
initCharts();
populateDropdowns().then(updateCharts);
});