{% extends "base.html" %}

{% block title %}cuti - Todo Manager{% endblock %}

{% block head %}
<style>
/* Page Layout */
.todos-page {
    max-width: 1400px;
    margin: 0 auto;
    padding: 2rem;
}

/* Page Header */
.page-header-section {
    margin-bottom: 2.5rem;
}

.page-title {
    font-size: 1.8rem;
    font-weight: 700;
    color: var(--text-primary);
    margin: 0 0 0.5rem 0;
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.page-title-icon {
    width: 40px;
    height: 40px;
    background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 2px 8px rgba(245, 158, 11, 0.2);
}

.page-title-icon i {
    color: white;
    font-size: 20px;
}

.page-subtitle {
    color: var(--text-muted);
    margin: 0;
    font-size: 0.95rem;
    margin-left: 52px;
}

/* Stats Bar */
.stats-bar {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1rem;
    margin-bottom: 2rem;
}

.stat-card {
    background: rgba(255, 255, 255, 0.03);
    border: 1px solid rgba(255, 255, 255, 0.05);
    border-radius: 12px;
    padding: 1.25rem;
    transition: all 0.2s ease;
}

.stat-card:hover {
    background: rgba(255, 255, 255, 0.05);
    border-color: rgba(255, 255, 255, 0.08);
}

.stat-label {
    color: var(--text-muted);
    font-size: 0.85rem;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    margin-bottom: 0.5rem;
}

.stat-value {
    font-size: 1.75rem;
    font-weight: 700;
    color: var(--text-primary);
}

.stat-value.pending { color: #f59e0b; }
.stat-value.progress { color: #3b82f6; }
.stat-value.completed { color: #10b981; }

/* Todos Grid */
.todos-container {
    display: grid;
    gap: 1rem;
}

.todo-card {
    background: rgba(255, 255, 255, 0.03);
    border: 1px solid rgba(255, 255, 255, 0.05);
    border-radius: 12px;
    padding: 1.5rem;
    transition: all 0.2s ease;
    position: relative;
    overflow: hidden;
}

.todo-card::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    width: 4px;
    background: currentColor;
}

.todo-card.status-pending::before { background: #f59e0b; }
.todo-card.status-in_progress::before { background: #3b82f6; }
.todo-card.status-completed::before { background: #10b981; }

.todo-card:hover {
    background: rgba(255, 255, 255, 0.05);
    border-color: rgba(255, 255, 255, 0.08);
    transform: translateY(-2px);
}

.todo-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 1rem;
    margin-bottom: 1rem;
}

.todo-title {
    font-weight: 600;
    font-size: 1.1rem;
    color: var(--text-primary);
    margin: 0;
    flex: 1;
}

.todo-status {
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.03em;
    white-space: nowrap;
}

.status-pending {
    background: rgba(245, 158, 11, 0.15);
    color: #f59e0b;
}

.status-in_progress {
    background: rgba(59, 130, 246, 0.15);
    color: #3b82f6;
}

.status-completed {
    background: rgba(16, 185, 129, 0.15);
    color: #10b981;
}

.todo-content {
    color: var(--text-secondary);
    margin-bottom: 1rem;
    line-height: 1.5;
    font-size: 0.95rem;
}

.todo-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 0.8rem;
    color: var(--text-muted);
    opacity: 0.7;
}

.todo-meta i {
    margin-right: 0.25rem;
    font-size: 0.75rem;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 4rem 2rem;
    color: var(--text-secondary);
}

.empty-state-icon {
    width: 80px;
    height: 80px;
    background: linear-gradient(135deg, rgba(245, 158, 11, 0.1) 0%, rgba(249, 115, 22, 0.1) 100%);
    border-radius: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 1.5rem;
}

.empty-state-icon i {
    font-size: 2.5rem;
    color: #f59e0b;
}

.empty-state-title {
    font-size: 1.5rem;
    font-weight: 700;
    color: var(--text-primary);
    margin-bottom: 0.5rem;
}

.empty-state-description {
    color: var(--text-muted);
    margin-bottom: 2rem;
}

.btn-primary {
    background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%);
    color: white;
    border: none;
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
}

.btn-primary i {
    font-size: 0.9rem;
}

/* Responsive */
@media (max-width: 768px) {
    .stats-bar {
        grid-template-columns: 1fr;
    }
    
    .page-title {
        font-size: 1.5rem;
    }
    
    .todo-header {
        flex-direction: column;
        align-items: flex-start;
    }
}
</style>
{% endblock %}

{% set body_class = "" %}
{% set alpine_data = "todoManager()" %}

{% block content %}
<div class="todos-page">
    <div class="page-header-section">
        <h1 class="page-title">
            <div class="page-title-icon">
                <i class="fas fa-tasks"></i>
            </div>
            Todo Manager
        </h1>
        <p class="page-subtitle">Track your tasks and project goals</p>
    </div>
    
    <!-- Stats Bar -->
    <div class="stats-bar" x-show="todos && todos.length > 0">
        <div class="stat-card">
            <div class="stat-label">Pending</div>
            <div class="stat-value pending" x-text="todos && todos.filter ? todos.filter(t => t.status === 'pending').length : 0"></div>
        </div>
        <div class="stat-card">
            <div class="stat-label">In Progress</div>
            <div class="stat-value progress" x-text="todos && todos.filter ? todos.filter(t => t.status === 'in_progress').length : 0"></div>
        </div>
        <div class="stat-card">
            <div class="stat-label">Completed</div>
            <div class="stat-value completed" x-text="todos && todos.filter ? todos.filter(t => t.status === 'completed').length : 0"></div>
        </div>
        <div class="stat-card">
            <div class="stat-label">Total Tasks</div>
            <div class="stat-value" x-text="todos ? todos.length : 0"></div>
        </div>
    </div>
    
    <!-- Todos Container -->
    <div id="todo-list" class="todos-container" x-show="todos && todos.length > 0">
        <template x-for="todo in (todos || [])" :key="todo && todo.id ? todo.id : Math.random()">
            <div class="todo-card" :class="todo && todo.status ? `status-${todo.status}` : ''">
                <div class="todo-header">
                    <h3 class="todo-title" x-text="todo && todo.content ? todo.content : ''"></h3>
                    <div style="display: flex; gap: 8px; align-items: center;">
                        <select @change="updateTodoStatus(todo, $event.target.value)" 
                                :value="todo.status"
                                class="todo-status-select"
                                style="padding: 4px 8px; border-radius: 4px; border: 1px solid rgba(255,255,255,0.2); background: rgba(0,0,0,0.3); color: white; font-size: 12px;">
                            <option value="pending">Pending</option>
                            <option value="in_progress">In Progress</option>
                            <option value="completed">Completed</option>
                            <option value="blocked">Blocked</option>
                        </select>
                        <button @click="deleteTodo(todo)" 
                                style="padding: 4px 8px; background: rgba(239, 68, 68, 0.2); color: #ef4444; border: 1px solid #ef4444; border-radius: 4px; cursor: pointer; font-size: 12px;"
                                title="Delete todo">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
                <div class="todo-content" x-show="todo.description" x-text="todo.description"></div>
                <div class="todo-meta">
                    <span>
                        <i class="far fa-clock"></i>
                        <span x-text="formatDate(todo.created_at)"></span>
                    </span>
                    <span x-show="todo.updated_at && todo.updated_at !== todo.created_at">
                        <i class="fas fa-sync-alt"></i>
                        <span x-text="`Updated ${formatDate(todo.updated_at)}`"></span>
                    </span>
                </div>
            </div>
        </template>
    </div>
    
    <!-- Add Todo Form -->
    <div class="add-todo-form" style="margin-bottom: 2rem; padding: 1.5rem; background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.05); border-radius: 12px;">
        <div style="display: flex; gap: 1rem; align-items: center;">
            <input 
                id="new-todo"
                type="text" 
                x-model="newTodo"
                @keydown.enter="addTodo()"
                placeholder="Add a new todo..." 
                style="flex: 1; padding: 0.75rem; background: rgba(0, 0, 0, 0.3); border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 8px; color: white; font-size: 1rem;"
                aria-label="New todo input">
            <button 
                @click="addTodo()" 
                class="add-todo btn-primary"
                style="padding: 0.75rem 1.5rem; background: #3b82f6; color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer;"
                :disabled="!newTodo || newTodo.trim() === ''"
                aria-label="Add todo">
                <i class="fas fa-plus"></i> Add Todo
            </button>
        </div>
    </div>
    
    <!-- Empty State -->
    <div x-show="!todos || todos.length === 0" class="empty-state">
        <div class="empty-state-icon">
            <i class="fas fa-clipboard-list"></i>
        </div>
        <div class="empty-state-title">No Todos Yet</div>
        <div class="empty-state-description">
            Start organizing your tasks and goals with the todo system
        </div>
        <button @click="openCLI()" class="btn-primary">
            <i class="fas fa-terminal"></i>
            Open CLI to Add Todos
        </button>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
function todoManager() {
    return {
        todos: [],
        newTodo: '',
        
        async init() {
            await this.loadTodos();
        },
        
        async loadTodos() {
            try {
                // Try the main todos API first
                const response = await fetch('/api/todos');
                if (response.ok) {
                    const data = await response.json();
                    // Extract todos from the response structure
                    if (data.master_todos) {
                        // New API format with master_todos
                        this.todos = data.master_todos.map(item => item.todo);
                    } else if (data.todos) {
                        // Claude logs format
                        this.todos = data.todos;
                    } else if (Array.isArray(data)) {
                        // Direct array format
                        this.todos = data;
                    } else {
                        this.todos = [];
                    }
                } else {
                    // Fallback to claude-logs endpoint
                    const fallbackResponse = await fetch('/api/claude-logs/todos');
                    if (fallbackResponse.ok) {
                        const data = await fallbackResponse.json();
                        this.todos = data.todos || [];
                    } else {
                        this.todos = [];
                    }
                }
            } catch (error) {
                console.error('Error loading todos:', error);
                this.todos = [];
            }
        },
        
        async addTodo() {
            if (!this.newTodo || this.newTodo.trim() === '') return;
            
            const todoData = {
                content: this.newTodo.trim(),
                status: 'pending',
                priority: 'medium',
                tags: [],
                created_at: new Date().toISOString()
            };
            
            try {
                // Save to backend first
                const response = await fetch('/api/todos', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(todoData)
                });
                
                if (response.ok) {
                    const result = await response.json();
                    // Clear input
                    this.newTodo = '';
                    // Reload todos to get the server version with proper ID
                    await this.loadTodos();
                    console.log('Todo created successfully:', result);
                } else {
                    // If backend fails, add locally with temporary ID
                    const localTodo = {
                        id: `temp-${Date.now()}`,
                        ...todoData
                    };
                    this.todos.unshift(localTodo);
                    this.newTodo = '';
                    console.error('Failed to save to backend, added locally');
                }
            } catch (error) {
                console.error('Error adding todo:', error);
                // Add locally on network error
                const localTodo = {
                    id: `temp-${Date.now()}`,
                    ...todoData
                };
                this.todos.unshift(localTodo);
                this.newTodo = '';
            }
        },
        
        async updateTodoStatus(todo, newStatus) {
            try {
                const response = await fetch(`/api/todos/${todo.id}/status`, {
                    method: 'PATCH',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ status: newStatus })
                });
                
                if (response.ok) {
                    // Update local state
                    todo.status = newStatus;
                    // Reload to sync with backend
                    await this.loadTodos();
                }
            } catch (error) {
                console.error('Error updating todo status:', error);
                // Update locally anyway
                todo.status = newStatus;
            }
        },
        
        async deleteTodo(todo) {
            if (!confirm(`Delete "${todo.content}"?`)) return;
            
            try {
                const response = await fetch(`/api/todos/${todo.id}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    // Reload todos
                    await this.loadTodos();
                } else {
                    // Remove locally
                    this.todos = this.todos.filter(t => t.id !== todo.id);
                }
            } catch (error) {
                console.error('Error deleting todo:', error);
                // Remove locally
                this.todos = this.todos.filter(t => t.id !== todo.id);
            }
        },
        
        formatStatus(status) {
            switch (status) {
                case 'pending': return 'Pending';
                case 'in_progress': return 'In Progress';
                case 'completed': return 'Completed';
                case 'blocked': return 'Blocked';
                default: return status;
            }
        },
        
        formatDate(dateStr) {
            if (!dateStr) return 'Recently created';
            const date = new Date(dateStr);
            const now = new Date();
            const diff = now - date;
            const days = Math.floor(diff / (1000 * 60 * 60 * 24));
            
            if (days === 0) return 'Today';
            if (days === 1) return 'Yesterday';
            if (days < 7) return `${days} days ago`;
            if (days < 30) return `${Math.floor(days / 7)} weeks ago`;
            return date.toLocaleDateString();
        },
        
        openCLI() {
            window.location.href = '/';
        }
    }
}
</script>
{% endblock %}