export class WaterView {
    constructor(containerId, app) {
        this.container = document.getElementById(containerId);
        this.app = app;
        this.history = JSON.parse(localStorage.getItem('hydroflux_water_history') || '[]');
        this.render();
        this.attachEvents();
    }

    render() {
        const data = JSON.parse(localStorage.getItem('hydroflux_data') || '{"current":0,"goal":3.0}');
        const drinkSize = parseInt(localStorage.getItem('hydroflux_drink_size') || '250');
        const percentage = Math.min((data.current / data.goal) * 100, 100);

        this.container.innerHTML = `
            <div class="w-full max-w-md bg-white min-h-screen relative mx-auto bg-gradient-to-br from-blue-50 to-blue-100 flex flex-col h-screen">
                <!-- Header -->
                <div class="flex justify-between items-center p-6 relative z-10 shrink-0">
                    <button id="backBtn" class="w-10 h-10 rounded-full bg-white bg-opacity-50 backdrop-blur-md flex items-center justify-center shadow-sm">
                        <svg class="w-6 h-6 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>
                    </button>
                    <span class="text-lg font-bold text-gray-800">Hydration</span>
                    <!-- Settings Cog -->
                    <button id="settingsBtn" class="w-10 h-10 rounded-full bg-white bg-opacity-50 backdrop-blur-md flex items-center justify-center shadow-sm">
                         <svg class="w-6 h-6 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>
                    </button>
                </div>

                <!-- Main Content Scrollable Area -->
                <div class="flex-1 overflow-y-auto pb-32">
                    
                    <!-- Main Visualization (Circular) -->
                    <div class="flex flex-col items-center justify-center py-6">
                        <div class="relative w-64 h-64 rounded-full border-8 border-white shadow-2xl overflow-hidden bg-blue-50">
                            <!-- Water Fill -->
                            <div class="absolute bottom-0 left-0 w-full water-container transition-all duration-700" 
                                style="height: ${percentage}%; background: linear-gradient(180deg, #60A5FA 0%, #3B82F6 100%);">
                                <svg class="absolute top-0 left-0 w-full wave-animation" viewBox="0 0 1200 120" preserveAspectRatio="none" style="height: 40px; transform: translateY(-50%); width: 200%;">
                                    <path d="M0,50 Q300,10 600,50 T1200,50 L1200,120 L0,120 Z" fill="#60A5FA" />
                                </svg>
                            </div>
                            
                            <!-- Center Text Overlay -->
                            <div class="absolute inset-0 flex flex-col items-center justify-center z-10">
                                <div class="text-5xl font-bold ${percentage > 50 ? 'text-white' : 'text-blue-600'} drop-shadow-md transition-colors duration-500">${data.current.toFixed(1)}L</div>
                                <div class="font-medium text-sm mt-1 uppercase tracking-wide ${percentage > 50 ? 'text-blue-100' : 'text-gray-500'} transition-colors duration-500">of ${data.goal.toFixed(1)}L Goal</div>
                            </div>
                        </div>
                    </div>

                    <!-- History Section -->
                    <div class="px-6 mt-4">
                        <h3 class="font-bold text-gray-800 text-lg mb-4">Today's History</h3>
                        <div class="space-y-3" id="historyList">
                            ${(() => {
                const todayStart = new Date();
                todayStart.setHours(0, 0, 0, 0);
                const todaysEntries = this.history.filter(h => h.timestamp >= todayStart.getTime());

                return todaysEntries.length === 0 ?
                    '<div class="text-center text-gray-400 py-4 text-sm">No drinks logged yet today.</div>' :
                    todaysEntries.slice().reverse().map(entry => `
                                <div class="flex items-center justify-between p-4 rounded-xl bg-white shadow-sm border border-blue-50">
                                    <div class="flex items-center gap-3">
                                        <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center text-blue-500">
                                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                        </div>
                                        <div>
                                            <div class="font-semibold text-gray-700">Water</div>
                                            <div class="text-xs text-gray-400">${new Date(entry.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</div>
                                        </div>
                                    </div>
                                    <span class="font-bold text-gray-800">+${entry.amount}ml</span>
                                </div>
                            `).join('');
            })()}
                        </div>
                    </div>
                </div>

                <!-- Floating Controls -->
                <div class="absolute bottom-6 left-6 right-6 z-20 bg-white rounded-3xl shadow-xl p-4 border border-blue-50">
                    <div class="flex justify-between items-center">
                        <button class="w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center text-gray-600 hover:bg-gray-200 active:scale-95 transition-transform" id="removeWater">
                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4"></path></svg>
                        </button>
                        
                        <button class="w-20 h-20 rounded-full bg-blue-500 shadow-xl shadow-blue-200 hover:shadow-blue-300 flex items-center justify-center transform hover:scale-105 active:scale-95 transition-all -mt-8 border-4 border-white" id="addWater">
                            <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
                        </button>
                        
                        <!-- Drink Size Selector -->
                        <div class="flex flex-col items-center gap-1 cursor-pointer group" id="drinkSizeBtn">
                            <span class="text-[10px] text-gray-500 font-medium uppercase group-hover:text-blue-500 transition-colors">Size</span>
                            <div class="w-14 h-14 rounded-2xl border-2 border-blue-100 flex items-center justify-center text-blue-500 font-bold bg-blue-50 group-hover:bg-blue-100 transition-colors relative text-sm">
                                ${drinkSize}
                                <div class="absolute -top-1 -right-1 w-3 h-3 bg-blue-500 rounded-full flex items-center justify-center">
                                    <svg class="w-2 h-2 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"></path></svg>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Size Selection Modal (Hidden) -->
                <div id="sizeModal" class="hidden absolute bottom-0 left-0 w-full z-50 h-full flex flex-col justify-end">
                    <div class="absolute inset-0 bg-black bg-opacity-20 backdrop-blur-sm" id="closeModalMask"></div>
                    <div class="bg-white rounded-t-3xl p-8 shadow-[0_-10px_40px_rgba(0,0,0,0.1)] relative animate-slide-up z-50">
                        <div class="w-12 h-1 bg-gray-200 rounded-full mx-auto mb-6"></div>
                        <h3 class="font-bold text-gray-800 text-lg mb-4 text-center">Select Amount</h3>
                        
                        <!-- Custom Input -->
                        <div class="flex gap-2 mb-6">
                            <input type="number" id="customAmountInput" placeholder="Custom ml" class="flex-1 bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-lg font-bold text-gray-800 focus:ring-2 focus:ring-blue-500 outline-none">
                            <button id="applyCustom" class="px-6 py-3 bg-blue-500 text-white font-bold rounded-xl shadow-md">Set</button>
                        </div>

                        <div class="grid grid-cols-3 gap-3 mb-6">
                            ${[100, 250, 330, 500, 750, 1000].map(size => `
                                <button class="size-option py-3 rounded-xl border-2 ${size === drinkSize ? 'border-blue-500 bg-blue-50 text-blue-600' : 'border-gray-100 text-gray-600 hover:bg-gray-50'} font-bold transition-all text-sm" data-size="${size}">
                                    ${size}ml
                                </button>
                            `).join('')}
                        </div>
                        <button id="closeModal" class="w-full py-3 rounded-xl bg-gray-100 text-gray-600 font-bold">Cancel</button>
                    </div>
                </div>

                <!-- Goal Settings Modal (New) -->
                <div id="goalModal" class="hidden absolute bottom-0 left-0 w-full z-50 h-full flex flex-col justify-end">
                    <div class="absolute inset-0 bg-black bg-opacity-20 backdrop-blur-sm" id="closeGoalModalMask"></div>
                    <div class="bg-white rounded-t-3xl p-8 shadow-[0_-10px_40px_rgba(0,0,0,0.1)] relative animate-slide-up z-50">
                        <div class="w-12 h-1 bg-gray-200 rounded-full mx-auto mb-6"></div>
                        <h3 class="font-bold text-gray-800 text-lg mb-2 text-center">Daily Goal</h3>
                         <p class="text-center text-gray-400 text-sm mb-6">Set your hydration target</p>
                        
                        <div class="flex items-center justify-center gap-4 mb-8">
                             <button id="decreaseGoal" class="w-12 h-12 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center font-bold text-xl hover:bg-blue-200">−</button>
                             <div class="text-4xl font-bold text-gray-800 w-24 text-center" id="goalDisplay">${data.goal.toFixed(1)}</div>
                             <button id="increaseGoal" class="w-12 h-12 rounded-full bg-blue-100 text-blue-600 flex items-center justify-center font-bold text-xl hover:bg-blue-200">+</button>
                        </div>
                        
                        <button id="saveGoal" class="w-full py-4 rounded-xl bg-blue-500 text-white font-bold shadow-lg shadow-blue-200">Save Goal</button>
                    </div>
                </div>
            </div>
            <style>
                @keyframes slide-up { from { transform: translateY(100%); } to { transform: translateY(0); } }
                .animate-slide-up { animation: slide-up 0.3s cubic-bezier(0.16, 1, 0.3, 1); }
            </style>
        `;
    }

    addHistory(amount) {
        this.history.push({
            timestamp: Date.now(),
            amount: amount
        });
        localStorage.setItem('hydroflux_water_history', JSON.stringify(this.history));
    }

    attachEvents() {
        this.container.querySelector('#backBtn').addEventListener('click', () => {
            this.app.back();
        });

        const updateWater = (amount) => {
            const data = JSON.parse(localStorage.getItem('hydroflux_data') || '{"current":0,"goal":3.0}');
            data.current = Math.min(data.current + (amount / 1000), data.goal); // amount in ml to L
            localStorage.setItem('hydroflux_data', JSON.stringify(data));
            this.addHistory(amount);
            this.render();
            this.attachEvents();
        };

        this.container.querySelector('#addWater').addEventListener('click', () => {
            const drinkSize = parseInt(localStorage.getItem('hydroflux_drink_size') || '250');
            updateWater(drinkSize);
        });

        this.container.querySelector('#removeWater').addEventListener('click', () => {
            // Removing doesn't add to history, usually just undoes
            const data = JSON.parse(localStorage.getItem('hydroflux_data') || '{"current":0,"goal":3.0}');
            const drinkSize = parseInt(localStorage.getItem('hydroflux_drink_size') || '250');
            data.current = Math.max(data.current - (drinkSize / 1000), 0);
            localStorage.setItem('hydroflux_data', JSON.stringify(data));

            // Optionally remove last history entry if it matches? 
            // For now just keep it simple
            this.render();
            this.attachEvents();
        });

        // Modal Logic
        const modal = this.container.querySelector('#sizeModal');
        const openModal = () => modal.classList.remove('hidden');
        const closeModal = () => modal.classList.add('hidden');

        this.container.querySelector('#drinkSizeBtn').addEventListener('click', openModal);
        this.container.querySelector('#closeModal').addEventListener('click', closeModal);
        this.container.querySelector('#closeModalMask').addEventListener('click', closeModal);

        this.container.querySelectorAll('.size-option').forEach(btn => {
            btn.addEventListener('click', () => {
                localStorage.setItem('hydroflux_drink_size', btn.dataset.size);
                closeModal();
                this.render();
                this.attachEvents();
            });
        });

        // Custom Input Logic
        this.container.querySelector('#applyCustom').addEventListener('click', () => {
            const val = this.container.querySelector('#customAmountInput').value;
            if (val && val > 0) {
                localStorage.setItem('hydroflux_drink_size', val);
                closeModal();
                this.render();
                this.attachEvents();
            }
        });

        // Goal Modal Logic
        const goalModal = this.container.querySelector('#goalModal');
        const openGoalModal = () => goalModal.classList.remove('hidden');
        const closeGoalModal = () => goalModal.classList.add('hidden');

        this.container.querySelector('#settingsBtn').addEventListener('click', openGoalModal);
        this.container.querySelector('#closeGoalModalMask').addEventListener('click', closeGoalModal);

        let tempGoal = parseFloat(this.container.querySelector('#goalDisplay').innerText);

        this.container.querySelector('#increaseGoal').addEventListener('click', () => {
            tempGoal = Math.min(tempGoal + 0.5, 10.0);
            this.container.querySelector('#goalDisplay').innerText = tempGoal.toFixed(1);
        });

        this.container.querySelector('#decreaseGoal').addEventListener('click', () => {
            tempGoal = Math.max(tempGoal - 0.5, 0.5);
            this.container.querySelector('#goalDisplay').innerText = tempGoal.toFixed(1);
        });

        this.container.querySelector('#saveGoal').addEventListener('click', () => {
            const data = JSON.parse(localStorage.getItem('hydroflux_data') || '{"current":0,"goal":3.0}');
            data.goal = tempGoal;
            localStorage.setItem('hydroflux_data', JSON.stringify(data));
            closeGoalModal();
            this.render();
            this.attachEvents();
        });
    }
}
