
export class StatsDashboard {
    constructor(containerId) {
        this.container = document.getElementById(containerId);
        this.render();
    }


    getStreakData() {
        const saved = localStorage.getItem('hydroflux_streak');
        if (saved) {
            const start = new Date(parseInt(saved));
            const now = new Date();
            const diff = now - start;
            const days = Math.floor(diff / (1000 * 60 * 60 * 24));
            return days < 0 ? 0 : days;
        }
        return 0;
    }

    getFitnessData() {
        const saved = localStorage.getItem('hydroflux_fitness_v2');
        if (saved) {
            const parsed = JSON.parse(saved);
            return {
                steps: parsed.steps || 0,
                sleep: parsed.sleep || 0,
                history: parsed.history || {}
            };
        }
        return { steps: 0, sleep: 0, history: {} };
    }

    calculateScores() {
        const waterData = this.getWaterDataRaw(); // Need raw history access
        const streakDays = this.getStreakData();
        const fitness = this.getFitnessData();

        // --- ENTROPY SCORING SYSTEM (Infinite & Decay) ---

        // 1. LIQUID LEVEL (Historical Volume - Time Decay)
        // You gain +1 XP for every 100mL you drink.
        // You lose -20 XP for every day since you started.
        // Result: You must drink > 2000mL/day just to maintain your level.

        // Calculate Total Volume from History
        let totalVolume = 0;
        let firstDate = new Date();
        const history = waterData.history || {};
        const dates = Object.keys(history);

        if (dates.length > 0) {
            // Find earliest date
            firstDate = new Date(dates.sort((a, b) => new Date(a) - new Date(b))[0]);

            // Sum Volume
            Object.values(history).forEach(day => {
                totalVolume += (day.current || 0);
            });
        }

        // Add Today's Volume (in case it's not in history yet)
        totalVolume += waterData.current;

        // Calculate Days Since Start
        const now = new Date();
        const msPerDay = 1000 * 60 * 60 * 24;
        const daysSinceStart = Math.max(1, Math.floor((now - firstDate) / msPerDay));

        // Liquid Math
        const volumeXP = Math.floor(totalVolume / 100); // 1 pt per 100mL
        const entropyTax = daysSinceStart * 25; // Tax: 25 pts/day (Need 2.5L to break even)

        let liquidLevel = volumeXP - entropyTax;

        // 2. WILLPOWER LEVEL (Streak * Multiplier)
        // High risk, high reward. 
        // 1 Day = 50 Levels.
        // Breaking streak = Instant loss of all these levels.
        let willpowerLevel = streakDays * 50;

        // 3. FIT LEVEL (Cumulative Persistence)
        // Logic: Sum of all historical performance - Daily Tax
        // Good day (+XP) > Tax = Level Up
        // Bad day (+0) < Tax = Level Down

        let cumulativeFitXP = 0;
        const fitHistory = fitness.history || {};

        // Sum all historical points
        Object.values(fitHistory).forEach(day => {
            const daySteps = day.steps || 0;
            const daySleep = day.sleep || 0;

            // Formula: 1pt per 500 steps + 4pts per hour sleep
            // e.g. 10k steps (20) + 8h sleep (32) = 52 pts/day
            cumulativeFitXP += Math.floor(daySteps / 500) + Math.floor(daySleep * 4);
        });

        // Add current day if not in history yet
        const todayKey = new Date().toDateString();
        if (!fitHistory[todayKey]) {
            cumulativeFitXP += Math.floor(fitness.steps / 500) + Math.floor(fitness.sleep * 4);
        }

        // Apply Entropy Tax
        // You lose 30 XP per day you've been active.
        const fitTax = daysSinceStart * 30;

        let fitLevel = cumulativeFitXP - fitTax;

        // 4. TOTAL HYDRO LEVEL
        let hydroLevel = liquidLevel + willpowerLevel + fitLevel;

        // Prevent Negative Display (though internal math is negative)
        // Actually, user wants to go down. Negative levels are valid shame indicators?
        // "Go down on levels" -> usually implies dropping from 50 to 40. 
        // If we allow negative, it might be discouraging. Let's floor at 0.
        // But the user said "harder to progress", implying you can be in a deficit.
        // Let's allow negative but style it red? No, let's keep floor at 0 for MVP.
        if (hydroLevel < 0) hydroLevel = 0;
        if (liquidLevel < 0) liquidLevel = 0;
        // Fit level can be negative (dragging you down), but we display it unsigned usually.
        // Let's allow the components to sum naturally, but display 0 if total is < 0.

        return {
            liquid: liquidLevel,
            willpower: willpowerLevel,
            fit: fitLevel,
            total: hydroLevel,
            details: {
                daysActive: daysSinceStart,
                totalLiters: (totalVolume / 1000).toFixed(1),
                dailyTax: 25
            }
        };
    }

    getWaterDataRaw() {
        const saved = localStorage.getItem('hydroflux_data');
        if (saved) {
            return JSON.parse(saved);
        }
        return { current: 0, goal: 3000, history: {} };
    }

    update() {
        this.render();
    }

    render() {
        const scores = this.calculateScores();

        // Progress Bar Calculation Logic
        const liquidPct = Math.min(100, (scores.details.waterCurrent / 2500) * 100); // 2.5L is break even
        const fitPct = Math.min(100, Math.max(0, scores.fit * 5)); // Scaling fit level to bar (approx)

        this.container.innerHTML = `
            <div class="stats-container" style="padding-bottom: 80px;">
                <!-- HERO LEVEL DISPLAY -->
                <div class="level-hero" style="text-align: center; margin-bottom: 30px; padding: 20px;">
                    <div style="position: relative; width: 160px; height: 160px; margin: 0 auto;">
                        <svg viewBox="0 0 100 100" style="transform: rotate(-90deg); width: 100%; height: 100%;">
                            <circle cx="50" cy="50" r="45" stroke="rgba(255,255,255,0.1)" stroke-width="8" fill="none"></circle>
                            <circle cx="50" cy="50" r="45" stroke="var(--primary-cyan)" stroke-width="8" fill="none" 
                                stroke-dasharray="283" stroke-dashoffset="${283 - (Math.min(100, scores.total % 100) / 100 * 283)}"></circle>
                        </svg>
                        <div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center;">
                            <span style="font-size: 0.8rem; color: var(--text-muted); letter-spacing: 2px;">LEVEL</span>
                            <span style="font-size: 3rem; font-family: var(--font-heading); color: #fff; text-shadow: 0 0 15px var(--primary-cyan);">${scores.total}</span>
                        </div>
                    </div>
                </div>

                <div class="stats-grid" style="display: flex; flex-direction: column; gap: 20px;">
                    
                    <!-- Liquid Level Card -->
                    <div class="glass-panel" style="margin: 0; padding: 20px;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <div class="icon-box cyan-box">
                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"/></svg>
                                </div>
                                <div>
                                    <span class="stat-label" style="margin: 0; color: var(--primary-cyan);">LIQUID LEVEL</span>
                                    <div class="stat-sub">Daily Maintenance</div>
                                </div>
                            </div>
                            <span class="stat-value" style="font-size: 1.8rem;">${scores.liquid}</span>
                        </div>
                        
                        <!-- Bar -->
                        <div style="height: 8px; background: rgba(255,255,255,0.1); border-radius: 4px; overflow: hidden; margin-top: 10px;">
                            <div style="width: ${liquidPct}%; height: 100%; background: var(--primary-cyan); box-shadow: 0 0 10px var(--primary-cyan); transition: width 1s;"></div>
                        </div>
                        <div style="display: flex; justify-content: space-between; margin-top: 8px; font-size: 0.8rem; color: var(--text-muted);">
                            <span>Tax: -${scores.details.dailyTax}/day</span>
                            <span>${Math.round(liquidPct)}% Safe</span>
                        </div>
                    </div>

                    <!-- Willpower Level Card -->
                    <div class="glass-panel" style="margin: 0; padding: 20px;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                             <div style="display: flex; align-items: center; gap: 10px;">
                                <div class="icon-box purple-box">
                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10 2v7.31"/><path d="M14 2v7.31"/><path d="M4 10h16v12a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1z"/></svg>
                                </div>
                                <div>
                                    <span class="stat-label" style="margin: 0; color: var(--secondary-purple);">WILLPOWER</span>
                                    <div class="stat-sub">Streak Intensity</div>
                                </div>
                            </div>
                            <span class="stat-value" style="font-size: 1.8rem;">${scores.willpower}</span>
                        </div>

                         <!-- Bar (Always full if active, pulsing) -->
                        <div style="height: 8px; background: rgba(255,255,255,0.1); border-radius: 4px; overflow: hidden; margin-top: 10px;">
                            <div style="width: 100%; height: 100%; background: var(--secondary-purple); box-shadow: 0 0 15px var(--secondary-purple); animation: pulse-glow 2s infinite;"></div>
                        </div>
                         <div style="display: flex; justify-content: space-between; margin-top: 8px; font-size: 0.8rem; color: var(--text-muted);">
                            <span>Streak: ${scores.details.daysActive} Days</span>
                            <span>ACTIVE</span>
                        </div>
                    </div>

                    <!-- Fit Level Card -->
                    <div class="glass-panel" style="margin: 0; padding: 20px;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                             <div style="display: flex; align-items: center; gap: 10px;">
                                <div class="icon-box" style="background: rgba(255, 215, 0, 0.1); color: #ffd700;">
                                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12" /></svg>
                                </div>
                                <div>
                                    <span class="stat-label" style="margin: 0; color: #ffd700;">FIT LEVEL</span>
                                    <div class="stat-sub">Daily Activity</div>
                                </div>
                            </div>
                            <span class="stat-value" style="font-size: 1.8rem; color: ${scores.fit < 0 ? '#ff4d4d' : '#ffd700'};">${scores.fit}</span>
                        </div>

                        <!-- Bar -->
                        <div style="height: 8px; background: rgba(255,255,255,0.1); border-radius: 4px; overflow: hidden; margin-top: 10px;">
                            <div style="width: ${fitPct}%; height: 100%; background: #ffd700; box-shadow: 0 0 10px #ffd700;"></div>
                        </div>
                        <div style="display: flex; justify-content: space-between; margin-top: 8px; font-size: 0.8rem; color: var(--text-muted);">
                            <span>Status</span>
                            <span style="color: ${scores.fit < 0 ? '#ff4d4d' : '#ffd700'};">${scores.fit < 0 ? 'PENALTY' : 'BOOSTING'}</span>
                        </div>
                    </div>

                </div>
            </div>
        `;
    }
}

