<?php
$title = $title ?? 'Marketplace de Módulos';
?>

<div class="page-header" style="display:flex;align-items:center;justify-content:space-between;gap:1rem;flex-wrap:wrap;">
    <div>
        <h1>Marketplace de Módulos</h1>
        <p class="muted">Explore e instale módulos opcionais para expandir as funcionalidades do sistema</p>
    </div>
</div>

<div id="alert-container"></div>

<div style="display: flex; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap;">
    <button class="btn" onclick="filterModules('all')" id="filter-all">Todos</button>
    <button class="btn btn-secondary" onclick="filterModules('free')" id="filter-free">Gratuitos</button>
    <button class="btn btn-secondary" onclick="filterModules('paid')" id="filter-paid">Pagos</button>
    <button class="btn btn-secondary" onclick="filterModules('installed')" id="filter-installed">Instalados</button>
</div>

<div id="modules-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 1.5rem;">
    <!-- Módulos serão carregados aqui -->
</div>

<script>
let allModules = [];
let currentFilter = 'all';

function setAlert(message, type = 'success') {
    const container = document.getElementById('alert-container');
    container.innerHTML = `<div class="alert alert-${type}">${message}</div>`;
    setTimeout(() => {
        container.innerHTML = '';
    }, 5000);
}

function filterModules(filter) {
    currentFilter = filter;
    
    // Atualizar botões
    document.querySelectorAll('[id^="filter-"]').forEach(btn => {
        btn.classList.remove('btn');
        btn.classList.add('btn-secondary');
    });
    document.getElementById(`filter-${filter}`).classList.remove('btn-secondary');
    document.getElementById(`filter-${filter}`).classList.add('btn');
    
    // Filtrar módulos
    let filtered = allModules;
    if (filter === 'free') {
        filtered = allModules.filter(m => !m.is_paid);
    } else if (filter === 'paid') {
        filtered = allModules.filter(m => m.is_paid);
    } else if (filter === 'installed') {
        filtered = allModules.filter(m => m.installed);
    }
    
    renderModules(filtered);
}

function renderModules(modules) {
    const grid = document.getElementById('modules-grid');
    
    if (modules.length === 0) {
        grid.innerHTML = '<p class="muted">Nenhum módulo encontrado.</p>';
        return;
    }
    
    grid.innerHTML = modules.map(module => {
        const statusBadge = module.status === 'development' 
            ? '<span style="background: #fbbf24; color: #78350f; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.75rem; font-weight: 600;">Em Desenvolvimento</span>'
            : module.installed 
                ? '<span style="background: #10b981; color: white; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.75rem; font-weight: 600;">Instalado</span>'
                : '';
        
        const priceBadge = module.is_paid
            ? `<div style="margin-top: 0.5rem;"><strong style="font-size: 1.5rem; color: var(--color-orange);">R$ ${module.price.toFixed(2)}</strong><span class="muted">/${module.price_cycle}</span></div>`
            : '<div style="margin-top: 0.5rem;"><strong style="font-size: 1.5rem; color: var(--color-olive);">Gratuito</strong></div>';
        
        const actionButton = module.installed
            ? `<button class="btn btn-danger" onclick="uninstallModule('${module.code}')">Desinstalar</button>`
            : module.status === 'development'
                ? `<button class="btn btn-secondary" disabled>Em Desenvolvimento</button>`
                : `<button class="btn" onclick="installModule('${module.code}')">Instalar</button>`;
        
        return `
            <div class="card" style="display: flex; flex-direction: column;">
                <div style="display: flex; align-items: center; gap: 1rem; margin-bottom: 1rem;">
                    <span style="font-size: 3rem;">${module.icon}</span>
                    <div style="flex: 1;">
                        <h3 style="margin: 0;">${module.name}</h3>
                        <span class="muted" style="font-size: 0.875rem;">${module.category}</span>
                    </div>
                </div>
                <p style="color: #666; margin-bottom: 1rem; flex: 1;">${module.description}</p>
                <div style="margin-bottom: 1rem;">
                    <strong>Recursos:</strong>
                    <ul style="margin: 0.5rem 0; padding-left: 1.5rem;">
                        ${module.features.map(f => `<li style="font-size: 0.875rem;">${f}</li>`).join('')}
                    </ul>
                </div>
                ${priceBadge}
                <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #e5e7eb;">
                    ${statusBadge}
                    ${actionButton}
                </div>
            </div>
        `;
    }).join('');
}

async function loadModules() {
    try {
        const response = await fetch('/api/marketplace/modules');
        const data = await response.json();
        allModules = data.data || [];
        filterModules('all');
    } catch (error) {
        console.error('Erro ao carregar módulos:', error);
        setAlert('Erro ao carregar módulos', 'error');
    }
}

async function installModule(code) {
    if (!confirm('Deseja instalar este módulo?')) return;
    
    try {
        const response = await fetch(`/api/marketplace/modules/${code}/install`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }
        });
        
        const data = await response.json();
        
        if (response.ok) {
            setAlert('Módulo instalado com sucesso!', 'success');
            loadModules();
        } else {
            setAlert(data.error?.message || 'Erro ao instalar módulo', 'error');
        }
    } catch (error) {
        console.error('Erro ao instalar módulo:', error);
        setAlert('Erro ao instalar módulo', 'error');
    }
}

async function uninstallModule(code) {
    if (!confirm('Deseja desinstalar este módulo? Esta ação não pode ser desfeita.')) return;
    
    try {
        const response = await fetch(`/api/marketplace/modules/${code}/uninstall`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }
        });
        
        const data = await response.json();
        
        if (response.ok) {
            setAlert('Módulo desinstalado com sucesso!', 'success');
            loadModules();
        } else {
            setAlert(data.error?.message || 'Erro ao desinstalar módulo', 'error');
        }
    } catch (error) {
        console.error('Erro ao desinstalar módulo:', error);
        setAlert('Erro ao desinstalar módulo', 'error');
    }
}

// Carregar módulos ao carregar a página
document.addEventListener('DOMContentLoaded', loadModules);
</script>

