export class WaterTracker {
    constructor(containerId) {
        this.container = document.getElementById(containerId);
        this.state = {
            current: 0,
            goal: 3000,
            bottleSize: 500,
            lastActiveDate: new Date().toISOString(),
            history: {} // Format: "YYYY-MM-DD": { current: 2000, goal: 3000 }
        };
        this.STORAGE_KEY = 'hydroflux_data';
        this.viewDate = new Date(); // For Calendar

        this.loadState();
        this.render();
        this.attachEvents();
        this.updateUI();
        this.setupSettings(); // New Settings Logic
    }

    loadState() {
        const saved = localStorage.getItem(this.STORAGE_KEY);
        if (saved) {
            const parsed = JSON.parse(saved);
            this.state = { ...this.state, ...parsed };
            if (!this.state.history) this.state.history = {}; // Safety init

            // Check for 1AM Reset
            this.checkDailyReset();
        }
    }

    checkDailyReset() {
        const now = new Date();
        const lastDate = this.state.lastActiveDate ? new Date(this.state.lastActiveDate) : new Date(0);

        // Logic: if it is a NEW day (past 1am), reset.
        if (now.toDateString() !== lastDate.toDateString()) {
            if (now.getHours() >= 1) {
                this.state.current = 0;
            }
        }

        this.state.lastActiveDate = now.toISOString();
        this.saveState();
    }

    saveState() {
        // Record History for Today
        const todayKey = new Date().toDateString(); // "Fri Dec 26 2025" logic
        this.state.history[todayKey] = {
            current: this.state.current,
            goal: this.state.goal
        };

        localStorage.setItem(this.STORAGE_KEY, JSON.stringify(this.state));
        this.updateUI(); // Updates UI and Calendar
        this.renderCalendar();
    }

    addWater() {
        this.state.current += this.state.bottleSize;
        this.saveState();
        if (navigator.vibrate) navigator.vibrate(50);
    }

    removeWater() {
        this.state.current = Math.max(0, this.state.current - this.state.bottleSize);
        this.saveState();
        if (navigator.vibrate) navigator.vibrate(50);
    }

    setBottleSize(size) {
        if (!size || size <= 0) return;
        this.state.bottleSize = size;
        this.saveState();
        // Update input field if visible
        const input = document.getElementById('bottle-size-input');
        if (input) input.value = size;
    }

    setGoal(goal) {
        if (!goal || goal <= 0) return;
        this.state.goal = goal;
        this.saveState();
    }

    getPercentage() {
        return Math.min(100, Math.max(0, (this.state.current / this.state.goal) * 100));
    }

    updateUI() {
        // Update Text
        const currentEl = this.container.querySelector('.water-count');
        const percentageEl = this.container.querySelector('.water-percentage');

        if (currentEl) currentEl.textContent = `${this.state.current} / ${this.state.goal} mL`;
        if (percentageEl) percentageEl.textContent = `${Math.round(this.getPercentage())}%`;

        // Update Wave Animation
        const wave = this.container.querySelector('.wave');
        if (wave) {
            wave.style.top = `${100 - this.getPercentage()}%`;
        }
    }

    // --- Calendar Logic ---
    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-water');
        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
            if (this.state.history[dateKey]) {
                const record = this.state.history[dateKey];
                if (record.current >= record.goal) {
                    classes += ' start-date active'; // Cyan glow for success
                } else if (record.current > 0) {
                    // Partial highlight could go here, but let's keep it simple
                    classes += ' active'; // Purple fallback or just active
                }
            }

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

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

    render() {
        this.container.innerHTML = `
            <div class="water-tracker-container">
                <!-- Circular Progress -->
                <div class="circle-container">
                    <div class="water-circle">
                        <div class="wave"></div>
                        <div class="circle-content">
                            <span class="water-percentage">0%</span>
                            <span class="water-label">HYDRATION</span>
                        </div>
                    </div>
                </div>

                <!-- Stats Display -->
                <div class="stats-row">
                    <span class="water-count">0 / 3000 mL</span>
                </div>

                <!-- Controls -->
                <div class="controls-area">
                    <div class="bottle-selector">
                        <label>Bottle (mL):</label>
                        <input type="number" id="bottle-size-input" value="${this.state.bottleSize}" min="1" max="5000">
                    </div>

                    <div class="action-buttons">
                        <button id="remove-water-btn" class="icon-btn secondary" aria-label="Remove Drink">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 12h14"/></svg>
                        </button>

                        <button id="add-water-btn" class="glow-btn">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"/></svg>
                            DRINK
                        </button>

                        <button id="notify-btn" class="icon-btn" title="Enable Reminders">
                            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path>
                                <path d="M13.73 21a2 2 0 0 1-3.46 0"></path>
                            </svg>
                        </button>
                    </div>
                </div>

                <!-- Hydration Calendar -->
                <div class="calendar-wrapper" style="margin-bottom: 0;">
                    <div class="calendar-header">
                        <button class="cal-nav-btn" id="water-prev-month">&lt;</button>
                        <span id="cal-month-label-water">Month</span>
                        <button class="cal-nav-btn" id="water-next-month">&gt;</button>
                    </div>
                    <div class="calendar-grid"></div>
                </div>
            </div>
        `;

        this.checkNotificationStatus();
        this.renderCalendar();
    }

    attachEvents() {
        this.container.querySelector('#add-water-btn').addEventListener('click', () => this.addWater());
        this.container.querySelector('#remove-water-btn').addEventListener('click', () => this.removeWater());

        this.container.querySelector('#notify-btn').addEventListener('click', (e) => this.toggleNotifications(e.currentTarget));

        this.container.querySelector('#bottle-size-input').addEventListener('change', (e) => {
            this.setBottleSize(parseInt(e.target.value));
        });

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

    // --- Settings Modal Logic ---
    setupSettings() {
        const modal = document.getElementById('settings-modal');
        const openBtn = document.getElementById('open-settings-btn');
        const closeBtn = document.getElementById('close-settings-btn');
        const saveBtn = document.getElementById('save-settings-btn');

        const goalInput = document.getElementById('setting-goal-input');
        const bottleInput = document.getElementById('setting-bottle-input');

        if (openBtn) {
            openBtn.addEventListener('click', () => {
                // Populate inputs
                goalInput.value = this.state.goal;
                bottleInput.value = this.state.bottleSize;
                modal.style.display = 'flex';
            });
        }

        if (closeBtn) {
            closeBtn.addEventListener('click', () => {
                modal.style.display = 'none';
            });
        }

        if (saveBtn) {
            saveBtn.addEventListener('click', () => {
                const newGoal = parseInt(goalInput.value);
                const newBottle = parseInt(bottleInput.value);

                if (newGoal) this.setGoal(newGoal);
                if (newBottle) this.setBottleSize(newBottle);

                modal.style.display = 'none';
                alert("Settings Saved!");
            });
        }
    }

    // --- Notification Logic ---
    toggleNotifications(btn) {
        if (!("Notification" in window)) {
            alert("Notifications coming soon to the Android App version!");
            return;
        }

        if (Notification.permission === "granted") {
            alert("Reminders are active! We'll check every hour.");
        } else if (Notification.permission !== "denied") {
            Notification.requestPermission().then(permission => {
                if (permission === "granted") {
                    this.startReminderLoop();
                    btn.style.color = "var(--primary-cyan)";
                    new Notification("HydroFlux", { body: "Smart Hydration Reminders Enabled!" });
                }
            });
        }
    }

    checkNotificationStatus() {
        if (!('Notification' in window)) return;

        if (Notification.permission === "granted") {
            const btn = this.container.querySelector('#notify-btn');
            if (btn) btn.style.color = "var(--primary-cyan)";
            this.startReminderLoop();
        }
    }

    startReminderLoop() {
        if (!('Notification' in window)) return;

        // Clear existing to avoid duplicates
        if (this.reminderInterval) clearInterval(this.reminderInterval);

        // Check every minute if it's been > 1 hour since last drink
        this.reminderInterval = setInterval(() => {
            // Pseudo-logic check since we don't store timestamp in this simple version yet
            // In a real app, you'd check this.state.lastDrinkTime
            new Notification("HydroFlux Needs You", {
                body: "Remember to drink water!",
                icon: "/icon.png"
            });
        }, 3600000); // 1 Hour
    }
}
