export class FitnessDashboard {
    constructor(containerId) {
        this.container = document.getElementById(containerId);
        this.viewDate = new Date(); // Calendar View

        // 1. Activity Ring Data & History
        this.data = {
            steps: { current: 0, goal: 10000 },
            sleep: { current: 0, goal: 8 },
            history: {}
        };

        // Try to load existing data from storage (So we don't start at 0 on refresh)
        const saved = localStorage.getItem('hydroflux_fitness_v2');
        if (saved) {
            try {
                const parsed = JSON.parse(saved);
                this.data.steps.current = parsed.steps || 0;
                this.data.sleep.current = parsed.sleep || 0;
                this.data.history = parsed.history || {};
            } catch (e) { console.error("Load failed", e); }
        }

        // 2. Custom Schedule Configuration
        this.schedule = {
            "Monday": {
                type: "CHEST DAY",
                focus: "Strength",
                exercises: [
                    { name: "Bench Press", sets: "4x8-12", note: "Bench Only" },
                    { name: "Push-Ups", sets: "3xFailure", note: "Wide Grip" },
                    { name: "Dips", sets: "3x10-15", note: "Use Bench/Chair" },
                    { name: "Incline Push-Ups", sets: "3x12", note: "Feet on Bench" }
                ],
                color: "var(--primary-cyan)"
            },
            "Tuesday": {
                type: "REST & RECOVERY",
                focus: "Recovery",
                exercises: [
                    { name: "Light Stretch", sets: "10 mins", note: "Full Body" },
                    { name: "Hydrate", sets: "3 Liters", note: "Goal" }
                ],
                color: "var(--text-muted)"
            },
            "Wednesday": {
                type: "CARDIO",
                focus: "Endurance",
                exercises: [
                    { name: "Running / Jogging", sets: "30 mins", note: "Steady Pace" },
                    { name: "Jumping Jacks", sets: "3x1 min", note: "High Intensity" },
                    { name: "Burpees", sets: "3x10", note: "Explosive" }
                ],
                color: "var(--secondary-purple)"
            },
            "Thursday": {
                type: "CORE STRENGTH",
                focus: "Abs & Core",
                exercises: [
                    { name: "Plank", sets: "3x60s", note: "Hold Steady" },
                    { name: "Crunches", sets: "3x20", note: "Slow Control" },
                    { name: "Leg Raises", sets: "3x15", note: "Lower Abs focus" },
                    { name: "Russian Twists", sets: "3x20", note: "Obliques" }
                ],
                color: "#ff0055" // Intense Red/Pink for Core
            },
            "Friday": {
                type: "REST & RECOVERY",
                focus: "Recovery",
                exercises: [
                    { name: "Mobility Work", sets: "15 mins", note: "Joint Focus" },
                    { name: "Walk", sets: "20 mins", note: "Light movement" }
                ],
                color: "var(--text-muted)"
            },
            "Saturday": {
                type: "FREESTYLE / ACTIVE",
                focus: "Fun",
                exercises: [
                    { name: "Hiking / Sports", sets: "N/A", note: "Enjoy yourself" }
                ],
                color: "#ffd700" // Gold
            },
            "Sunday": {
                type: "PREP & REST",
                focus: "Recharge",
                exercises: [
                    { name: "Meal Prep", sets: "Weekly", note: "Nutrition" },
                    { name: "Sleep Early", sets: "8h+", note: "Recovery" }
                ],
                color: "var(--text-muted)"
            }
        };

        // 3. Setup Global Listener (Once)
        window.updateHealthData = (steps, sleep) => {
            // Update Data Model
            this.data.steps.current = steps;
            this.data.sleep.current = parseFloat(sleep.toFixed(1));
            this.data.sleep.current = parseFloat(sleep.toFixed(1));

            // Update today in history
            const todayKey = new Date().toDateString();
            this.data.history[todayKey] = {
                steps: steps,
                sleep: this.data.sleep.current
            };

            // Persist for Stats Module (NOW INCLUDES HISTORY)
            localStorage.setItem('hydroflux_fitness_v2', JSON.stringify({
                steps: this.data.steps.current,
                sleep: this.data.sleep.current,
                history: this.data.history
            }));

            // Re-render
            this.render();
            this.animate();
            this.renderCalendar();

            const btn = this.container.querySelector('#connect-watch-btn');
            if (btn) {
                btn.textContent = "UPDATE";
                btn.style.borderColor = "#00ff00"; // Green success
                btn.style.color = "#00ff00";
            }
        };

        this.render();
        // Delay animation to allow DOM paint
        setTimeout(() => this.animate(), 100);

        // 4. Auto-Sync on load if Native (Once)
        if (window.HydroFluxNative) {
            window.HydroFluxNative.requestHealthPermissions();
        }
    }

    render() {
        // --- Logic for Activity Rings ---
        const stepPercent = Math.min((this.data.steps.current / this.data.steps.goal) * 100, 100);
        const sleepPercent = Math.min((this.data.sleep.current / this.data.sleep.goal) * 100, 100);

        const center = 100;
        const radiusOuter = 80;
        const radiusInner = 55;
        const circumOuter = 2 * Math.PI * radiusOuter;
        const circumInner = 2 * Math.PI * radiusInner;

        // --- Logic for Weekly Schedule ---
        const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
        const todayIndex = new Date().getDay();
        const todayName = days[todayIndex];
        const plan = this.schedule[todayName];

        this.container.innerHTML = `
            <div class="fitness-container">
                <!-- SECTION 1: ACTIVITY RINGS -->
                <h2 class="section-title">DAILY ACTIVITY</h2>
                <div class="rings-wrapper">
                    <svg class="concentric-svg" viewBox="0 0 200 200">
                        <circle class="ring-bg" cx="${center}" cy="${center}" r="${radiusOuter}" stroke-width="18"></circle>
                        <circle class="ring-bg" cx="${center}" cy="${center}" r="${radiusInner}" stroke-width="18"></circle>
                        
                        <circle class="ring-progress cyan" cx="${center}" cy="${center}" r="${radiusOuter}" 
                            stroke-width="18"
                            stroke-dasharray="${circumOuter}" 
                            stroke-dashoffset="${circumOuter}"
                            data-offset="${circumOuter - (stepPercent / 100) * circumOuter}"></circle>
                            
                        <circle class="ring-progress purple" cx="${center}" cy="${center}" r="${radiusInner}" 
                            stroke-width="18"
                            stroke-dasharray="${circumInner}" 
                            stroke-dashoffset="${circumInner}"
                            data-offset="${circumInner - (sleepPercent / 100) * circumInner}"></circle>
                            
                        <image href="https://fonts.gstatic.com/s/i/materialicons/bolt/v5/24px.svg" x="90" y="90" height="20" width="20" style="filter: invert(1); opacity: 0.5;" />
                    </svg>
                    
                    <div class="rings-stats">
                        <div class="stat-item cyan">
                            <span class="stat-label-small"><span class="dot cyan"></span> STEPS</span>
                            <span class="stat-number" id="steps-display">${this.data.steps.current.toLocaleString()}</span>
                        </div>
                        <div class="stat-item purple">
                            <span class="stat-label-small"><span class="dot purple"></span> SLEEP</span>
                            <span class="stat-number" id="sleep-display">${this.data.sleep.current}h</span>
                        </div>
                    </div>
                </div>

                <div class="device-card">
                    <div class="device-info">
                        <span class="device-name">TicWatch Pro 5</span>
                        <span class="device-status">Disconnected</span>
                    </div>
                    <button id="connect-watch-btn" class="connect-glow-btn">UPDATE</button>
                </div>

                <!-- SECTION 2: WEEKLY SCHEDULE -->
                <h2 class="section-title" style="margin-top: 30px;">WEEKLY SCHEDULE</h2>

                <div class="workout-card glow-card">
                    <div class="card-header">
                        <span class="day-badge">TODAY: ${todayName.toUpperCase()}</span>
                        <h3 class="workout-type" style="color: ${plan.color}">${plan.type}</h3>
                    </div>
                    <div class="exercise-list">
                        ${plan.exercises.map(ex => `
                            <div class="exercise-item">
                                <span class="ex-name">${ex.name}</span>
                                <span class="ex-meta">${ex.sets} <span class="ex-note">• ${ex.note}</span></span>
                            </div>
                        `).join('')}
                    </div>
                </div>

                <div class="schedule-list">
                    <h3 class="subsection-title">UPCOMING</h3>
                    ${days.map((d, i) => {
            if (d === todayName) return '';
            const p = this.schedule[d];
            return `
                            <div class="schedule-row ${i === todayIndex ? 'active' : ''}">
                                <span class="sch-day">${d.substring(0, 3)}</span>
                                <span class="sch-type" style="color: ${p.color}">${p.type}</span>
                            </div>
                        `;
        }).join('')}
                </div>

                <!-- SECTION 3: CALENDAR HISTORY -->
                <h2 class="section-title" style="margin-top: 30px;">HISTORY LOG</h2>
                <div class="calendar-wrapper" style="margin-bottom: 20px;">
                    <div class="calendar-header">
                        <button class="cal-nav-btn" id="fit-prev-month">&lt;</button>
                        <span id="cal-month-label-fit">Month</span>
                        <button class="cal-nav-btn" id="fit-next-month">&gt;</button>
                    </div>
                    <div class="calendar-grid" id="fit-calendar-grid"></div>
                </div>

            </div>
        `;

        this.renderCalendar();
        this.attachEvents();
    }

    // --- Calendar Logic ---
    changeMonth(offset) {
        this.viewDate.setMonth(this.viewDate.getMonth() + offset);
        this.renderCalendar();
    }

    renderCalendar() {
        const grid = this.container.querySelector('#fit-calendar-grid');
        const monthLabel = this.container.querySelector('#cal-month-label-fit');
        if (!grid || !monthLabel) return;

        grid.innerHTML = '';

        const year = this.viewDate.getFullYear();
        const month = this.viewDate.getMonth();
        const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        monthLabel.textContent = `${months[month]} ${year}`;

        const firstDay = new Date(year, month, 1).getDay();
        const daysInMonth = new Date(year, month + 1, 0).getDate();

        // Loop Days
        const daysShort = ['S', 'M', 'T', 'W', 'T', 'F', 'S'];
        daysShort.forEach(d => grid.innerHTML += `<div class="cal-day-label">${d}</div>`);
        for (let i = 0; i < firstDay; i++) grid.innerHTML += `<div></div>`;

        const todayStr = new Date().toDateString();

        for (let i = 1; i <= daysInMonth; i++) {
            const dateObj = new Date(year, month, i);
            const dateKey = dateObj.toDateString();

            let classes = 'cal-day';

            // Check History (Prioritize Steps Goal)
            if (this.data.history[dateKey]) {
                const record = this.data.history[dateKey];
                // Success = Steps > Goal (10k) OR Sleep > 7h
                if (record.steps >= 10000 || record.sleep >= 7) {
                    classes += ' start-date active'; // Cyan glow (Success)
                } else {
                    classes += ' active'; // Just active (Purple/Normal)
                }
            }

            if (dateKey === todayStr) classes += ' today';

            grid.innerHTML += `<div class="${classes}">${i}</div>`;
        }
    }

    animate() {
        this.container.querySelectorAll('.ring-progress').forEach(ring => {
            ring.style.strokeDashoffset = ring.dataset.offset;
        });
    }

    attachEvents() {
        const btn = this.container.querySelector('#connect-watch-btn');
        if (btn) {
            btn.addEventListener('click', () => {
                // Feature Detection for Native Android Bridge
                if (window.HydroFluxNative) {
                    btn.textContent = "REQUESTING...";
                    window.HydroFluxNative.requestHealthPermissions();

                    // Fallback reset if no response in 5s
                    setTimeout(() => {
                        if (btn.textContent === "REQUESTING...") btn.textContent = "UPDATE";
                    }, 5000);
                } else {
                    alert("This feature requires the Android App!");
                }
            });
        }

        // Calendar Nav
        const prevBtn = this.container.querySelector('#fit-prev-month');
        const nextBtn = this.container.querySelector('#fit-next-month');
        if (prevBtn) prevBtn.addEventListener('click', () => this.changeMonth(-1));
        if (nextBtn) nextBtn.addEventListener('click', () => this.changeMonth(1));
    }
}
