// Global state
let currentPage = 'dashboard';
let currentUser = null;
let currentDateFilter = {
    startDate: getFirstDayOfMonth(),
    endDate: getLastDayOfMonth()
};

// API Base URL
const API_URL = 'api';

// Authentication
async function checkAuth() {
    try {
        const response = await fetch(`${API_URL}/auth.php?action=check`, {
            credentials: 'include'
        });
        const data = await response.json();
        
        if (data.authenticated) {
            currentUser = data.admin;
            showApp();
        } else {
            showLogin();
        }
    } catch (error) {
        console.error('Auth check error:', error);
        showLogin();
    }
}

function showLogin() {
    document.getElementById('login-screen').classList.remove('hidden');
    document.getElementById('app-container').classList.add('hidden');
    
    document.getElementById('login-form').onsubmit = async (e) => {
        e.preventDefault();
        const email = document.getElementById('login-email').value;
        const password = document.getElementById('login-password').value;
        const errorDiv = document.getElementById('login-error');
        
        try {
            const response = await fetch(`${API_URL}/auth.php?action=login`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify({ email, password })
            });
            
            const data = await response.json();
            
            if (response.ok && data.success) {
                currentUser = data.admin;
                showApp();
            } else {
                errorDiv.textContent = data.error || 'Erro ao fazer login';
                errorDiv.classList.remove('hidden');
            }
        } catch (error) {
            errorDiv.textContent = 'Erro de conexão';
            errorDiv.classList.remove('hidden');
        }
    };
}

function showApp() {
    document.getElementById('login-screen').classList.add('hidden');
    document.getElementById('app-container').classList.remove('hidden');
    
    if (currentUser) {
        document.getElementById('user-name').textContent = currentUser.name;
        document.getElementById('user-email').textContent = currentUser.email;
        const avatar = document.getElementById('user-avatar');
        avatar.style.backgroundColor = currentUser.color || '#3B82F6';
        avatar.textContent = currentUser.name.charAt(0).toUpperCase();
    }
    
    loadPage('dashboard');
}

async function logout() {
    try {
        await fetch(`${API_URL}/auth.php?action=logout`, {
            credentials: 'include'
        });
    } catch (error) {
        console.error('Logout error:', error);
    }
    currentUser = null;
    showLogin();
}

// Theme Management
function initTheme() {
    const savedTheme = localStorage.getItem('theme') || 'light';
    if (savedTheme === 'dark') {
        document.documentElement.classList.add('dark');
    }
}

function toggleTheme() {
    document.documentElement.classList.toggle('dark');
    const isDark = document.documentElement.classList.contains('dark');
    localStorage.setItem('theme', isDark ? 'dark' : 'light');
}

// Sidebar Management
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebar-overlay');
    
    sidebar.classList.toggle('-translate-x-full');
    overlay.classList.toggle('hidden');
}

// Page Navigation
function loadPage(page) {
    currentPage = page;
    
    document.querySelectorAll('.nav-link').forEach(link => {
        link.classList.remove('active');
        if (link.dataset.page === page) {
            link.classList.add('active');
        }
    });
    
    const titles = {
        dashboard: 'Dashboard',
        transactions: 'Lançamentos',
        bills: 'Boletos',
        projections: 'Projeções',
        partners: 'Parceiros',
        branches: 'Filiais',
        employees: 'Funcionários',
        salaries: 'Salários',
        absences: 'Faltas',
        stock: 'Estoque',
        employeeConsumptions: 'Consumo Funcionário',
        administrators: 'Administradores',
        calendar: 'Agenda'
    };
    document.getElementById('page-title').textContent = titles[page] || page;
    
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebar-overlay');
    if (!sidebar.classList.contains('-translate-x-full') && window.innerWidth < 1024) {
        sidebar.classList.add('-translate-x-full');
        overlay.classList.add('hidden');
    }
    
    const content = document.getElementById('main-content');
    content.innerHTML = '<div class="flex justify-center items-center h-64"><div class="spinner"></div></div>';
    
    switch(page) {
        case 'dashboard':
            renderDashboard();
            break;
        case 'transactions':
            renderTransactions();
            break;
        case 'bills':
            renderBills();
            break;
        case 'projections':
            renderProjections();
            break;
        case 'partners':
            renderPartners();
            break;
        case 'branches':
            renderBranches();
            break;
        case 'employees':
            renderEmployees();
            break;
        case 'salaries':
            renderSalaries();
            break;
        case 'administrators':
            renderAdministrators();
            break;
        case 'calendar':
            renderCalendar();
            break;
        case 'absences':
            loadAbsencesPage();
            break;
        case 'stock':
            loadStockPage();
            break;
        case 'employeeConsumptions':
            loadEmployeeConsumptionsPage();
            break;
    }
    
    return false;
}

// Date utilities
function getFirstDayOfMonth() {
    const date = new Date();
    return new Date(date.getFullYear(), date.getMonth(), 1).toISOString().split('T')[0];
}

function getLastDayOfMonth() {
    const date = new Date();
    return new Date(date.getFullYear(), date.getMonth() + 1, 0).toISOString().split('T')[0];
}

function formatDate(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr + 'T00:00:00');
    return date.toLocaleDateString('pt-BR');
}

function formatDateTime(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.toLocaleString('pt-BR');
}

function formatMoney(value) {
    return new Intl.NumberFormat('pt-BR', {
        style: 'currency',
        currency: 'BRL'
    }).format(value || 0);
}

function getCurrentMonth() {
    const date = new Date();
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
}

function setDateFilter(period) {
    const today = new Date();
    let startDate, endDate;
    
    switch(period) {
        case 'day':
            startDate = endDate = today.toISOString().split('T')[0];
            break;
        case 'week':
            const weekStart = new Date(today);
            weekStart.setDate(today.getDate() - today.getDay());
            const weekEnd = new Date(weekStart);
            weekEnd.setDate(weekStart.getDate() + 6);
            startDate = weekStart.toISOString().split('T')[0];
            endDate = weekEnd.toISOString().split('T')[0];
            break;
        case 'biweekly':
            const biweeklyStart = new Date(today);
            biweeklyStart.setDate(today.getDate() - 14);
            startDate = biweeklyStart.toISOString().split('T')[0];
            endDate = today.toISOString().split('T')[0];
            break;
        case 'month':
        default:
            startDate = getFirstDayOfMonth();
            endDate = getLastDayOfMonth();
            break;
    }
    
    currentDateFilter = { startDate, endDate };
    loadPage(currentPage);
}

// AJAX Helper
async function apiRequest(endpoint, method = 'GET', data = null) {
    const options = {
        method,
        headers: {
            'Content-Type': 'application/json'
        },
        credentials: 'include'
    };
    
    if (data && method !== 'GET') {
        options.body = JSON.stringify(data);
    }
    
    let url = `${API_URL}/${endpoint}`;
    
    const response = await fetch(url, options);
    
    if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || 'Erro na requisição');
    }
    
    return response.json();
}

// Modal Management
function openModal(content) {
    const container = document.getElementById('modal-container');
    const contentDiv = document.getElementById('modal-content');
    contentDiv.innerHTML = content;
    container.classList.remove('hidden');
}

function closeModal() {
    const container = document.getElementById('modal-container');
    container.classList.add('hidden');
}

// Toast Notifications
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, 3000);
}

// Date Filter Component
function renderDateFilter() {
    return `
        <div class="date-filter">
            <button class="date-filter-btn" onclick="setDateFilter('day')">Hoje</button>
            <button class="date-filter-btn" onclick="setDateFilter('week')">Semana</button>
            <button class="date-filter-btn" onclick="setDateFilter('biweekly')">Quinzena</button>
            <button class="date-filter-btn active" onclick="setDateFilter('month')">Mês</button>
            <div class="flex gap-2 items-center ml-auto">
                <input type="date" id="filter-start" class="form-input w-auto" value="${currentDateFilter.startDate}" onchange="updateCustomDate()">
                <span class="text-gray-500">até</span>
                <input type="date" id="filter-end" class="form-input w-auto" value="${currentDateFilter.endDate}" onchange="updateCustomDate()">
            </div>
        </div>
    `;
}

function updateCustomDate() {
    const startDate = document.getElementById('filter-start').value;
    const endDate = document.getElementById('filter-end').value;
    if (startDate && endDate) {
        currentDateFilter = { startDate, endDate };
        loadPage(currentPage);
    }
}
