// settings-stats.js
import { BackendService } from "./backend-db.js";

export class SettingsStats {
    constructor(parentElement) {
        this._parentElement = parentElement;
        this._container = null;
        this._injectHTML();
        this.refresh();
    }

    _injectHTML() {
        const html = `
            <div class="settings-row stats-row">
                <div class="stats-header"><span id="stats-scope" class="auth-status" style="font-size: 15px;">Lade...</span></div>
                <div class="stats-grid">
                    <div class="stat-item"><b id="stat-today">-</b><span>Heute</span></div>
                    <div class="stat-item"><b id="stat-month">-</b><span>Monat</span></div>
                    <div class="stat-item"><b id="stat-year">-</b><span>Jahr</span></div>
                </div>
                <div class="cleaning-stats-section" style="margin-top: 20px;">
                    <div class="stats-header" style="font-size: 15px; color: #000000; margin-bottom: 10px;">Stolpersteine nach Zustand</div>
                    <div id="cleaning-bars-list"></div>
                </div>
            </div>
        `;
        this._parentElement.insertAdjacentHTML('beforeend', html);
        this._container = this._parentElement.lastElementChild;

        if (!document.getElementById('stats-styles')) {
            const css = `
                .stats-grid { display: flex; gap: 10px; margin-top: 8px; justify-content: space-between; }
                .stat-item { background: rgba(0,0,0,0.03); padding: 8px; border-radius: 8px; flex: 1; text-align: center; display: flex; flex-direction: column; }
                .stat-item b { font-size: 1.1rem; color: #007AFF; }
                .stat-item span { font-size: 0.65rem; text-transform: uppercase; color: #8e8e93; }
                .cleaning-row { display: flex; align-items: center; margin-bottom: 6px; height: 18px; }
                .cleaning-label { width: 85px; font-size: 12px; text-align: right; padding-right: 10px; color: #666; }
                .cleaning-bar-bg { flex-grow: 1; background: rgba(0,0,0,0.05); height: 12px; border-radius: 6px; overflow: hidden; position: relative; }
                .cleaning-bar-fill { height: 100%; border-radius: 6px; width: 0; transition: width 0.8s cubic-bezier(0.1, 0.5, 0.5, 1); }
                .cleaning-value { width: 35px; font-size: 12px; font-weight: bold; padding-left: 8px; color: #333; }
            `;
            const style = document.createElement('style');
            style.id = 'stats-styles';
            style.textContent = css;
            document.head.appendChild(style);
        }
    }

    async refresh() {
        const backend = BackendService.getInstance();
        const barsContainer = document.getElementById('cleaning-bars-list');

        try {
            const [resLogs, resCleaning] = await Promise.allSettled([
                backend.getLogStats(),
                backend.getCleaningStats()
            ]);

            if (resLogs.status === 'fulfilled' && resLogs.value.success) {
                const data = resLogs.value.data;
                document.getElementById('stat-today').textContent = data.today || 0;
                document.getElementById('stat-month').textContent = data.month || 0;
                document.getElementById('stat-year').textContent = data.year || 0;

                const scopeEl = document.getElementById('stats-scope');
                if (scopeEl) {
                    const isUser = (resLogs.value.uid && parseInt(resLogs.value.uid) > 1);
                    scopeEl.textContent = "Stolperstein-Zustand erfasst - " + (isUser ? "von mir" : "insgesamt");
                }
            }

            if (resCleaning.status === 'fulfilled' && resCleaning.value.success && barsContainer) {
                this._renderCleaningBars(resCleaning.value.data, barsContainer);
            }
        } catch (e) { console.error("SettingsStats: Refresh Fehler", e); }
    }

_renderCleaningBars(data, container) {
    const power = 0.6; // <--- DEINE STELLSCHRAUBE (0.1 = extrem verzerrt, 1.0 = linear/ehrlich)

    const config = {
        '1_monat':        { label: 'glänzend', color: '#76ca6b' },
        '2_3_monate':     { label: 'gut',      color: '#f6d358' },
        '4_6_monate':     { label: 'schlecht', color: '#fb9a40' },
        'ueber_6_monate': { label: 'stumpf',   color: '#ec5d57' },
        'nie_null':       { label: 'unbekannt', color: '#cccccc' }
    };

    // Transformation der Werte für die optische Breite
    const transform = (v) => Math.pow(parseInt(v) || 0, power);
    const maxTransformed = Math.max(...data.map(d => transform(d.value)), 1);

    container.innerHTML = data.map(item => {
        const conf = config[item.label] || { label: item.label, color: '#aaa' };
        const val = parseInt(item.value) || 0;
        
        // Berechnung der Breite basierend auf der Stellschraube
        const width = (transform(val) / maxTransformed) * 100;

        return `
            <div class="cleaning-row">
                <div class="cleaning-label">${conf.label}</div>
                <div class="cleaning-bar-bg">
                    <div class="cleaning-bar-fill" style="width: ${width}%; background-color: ${conf.color};"></div>
                </div>
                <div class="cleaning-value">${val}</div>
            </div>
        `;
    }).join('');
}
}