@{
    ViewData["Title"] = "Home";
}

<!-- Hero Section -->
<section class="hero-section">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-lg-6">
                <h1 class="display-4 fw-bold mb-4">
                    @ViewBag.Config.LocalizedTexts["ConverterTitle"]
                </h1>
                <p class="lead mb-4">
                    @ViewBag.Config.LocalizedTexts["ConverterDescription"]
                </p>
                <div class="d-flex gap-3">
                    <span class="badge bg-light text-dark fs-6">
                        <i class="fas fa-code me-1"></i> Standalone
                    </span>
                    <span class="badge bg-light text-dark fs-6">
                        <i class="fas fa-globe me-1"></i> Multi-idioma
                    </span>
                    <span class="badge bg-light text-dark fs-6">
                        <i class="fas fa-bolt me-1"></i> API Ready
                    </span>
                </div>
            </div>
            <div class="col-lg-6 text-center">
                <i class="fas fa-text-height fa-5x opacity-75"></i>
            </div>
        </div>
    </div>
</section>

<!-- Módulo Demo -->
<section class="py-5">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-10">
                <div class="text-center mb-5">
                    <h2>🧪 Teste do Módulo</h2>
                    <p class="text-muted">Este é o módulo funcionando independentemente</p>
                </div>

                <div class="module-demo">
                    <div id="sentence-converter-demo">
                        <!-- O módulo será carregado aqui -->
                        <div class="text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Carregando...</span>
                            </div>
                            <p class="mt-3">Carregando módulo...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Test Section -->
<section class="test-section">
    <div class="container">
        <div class="row">
            <div class="col-12">
                <h3 class="text-center mb-5">🔗 Endpoints Disponíveis</h3>
            </div>
        </div>

        <div class="row" id="endpoints-container">
            <!-- Endpoints serão carregados via JavaScript -->
        </div>

        <!-- SUBSTITUIR os cards existentes por: -->
        <div class="row mt-5">
            <div class="col-lg-4">
                <div class="card endpoint-card h-100">
                    <div class="card-body">
                        <h5 class="card-title">
                            <i class="fas fa-puzzle-piece text-primary me-2"></i>
                            Widget Dinâmico
                        </h5>
                        <p class="card-text">Módulo carregado com o novo sistema de loading dinâmico</p>
                        <button class="btn btn-primary" onclick="loadWidgetManually()">
                            <i class="fas fa-sync me-1"></i> Recarregar Widget
                        </button>
                    </div>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="card endpoint-card h-100">
                    <div class="card-body">
                        <h5 class="card-title">
                            <i class="fas fa-code text-success me-2"></i>
                            Teste de API
                        </h5>
                        <p class="card-text">Teste direto da API de conversão com resultado visual</p>
                        <button class="btn btn-success" onclick="testApi()">
                            <i class="fas fa-play me-1"></i> Testar API
                        </button>
                        <div id="api-result" class="mt-3"></div>
                    </div>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="card endpoint-card h-100">
                    <div class="card-body">
                        <h5 class="card-title">
                            <i class="fas fa-cogs text-info me-2"></i>
                            Sistema de Módulos
                        </h5>
                        <p class="card-text">Informações sobre o sistema de carregamento dinâmico</p>
                        <button class="btn btn-info" onclick="showSystemInfo()">
                            <i class="fas fa-info-circle me-1"></i> Ver Detalhes
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

@section Scripts {
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // Auto-carregar o widget usando o novo sistema
            loadFullWidgetDynamic();
            loadEndpoints();
        });

        async function loadFullWidgetDynamic() {
            const containerId = 'sentence-converter-demo';
            const endpoint = `/modules/sentence-converter?language=@ViewBag.Language`;

            console.log('🚀 Carregando widget usando sistema dinâmico...');

            const success = await window.loadTestModule(containerId, endpoint);
            if (success) {
                console.log('✅ Widget carregado com sistema dinâmico!');
            } else {
                console.error('❌ Falha ao carregar widget dinamicamente');
            }
        }

        async function loadEndpoints() {
            try {
                const response = await fetch('/home/testendpoints');
                const endpoints = await response.json();

                const container = document.getElementById('endpoints-container');
                let html = '';

                Object.entries(endpoints).forEach(([name, url]) => {
                    const displayName = name.replace(/_/g, ' ').toUpperCase();
                    const isModuleEndpoint = name.includes('module');

                    html += `
                        <div class="col-md-6 col-lg-4 mb-3">
                            <div class="card endpoint-card h-100">
                                <div class="card-body">
                                    <h6 class="card-title">
                                        ${isModuleEndpoint ? '<i class="fas fa-puzzle-piece text-primary me-1"></i>' : ''}
                                        ${displayName}
                                    </h6>
                                    <small class="text-muted">${url}</small>
                                    <div class="mt-2">
                                        ${isModuleEndpoint ?
                            `<button class="btn btn-sm btn-primary" onclick="testModuleLoad('${url}')">
                                                <i class="fas fa-play me-1"></i> Carregar
                                             </button>` :
                            `<button class="btn btn-sm btn-outline-primary" onclick="testEndpoint('${url}')">
                                                Testar
                                             </button>`
                        }
                                        <button class="btn btn-sm btn-outline-secondary" onclick="copyUrl('${url}')">
                                            Copiar
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>`;
                });

                container.innerHTML = html;
            } catch (error) {
                console.error('Erro ao carregar endpoints:', error);
            }
        }

        async function testModuleLoad(url) {
            // Criar container temporário para teste
            const testId = 'test-module-' + Date.now();
            const modal = document.createElement('div');
            modal.className = 'modal fade';
            modal.innerHTML = `
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="fas fa-vial me-2"></i>Teste de Carregamento do Módulo
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <p><strong>URL:</strong> <code>${url}</code></p>
                            <div id="${testId}" class="border rounded p-3 bg-light">
                                <!-- Módulo será carregado aqui -->
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fechar</button>
                            <button type="button" class="btn btn-primary" onclick="window.loadTestModule('${testId}', '${url}')">
                                <i class="fas fa-redo me-1"></i> Recarregar
                            </button>
                        </div>
                    </div>
                </div>
            `;

            document.body.appendChild(modal);
            const bsModal = new bootstrap.Modal(modal);

            // Limpar modal quando fechado
            modal.addEventListener('hidden.bs.modal', () => {
                document.body.removeChild(modal);
            });

            bsModal.show();

            // Carregar módulo no modal
            setTimeout(() => {
                window.loadTestModule(testId, url);
            }, 500);
        }

        async function testEndpoint(url) {
            try {
                const response = await fetch(url);
                const result = await response.text();

                // Abrir resultado em nova janela
                const newWindow = window.open('', '_blank');
                newWindow.document.write(`
                    <html>
                        <head>
                            <title>Resultado do Teste</title>
                            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
                        </head>
                        <body class="p-4">
                            <div class="container">
                                <h3>Teste de Endpoint</h3>
                                <p><strong>URL:</strong> <code>${url}</code></p>
                                <p><strong>Status:</strong> <span class="badge bg-${response.ok ? 'success' : 'danger'}">${response.status}</span></p>
                                <hr>
                                <h5>Resposta:</h5>
                                <pre class="bg-light p-3 rounded"><code>${result}</code></pre>
                            </div>
                        </body>
                    </html>
                `);
            } catch (error) {
                alert('Erro ao testar endpoint: ' + error.message);
            }
        }

        async function testApi() {
            const resultDiv = document.getElementById('api-result');
            resultDiv.innerHTML = '<div class="spinner-border spinner-border-sm" role="status"></div> Testando API...';

            try {
                const formData = new FormData();
                formData.append('TextInput', 'este é um teste. vamos ver se funciona!');
                formData.append('Language', '@ViewBag.Language');

                const response = await fetch('/api/converter/convert', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

                if (result.success) {
                    resultDiv.innerHTML = `
                        <div class="alert alert-success">
                            <h6><i class="fas fa-check-circle me-2"></i>Sucesso!</h6>
                            <p class="mb-1"><strong>Entrada:</strong> este é um teste. vamos ver se funciona!</p>
                            <p class="mb-0"><strong>Saída:</strong> <em>${result.outputText}</em></p>
                        </div>`;
                } else {
                    resultDiv.innerHTML = `
                        <div class="alert alert-danger">
                            <h6><i class="fas fa-times-circle me-2"></i>Erro</h6>
                            <p class="mb-0">${result.message}</p>
                        </div>`;
                }
            } catch (error) {
                resultDiv.innerHTML = `
                    <div class="alert alert-danger">
                        <h6><i class="fas fa-exclamation-triangle me-2"></i>Erro de Conexão</h6>
                        <p class="mb-0">${error.message}</p>
                    </div>`;
            }
        }

        function copyUrl(url) {
            navigator.clipboard.writeText(url).then(() => {
                // Feedback visual
                const button = event.target;
                const originalText = button.textContent;
                const originalClass = button.className;

                button.textContent = 'Copiado!';
                button.className = button.className.replace('btn-outline-secondary', 'btn-success');

                setTimeout(() => {
                    button.textContent = originalText;
                    button.className = originalClass;
                }, 2000);
            });
        }

        // Função para demonstrar carregamento manual
        function loadWidgetManually() {
            const endpoint = `/modules/sentence-converter?language=@ViewBag.Language`;
            window.loadTestModule('sentence-converter-demo', endpoint);
        }
    </script>

    <script>
        function showSystemInfo() {
            const info = {
                moduleLoader: !!window.ModuleLoaderLite,
                version: window.ModuleLoaderLite?.version || 'N/A',
                loadedModules: document.querySelectorAll('[data-module-id]').length,
                loadedScripts: document.querySelectorAll('[data-test-script]').length,
                loadedStyles: document.querySelectorAll('[data-test-style]').length
            };

            const modal = document.createElement('div');
            modal.className = 'modal fade';
            modal.innerHTML = `
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header bg-info text-white">
                            <h5 class="modal-title">
                                <i class="fas fa-info-circle me-2"></i>Informações do Sistema
                            </h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <dl class="row">
                                <dt class="col-sm-6">Module Loader:</dt>
                                <dd class="col-sm-6">
                                    <span class="badge bg-${info.moduleLoader ? 'success' : 'danger'}">
                                        ${info.moduleLoader ? 'Ativo' : 'Inativo'}
                                    </span>
                                </dd>

                                <dt class="col-sm-6">Versão:</dt>
                                <dd class="col-sm-6"><code>${info.version}</code></dd>

                                <dt class="col-sm-6">Módulos Carregados:</dt>
                                <dd class="col-sm-6"><span class="badge bg-primary">${info.loadedModules}</span></dd>

                                <dt class="col-sm-6">Scripts Dinâmicos:</dt>
                                <dd class="col-sm-6"><span class="badge bg-secondary">${info.loadedScripts}</span></dd>

                                <dt class="col-sm-6">Estilos Dinâmicos:</dt>
                                <dd class="col-sm-6"><span class="badge bg-secondary">${info.loadedStyles}</span></dd>
                            </dl>

                            <hr>

                            <h6>Recursos Carregados:</h6>
                            <div class="row">
                                <div class="col-12">
                                    <small class="text-muted">Scripts:</small>
                                    <ul class="list-unstyled small">
                                        ${Array.from(document.querySelectorAll('[data-test-script]')).map(s =>
                `<li><code>${s.getAttribute('data-test-script')}</code></li>`
            ).join('') || '<li class="text-muted">Nenhum script dinâmico carregado</li>'}
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fechar</button>
                        </div>
                    </div>
                </div>
            `;

            document.body.appendChild(modal);
            const bsModal = new bootstrap.Modal(modal);

            modal.addEventListener('hidden.bs.modal', () => {
                document.body.removeChild(modal);
            });

            bsModal.show();
        }
    </script>
}