// ====== METRICS ENGINE ======
async function renderMetrics(divId) {
    const div = state.divisions.find(d => d.id === divId);
    if (!div || !state.metricsData) return;

    const config = state.metricsData.config;
    queueTranslationRefresh(config.map((c) => c.metric_label));
    const todayStr = new Date().toISOString().split('T')[0];
    
    // Set date input to today by default
    const dateInput = document.getElementById('metricDateInput');
    dateInput.value = todayStr;

    // Build dynamic input forms for this division's specific metrics
    const inputContainer = document.getElementById('metricInputContainer');
    const mockToggle = document.getElementById('mockDataToggle');
    if (mockToggle) mockToggle.checked = state.showMockData;
    inputContainer.innerHTML = config.map(c => `
        <div class="metric-field flex flex-col min-w-0">
            <label class="text-[10px] text-gray-400 uppercase tracking-wider mb-1 flex items-center gap-1 break-words"><i class="fas ${c.icon} shrink-0"></i> <span>${escapeHtml(getCachedTranslation(c.metric_label))}</span></label>
            <input type="number" data-key="${c.metric_key}" class="metric-val-input w-full sm:w-28 bg-black/40 border border-white/10 rounded-lg px-2 py-2 text-white text-sm focus:outline-none focus:border-[var(--dash-accent)] shadow-inner" placeholder="0">
        </div>
    `).join('') + `
        <div class="flex flex-col justify-end metric-save-row">
            <button id="saveMetricsBtn" class="bg-[var(--dash-accent)] text-white hover:brightness-110 px-4 py-2 rounded-lg text-sm font-semibold transition shadow-lg h-[40px] w-full sm:w-auto">${escapeHtml(t('common.save'))}</button>
        </div>
    `;

    document.getElementById('saveMetricsBtn').addEventListener('click', async () => {
        const dStr = document.getElementById('metricDateInput').value;
        if(!dStr) return showToast(t('metrics.selectDate'), "warning");
        const inputs = document.querySelectorAll('.metric-val-input');
        for (let inp of inputs) {
            const val = inp.value;
            if(val !== '') {
                await api.saveMetric({ division_id: divId, metric_key: inp.dataset.key, value: parseFloat(val), date: dStr });
            }
        }
        await refreshActiveAppState({ maintainFocus: true });
        showToast(t('metrics.savedToast'), "success");
    });

    // Populate current values in inputs if exist
    const todaysData = state.metricsData.data.filter(d => d.date === dateInput.value);
    document.querySelectorAll('.metric-val-input').forEach(inp => {
        const found = todaysData.find(d => d.metric_key === inp.dataset.key);
        if(found) inp.value = found.value;
    });

    dateInput.addEventListener('change', () => {
        document.querySelectorAll('.metric-val-input').forEach(inp => inp.value = '');
        const d = state.metricsData.data.filter(x => x.date === dateInput.value);
        document.querySelectorAll('.metric-val-input').forEach(inp => {
            const found = d.find(x => x.metric_key === inp.dataset.key);
            if(found) inp.value = found.value;
        });
    });

    // AI Insight — trigger interpretation
    const insightEl = document.getElementById('aiMetricsInsight');
    insightEl.innerHTML = `<button onclick="loadMetricsInsight(${divId})" class="text-purple-300 hover:text-white transition flex items-center gap-2 text-xs"><i class="fas fa-magic"></i> ${escapeHtml(t('metrics.getInterpretation'))}</button>`;
    if (todaysData.length > 0) insightEl.innerHTML = `<span class="text-xs text-gray-400">${escapeHtml(t('metrics.todaysLogged'))}</span> <button onclick="loadMetricsInsight(${divId})" class="ml-2 text-purple-300 hover:text-white transition text-xs"><i class="fas fa-magic"></i> ${escapeHtml(t('metrics.aiInterpret'))}</button>`;

    document.querySelectorAll('.chart-period-btn').forEach((btn) => {
        btn.classList.toggle('active', btn.dataset.period === state.activeChartPeriod);
        btn.classList.toggle('bg-white/10', btn.dataset.period === state.activeChartPeriod);
        btn.classList.toggle('text-white', btn.dataset.period === state.activeChartPeriod);
        btn.classList.toggle('text-gray-400', btn.dataset.period !== state.activeChartPeriod);
    });

    renderChart(state.activeChartPeriod);
}

function renderChart(period) {
    if(!state.metricsData) return;
    state.activeChartPeriod = period;
    const config = state.metricsData.config;
    
    // Filter mock data based on toggle
    const rawData = state.metricsData.data.filter(d => state.showMockData || d.is_mock === 0);

    const grouped = {};
    const toKey = (dateStr) => {
        if (period === 'monthly') return dateStr.slice(0, 7);
        if (period === 'weekly') {
            const date = new Date(`${dateStr}T00:00:00`);
            const monday = new Date(date);
            const day = (date.getDay() + 6) % 7;
            monday.setDate(date.getDate() - day);
            return monday.toISOString().split('T')[0];
        }
        return dateStr;
    };

    rawData.forEach((row) => {
        const bucket = toKey(row.date);
        if (!grouped[bucket]) grouped[bucket] = {};
        if (!grouped[bucket][row.metric_key]) grouped[bucket][row.metric_key] = [];
        grouped[bucket][row.metric_key].push(Number(row.value) || 0);
    });

    const labelLimit = period === 'daily' ? 14 : period === 'weekly' ? 10 : 8;
    const labels = Object.keys(grouped).sort().slice(-labelLimit);
    const datasets = [];

    config.forEach((c, idx) => {
        const dataArr = labels.map((label) => {
            const values = grouped[label][c.metric_key] || [];
            if (!values.length) return 0;
            const total = values.reduce((sum, value) => sum + value, 0);
            return period === 'daily' ? total : Number((total / values.length).toFixed(2));
        });
        datasets.push({
            label: getCachedTranslation(c.metric_label),
            data: dataArr,
            borderColor: idx === 0 ? 'rgba(33, 150, 243, 1)' : idx === 1 ? 'rgba(102, 187, 106, 1)' : 'rgba(236, 64, 122, 1)',
            backgroundColor: idx === 0 ? 'rgba(33, 150, 243, 0.1)' : idx === 1 ? 'rgba(102, 187, 106, 0.1)' : 'rgba(236, 64, 122, 0.1)',
            borderWidth: 2,
            tension: 0.4,
            fill: true
        });
    });

    if(state.divisionChartInstance) state.divisionChartInstance.destroy();
    const ctx = document.getElementById('divisionChart').getContext('2d');
    state.divisionChartInstance = new Chart(ctx, {
        type: 'line',
        data: { labels, datasets },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { labels: { color: 'rgba(255,255,255,0.7)' } } },
            scales: {
                y: { grid: { color: 'rgba(255,255,255,0.05)' }, ticks: { color: 'rgba(255,255,255,0.5)' }, beginAtZero: true },
                x: { grid: { color: 'rgba(255,255,255,0.05)' }, ticks: { color: 'rgba(255,255,255,0.5)' } }
            }
        }
    });
}
