export class StreakTracker {
    constructor(containerId) {
        this.container = document.getElementById(containerId);
        this.STORAGE_KEY = 'hydroflux_streak';
        this.quotes = [
            "The only easy day was yesterday.",
            "Discipline is doing what needs to be done, even if you don't want to.",
            "Your future self is watching you right now through memories.",
            "Pain is temporary. Quitting lasts forever.",
            "Suffering is the currency of success.",
            "Don't stop when you're tired. Stop when you're done.",
            "You are stronger than your urges.",
            "Focus on the goal, not the obstacle."
        ];

        this.viewDate = new Date(); // For Calendar Navigation
        this.loadState();
        this.render();
        this.startTimer();
    }

    loadState() {
        const saved = localStorage.getItem(this.STORAGE_KEY);
        if (saved) {
            this.startDate = new Date(parseInt(saved));
        } else {
            this.startDate = new Date();
            this.saveState();
        }
    }

    saveState() {
        localStorage.setItem(this.STORAGE_KEY, this.startDate.getTime().toString());
    }

    resetStreak() {
        if (confirm("Are you sure you want to reset your streak?")) {
            this.startDate = new Date();
            this.saveState();
            this.updateUI();
            this.renderCalendar(); // Refresh calendar

            // Haptic Bad Feedback
            if (navigator.vibrate) navigator.vibrate([100, 50, 100]);
        }
    }

    getDuration() {
        const now = new Date();
        const diff = now - this.startDate;

        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

        return { days, hours, minutes };
    }

    updateUI() {
        const { days, hours, minutes } = this.getDuration();

        const daysEl = this.container.querySelector('.streak-days');
        const detailEl = this.container.querySelector('.streak-detail');

        if (daysEl) daysEl.textContent = days;
        if (detailEl) detailEl.textContent = `${hours}h ${minutes}m`;
    }

    startTimer() {
        setInterval(() => this.updateUI(), 60000); // Update every minute
    }

    getRandomQuote() {
        return this.quotes[Math.floor(Math.random() * this.quotes.length)];
    }

    changeMonth(offset) {
        this.viewDate.setMonth(this.viewDate.getMonth() + offset);
        this.renderCalendar();
    }

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

        grid.innerHTML = '';

        const year = this.viewDate.getFullYear();
        const month = this.viewDate.getMonth();

        // Month Names
        const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        monthLabel.textContent = `${months[month]} ${year}`;

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

        // Adjust for Monday start if preferred, but let's stick to Sun=0 for standard
        const paddingDays = firstDay;

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

        // Padding
        for (let i = 0; i < paddingDays; i++) {
            grid.innerHTML += `<div></div>`;
        }

        const now = new Date();
        const todayStr = now.toDateString();
        const startStr = this.startDate.toDateString();

        // Days
        for (let i = 1; i <= daysInMonth; i++) {
            const currentObj = new Date(year, month, i);
            const currentStr = currentObj.toDateString();

            let classes = 'cal-day';

            // Check if within streak (Active)
            // Active if: current >= startDate AND current <= now
            if (currentObj >= this.startDate && currentObj <= now) {
                // Determine if it's the exact start date for special styling
                if (currentStr === startStr) {
                    classes += ' start-date active';
                } else {
                    classes += ' active';
                }
            } else if (currentStr === startStr) {
                // Even if in future (impossible logic wise but for safety) or just start
                classes += ' start-date';
            }

            // Today marker
            if (currentStr === todayStr) {
                classes += ' today';
            }

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

    render() {
        this.container.innerHTML = `
            <div class="streak-container">
                <h2 class="section-title">QUIT STREAK</h2>
                
                <div class="streak-counter">
                    <div class="streak-days glow-text">0</div>
                    <div class="streak-label">DAYS</div>
                    <div class="streak-detail">0h 0m</div>
                </div>

                 <!-- Calendar Module -->
                <div class="calendar-wrapper">
                    <div class="calendar-header">
                        <button class="cal-nav-btn" id="prev-month">&lt;</button>
                        <span id="cal-month-label">Month</span>
                        <button class="cal-nav-btn" id="next-month">&gt;</button>
                    </div>
                    <div class="calendar-grid">
                        <!-- JS Injected -->
                    </div>
                </div>

                <div class="quote-card">
                    "${this.getRandomQuote()}"
                </div>

                <button id="reset-streak-btn" class="danger-btn">
                    RESET STREAK
                </button>
            </div>
        `;

        this.updateUI();
        this.renderCalendar();

        this.container.querySelector('#reset-streak-btn').addEventListener('click', () => {
            this.resetStreak();
        });

        this.container.querySelector('#prev-month').addEventListener('click', () => {
            this.changeMonth(-1);
        });

        this.container.querySelector('#next-month').addEventListener('click', () => {
            this.changeMonth(1);
        });
    }
}
