// API Base URL
const API_URL = 'http://localhost:8000/api';

// Navigation
function navigate(page) {
    // Hide all pages
    document.querySelectorAll('[id$="-page"]').forEach(el => {
        el.classList.add('hidden');
    });
    
    // Show selected page
    const pageEl = document.getElementById(`${page}-page`);
    if (pageEl) {
        pageEl.classList.remove('hidden');
    }
    
    // Update active nav
    document.querySelectorAll('.nav-item').forEach(el => {
        el.classList.remove('active');
    });
    event.target.closest('.nav-item')?.classList.add('active');
    
    // Update title
    const titles = {
        dashboard: 'ダッシュボード',
        timer: '学習記録',
        stats: '統計',
        calendar: 'カレンダー',
        goals: '目標設定',
        settings: '設定'
    };
    document.getElementById('page-title').textContent = titles[page];
}

// Auth Functions
async function logout() {
    try {
        await fetch(`${API_URL}/auth/logout`, {
            method: 'POST'
        });
        window.location.href = '/login.html';
    } catch (error) {
        console.error('Logout failed:', error);
    }
}

// Dashboard Functions
async function loadDashboard() {
    try {
        const response = await fetch(`${API_URL}/dashboard/`);
        const data = await response.json();
        
        if (response.ok) {
            // Update dashboard with data
            console.log('Dashboard data:', data);
        }
    } catch (error) {
        console.error('Failed to load dashboard:', error);
    }
}

// Timer Functions
class StudyTimer {
    constructor() {
        this.isRunning = false;
        this.isPaused = false;
        this.timeRemaining = 25 * 60; // 25 minutes default
        this.totalTime = 25 * 60;
        this.startTime = null;
        this.pausedTime = 0;
    }
    
    start() {
        this.isRunning = true;
        this.isPaused = false;
        this.startTime = Date.now() - (this.totalTime - this.timeRemaining) * 1000;
        this.run();
    }
    
    run() {
        if (!this.isRunning) return;
        
        const elapsed = Math.floor((Date.now() - this.startTime) / 1000);
        this.timeRemaining = this.totalTime - elapsed;
        
        if (this.timeRemaining <= 0) {
            this.stop();
            this.notify('学習セッションが終了しました');
            return;
        }
        
        this.updateDisplay();
        setTimeout(() => this.run(), 100);
    }
    
    pause() {
        this.isPaused = true;
        this.isRunning = false;
    }
    
    resume() {
        this.isRunning = true;
        this.isPaused = false;
        this.startTime = Date.now() - (this.totalTime - this.timeRemaining) * 1000;
        this.run();
    }
    
    stop() {
        this.isRunning = false;
        this.isPaused = false;
    }
    
    reset(minutes = 25) {
        this.stop();
        this.timeRemaining = minutes * 60;
        this.totalTime = minutes * 60;
        this.updateDisplay();
    }
    
    updateDisplay() {
        const hours = Math.floor(this.timeRemaining / 3600);
        const minutes = Math.floor((this.timeRemaining % 3600) / 60);
        const seconds = this.timeRemaining % 60;
        
        const display = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
        const timerEl = document.querySelector('.timer-circle');
        if (timerEl) {
            timerEl.textContent = display;
        }
    }
    
    notify(message) {
        if ('Notification' in window) {
            new Notification('Study Timer', {
                body: message,
                icon: '📚'
            });
        }
    }
}

const timer = new StudyTimer();

// Session Functions
async function recordSession(subject, startTime, endTime, memo = '') {
    try {
        const response = await fetch(`${API_URL}/sessions/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                subject,
                start_time: startTime,
                end_time: endTime,
                memo
            })
        });
        
        const data = await response.json();
        if (response.ok) {
            console.log('Session recorded:', data);
            return data;
        } else {
            console.error('Failed to record session:', data.error);
        }
    } catch (error) {
        console.error('Error recording session:', error);
    }
}

async function getSessions(dateFrom, dateTo) {
    try {
        const response = await fetch(`${API_URL}/sessions/?from=${dateFrom}&to=${dateTo}`);
        const data = await response.json();
        
        if (response.ok) {
            return data.sessions;
        }
    } catch (error) {
        console.error('Failed to load sessions:', error);
    }
}

// Stats Functions
async function loadStats(period = 'week') {
    try {
        const response = await fetch(`${API_URL}/stats/?period=${period}`);
        const data = await response.json();
        
        if (response.ok) {
            console.log('Stats data:', data);
            return data;
        }
    } catch (error) {
        console.error('Failed to load stats:', error);
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
    // Request notification permission
    if ('Notification' in window && Notification.permission === 'default') {
        Notification.requestPermission();
    }
    
    // Load dashboard data
    loadDashboard();
    
    // Timer button handlers (placeholder)
    console.log('App initialized');
});
