const express = require('express');
const path = require('path');
const fs = require('fs');

// Servidor simples para servir sites clonados
const app = express();
const PORT = 8080;

// Middleware para servir arquivos estáticos com CORS habilitado
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

// Servir arquivos estáticos do diretório cloned-sites
const clonedSitesDir = path.join(__dirname, '..', 'cloned-sites');
app.use(express.static(clonedSitesDir));

// Listar sites clonados
app.get('/api/sites', (req, res) => {
  try {
    const dirs = fs.readdirSync(clonedSitesDir)
      .filter(file => fs.statSync(path.join(clonedSitesDir, file)).isDirectory())
      .map(dir => ({
        name: dir,
        path: `/${dir}/index.html`,
        fullPath: path.join(clonedSitesDir, dir)
      }));
    res.json({ sites: dirs });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Página inicial com lista de sites
app.get('/', (req, res) => {
  try {
    const dirs = fs.readdirSync(clonedSitesDir)
      .filter(file => fs.statSync(path.join(clonedSitesDir, file)).isDirectory());
    
    const html = `
<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Sites Clonados - Servidor Local</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      min-height: 100vh;
      padding: 2rem;
    }
    .container {
      max-width: 1200px;
      margin: 0 auto;
    }
    h1 {
      color: white;
      text-align: center;
      margin-bottom: 2rem;
      font-size: 2.5rem;
    }
    .sites-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 1.5rem;
    }
    .site-card {
      background: white;
      border-radius: 12px;
      padding: 1.5rem;
      box-shadow: 0 10px 30px rgba(0,0,0,0.2);
      transition: transform 0.3s ease, box-shadow 0.3s ease;
    }
    .site-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 15px 40px rgba(0,0,0,0.3);
    }
    .site-name {
      font-size: 1.1rem;
      font-weight: 600;
      color: #333;
      margin-bottom: 1rem;
      word-break: break-word;
    }
    .site-link {
      display: inline-block;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      text-decoration: none;
      padding: 0.75rem 1.5rem;
      border-radius: 8px;
      font-weight: 500;
      transition: opacity 0.3s ease;
    }
    .site-link:hover {
      opacity: 0.9;
    }
    .empty-state {
      text-align: center;
      color: white;
      font-size: 1.2rem;
      padding: 3rem;
    }
    .info {
      background: rgba(255,255,255,0.1);
      color: white;
      padding: 1rem;
      border-radius: 8px;
      margin-bottom: 2rem;
      text-align: center;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>🌐 Sites Clonados</h1>
    <div class="info">
      <p>Servidor local rodando em <strong>http://localhost:${PORT}</strong></p>
      <p>Sem problemas de CORS ou permissões!</p>
    </div>
    ${dirs.length > 0 ? `
      <div class="sites-grid">
        ${dirs.map(dir => `
          <div class="site-card">
            <div class="site-name">${dir}</div>
            <a href="/${dir}/index.html" class="site-link" target="_blank">
              Abrir Site →
            </a>
          </div>
        `).join('')}
      </div>
    ` : `
      <div class="empty-state">
        <p>Nenhum site clonado ainda.</p>
        <p>Use o CloneWeb para clonar um site!</p>
      </div>
    `}
  </div>
</body>
</html>
    `;
    
    res.send(html);
  } catch (error) {
    res.status(500).send(`<h1>Erro: ${error.message}</h1>`);
  }
});

app.listen(PORT, () => {
  console.log(`\n${'='.repeat(60)}`);
  console.log(`🌐 Servidor de Sites Clonados`);
  console.log(`${'='.repeat(60)}`);
  console.log(`📡 Rodando em: http://localhost:${PORT}`);
  console.log(`📁 Servindo de: ${clonedSitesDir}`);
  console.log(`✅ Sem problemas de CORS!`);
  console.log(`${'='.repeat(60)}\n`);
});
