<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Alguém me Perguntou</title>
  
  <!-- reCAPTCHA -->
  <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  
  <!-- Firebase -->
  <script src="https://www.gstatic.com/firebasejs/10.12.5/firebase-app-compat.js"></script>
  <script src="https://www.gstatic.com/firebasejs/10.12.5/firebase-firestore-compat.js"></script>

  <style>
    /* ===== RESET & BASE ===== */
    * { box-sizing: border-box; }
    html { scroll-behavior: smooth; }
    body {
      margin: 0;
      font-family: system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif;
      line-height: 1.6;
      color: #000;
      background: #fff;
      min-height: 100vh;
      display: flex;
      flex-direction: column;
    }
    a { color: #0047AB; text-decoration: underline; text-underline-offset: 2px; }

    /* ===== ACESSIBILIDADE ===== */
    .sr-only { 
      position: absolute; 
      width: 1px; 
      height: 1px; 
      padding: 0; 
      margin: -1px; 
      overflow: hidden; 
      clip: rect(0,0,0,0); 
      border: 0; 
    }
    .skip-link { 
      position: absolute; 
      left: -999px; 
      top: -999px; 
      z-index: 1000;
    }
    .skip-link:focus { 
      left: 8px; 
      top: 8px; 
      background: #ffd; 
      padding: 8px 12px; 
      border-radius: 8px; 
      color: #000;
      font-weight: bold;
    }

    /* ===== PREFERÊNCIAS DE ACESSIBILIDADE ===== */
    body.high-contrast { 
      background: #000 !important; 
      color: #fff !important; 
    }
    body.high-contrast a { 
      color: #ffff00 !important;
    }
    body.high-contrast button { 
      background: #fff !important; 
      color: #000 !important; 
      border: 2px solid #fff !important;
    }
    body.large-font { 
      font-size: 1.125rem; 
    }
    body.large-font h1 { font-size: 2rem; }
    body.large-font h2 { font-size: 1.75rem; }
    body.large-font h3 { font-size: 1.5rem; }

    /* ===== LAYOUT PRINCIPAL ===== */
    .site-header, .site-footer {
      display: flex; 
      align-items: center; 
      justify-content: space-between;
      padding: 12px 16px;
      background: #f0f0f0;
      border-bottom: 2px solid #ccc;
    }
    .site-footer { 
      border-top: 2px solid #ccc;
      border-bottom: none;
      margin-top: auto;
      flex-direction: column;
      gap: 10px;
      text-align: center;
    }
    .brand { 
      display: flex; 
      gap: 20px;
      align-items: center; 
    }
    .top-actions { 
      display: flex; 
      gap: 8px; 
      flex-wrap: wrap;
    }

    main { 
      max-width: 980px; 
      margin: 24px auto; 
      padding: 0 16px;
      flex: 1;
    }
    section { 
      margin: 32px 0; 
      padding: 20px 0;
    }

    /* ===== FORMULÁRIOS ===== */
    form { 
      display: grid; 
      gap: 16px;
      background: #f5f5f5;
      padding: 20px;
      border-radius: 12px;
      border: 1px solid #ccc;
    }
    label { 
      font-weight: 700;
      display: block;
      margin-bottom: 5px;
      color: #222;
    }
    input, select, textarea, button {
      font: inherit;
      padding: 12px;
      border: 2px solid #666;
      border-radius: 10px;
      width: 100%;
    }
    textarea { 
      resize: vertical; 
      min-height: 120px;
    }
    button { 
      cursor: pointer; 
      border: none; 
      background: #000;
      color: #fff; 
      border-radius: 10px; 
      padding: 12px 20px;
      font-weight: 700;
      transition: background 0.2s;
    }
    button:hover {
      background: #333;
    }
    button.secondary { 
      background: #e0e0e0;
      color: #000; 
      border: 2px solid #999;
    }
    button.secondary:hover {
      background: #ccc;
    }
    button:focus-visible, .link:focus-visible { 
      outline: 3px solid #0047AB;
      outline-offset: 3px; 
    }
    .checkbox { 
      display: flex; 
      gap: 8px; 
      align-items: flex-start; 
    }
    .checkbox input {
      width: auto;
      margin-top: 3px;
    }

    .hint { color: #333; font-size: 0.9rem; }

    /* ===== ABAS DE TEMAS ===== */
    .tabs-header {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: 20px;
      border-bottom: 2px solid #e9ecef;
      padding-bottom: 10px;
    }
    
    .tab-button {
      background: #f8f9fa;
      border: 2px solid #e9ecef;
      border-radius: 25px;
      padding: 12px 24px;
      font-size: 14px;
      font-weight: 600;
      color: #6c757d;
      cursor: pointer;
      transition: all 0.3s ease;
      margin-bottom: 5px;
    }
    
    .tab-button:hover {
      background: #e9ecef;
      color: #495057;
    }
    
    .tab-button.active {
      background: #3498db;
      color: white;
      border-color: #3498db;
    }
    
    .tab-content {
      display: none;
      animation: fadeIn 0.5s ease;
    }
    
    .tab-content.active {
      display: block;
    }
    
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(10px); }
      to { opacity: 1; transform: translateY(0); }
    }

    /* ===== RESPOSTAS ===== */
    .resposta-card {
      background: white;
      border: 1px solid #e9ecef;
      border-radius: 12px;
      padding: 25px;
      margin-bottom: 20px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.08);
      transition: transform 0.2s ease, box-shadow 0.2s ease;
    }
    
    .resposta-card:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0,0,0,0.12);
    }
    
    .resposta-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      padding-bottom: 12px;
      border-bottom: 1px solid #f1f3f4;
    }
    
    .data-resposta {
      color: #7f8c8d;
      font-size: 13px;
      font-weight: 500;
    }
    
    .resposta-conteudo {
      background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
      padding: 20px;
      border-radius: 8px;
      border-left: 4px solid #27ae60;
      font-size: 15px;
      line-height: 1.6;
      color: #2c3e50;
    }
    
    .resposta-conteudo p {
      margin: 0;
      text-align: justify;
    }
    
    .empty-tab {
      text-align: center;
      padding: 60px 20px;
      color: #7f8c8d;
      background: #f8f9fa;
      border-radius: 12px;
      border: 2px dashed #dee2e6;
    }
    
    .loading {
      text-align: center;
      padding: 50px;
      color: #7f8c8d;
      font-size: 18px;
    }
    
    .error {
      text-align: center;
      padding: 25px;
      background: #fadbd8;
      color: #e74c3c;
      border-radius: 10px;
      margin: 15px 0;
      border-left: 4px solid #e74c3c;
    }

    /* ===== reCAPTCHA ===== */
    .recaptcha-container {
      margin: 20px 0;
    }

    /* ===== RESPONSIVIDADE ===== */
    @media (max-width: 768px) {
      .site-header {
        flex-direction: column;
        text-align: center;
        gap: 15px;
      }
      
      .top-actions {
        justify-content: center;
        width: 100%;
      }
      
      .tabs-header {
        flex-direction: column;
        gap: 5px;
      }
      
      .tab-button {
        width: 100%;
        text-align: center;
      }
      
      .resposta-card {
        padding: 20px;
        margin-bottom: 15px;
      }
    }

    /* Melhorias para touch */
    @media (hover: none) and (pointer: coarse) {
      button:hover, .btn:hover {
        transform: none;
      }
      
      .resposta-card:hover {
        transform: none;
        box-shadow: 0 2px 6px rgba(0,0,0,0.1);
      }
    }

    :focus-visible { 
      outline: 3px solid #0047AB;
      outline-offset: 3px; 
    }
  </style>
</head>
<body>
  <a class="skip-link" href="#conteudo">Pular para o conteúdo</a>
  
  <header class="site-header" role="banner">
    <div class="brand" aria-label="Marca do site">
      <img src="assets/logo.svg" alt="Logotipo: balão de fala com um ponto de interrogação" width="295" height="295" />
      <h1>Alguém Me Perguntou</h1>
    </div>

    <nav class="top-actions" aria-label="Preferências de acessibilidade">
      <button id="toggle-contrast" aria-pressed="false">Alto Contraste</button>
      <button id="bump-font" aria-pressed="false">Aumentar Fonte</button>
    </nav>
  </header>

  <main id="conteudo" tabindex="-1">
    <section class="intro" aria-label="Apresentação do projeto">
      <h2>Faça sua pergunta de forma anônima</h2>
      <p>Você pode enviar até <strong>2 perguntas por acesso</strong>. Não coletamos nome, e-mail ou outras informações pessoais. As perguntas passam por <strong>moderação</strong> para garantir segurança e respeito às leis.</p>
      <details>
        <summary>Como protegemos seu anonimato?</summary>
        <ul>
          <li>Não pedimos cadastro nem identificadores pessoais.</li>
          <li>Evite inserir dados que identifiquem você ou terceiros.</li>
          <li>Provedores podem registrar dados técnicos (ex.: IP) por motivos de segurança; nós não armazenamos no banco.</li>
        </ul>
      </details>
    </section>

    <section class="ask" aria-label="Formulário de envio de perguntas">
      <h2>Enviar Pergunta</h2>
      <form id="ask-form">
        <label for="category">Tema da sua pergunta</label>
        <select id="category" name="category" required>
          <option value="">Selecione um tema</option>
          <option>Oratória</option>
          <option>Saúde mental</option>
          <option>Corpo humano</option>
          <option>Reflexões</option>
          <option>Dicas</option>
          <option>Assuntos aleatórios</option>
          <option>Curiosidades</option>
        </select>

        <label for="question">Sua pergunta</label>
        <textarea id="question" name="question" rows="5" maxlength="600" placeholder="Escreva sua pergunta (máx. 600 caracteres)" required></textarea>
        <p id="char-count" aria-live="polite">0/600</p>

        <!-- reCAPTCHA -->
        <div class="recaptcha-container">
          <div class="g-recaptcha" 
               data-sitekey="6Lcs0cwrAAAAAMJJ8ioTRk931t4MmQlgtOPbYTNu"
               data-callback="onRecaptchaSuccess"
               data-expired-callback="onRecaptchaExpired"
               data-error-callback="onRecaptchaError">
          </div>
        </div>

        <div class="form-foot">
          <label class="checkbox">
            <input type="checkbox" id="agree" required>
            <span>Concordo com as <a href="#regras" class="link">regras de uso</a> e confirmo que não inseri dados pessoais.</span>
          </label>
          <button type="submit" id="submit-btn" disabled>Enviar anonimamente</button>
        </div>
        <p id="limit-msg" class="hint" role="status" aria-live="polite"></p>
        <p id="timer-msg" class="hint" style="display: none;"></p>
      </form>
    </section>

    <section class="answers" aria-label="Respostas publicadas">
      <h2>Respostas Publicadas por Tema</h2>
      
      <div id="loading-answers">
        <p>Carregando respostas publicadas...</p>
      </div>
      
      <div id="no-answers" style="display: none;">
        <p>Nenhuma resposta publicada ainda.</p>
        <p>As respostas às perguntas aparecerão aqui após a moderação!</p>
      </div>
      
      <!-- Abas de temas -->
      <div id="tabs-container" style="display: none;">
        <div class="tabs-header" role="tablist" aria-label="Temas de respostas">
          <!-- As abas serão geradas dinamicamente -->
        </div>
        
        <div class="tabs-content">
          <!-- O conteúdo das abas será gerado dinamicamente -->
        </div>
      </div>
    </section>

    <section id="regras" class="rules" aria-label="Regras e moderação">
      <h2>Regras de Uso e Moderação</h2>
      <ul>
        <li>Não publique dados pessoais próprios ou de terceiros (nomes completos, endereços, telefones, documentos).</li>
        <li>É proibido conteúdo ilegal, apologia ao crime, incitação à violência, discriminação, assédio ou bullying.</li>
        <li>Conteúdos sensíveis de saúde, segurança ou legais podem ser redirecionados para fontes confiáveis.</li>
        <li>Todas as perguntas passam por análise antes de serem publicadas.</li>
        <li>Abusos podem resultar em bloqueio do acesso do dispositivo.</li>
      </ul>
    </section>
  </main>

  <footer class="site-footer" role="contentinfo">
    <p>© <span id="year">2024</span> Alguém Me Perguntou — Projeto educacional para Ensino Médio.</p>
    <a href="painel-gestao-interna.html" class="admin-link-visible">Administração</a>
  </footer>

  <script>
    // 🔥 CONFIGURAÇÃO DO FIREBASE
    const firebaseConfig = {
      apiKey: "AIzaSyAgATT9EZ_2begAVA6yDXx0ub-Ov6pyLCg",
      authDomain: "alguemmeperguntou.firebaseapp.com",
      projectId: "alguemmeperguntou",
      storageBucket: "alguemmeperguntou.firebasestorage.app",
      messagingSenderId: "463348904304",
      appId: "1:463348904304:web:3e6deaf231287ed9cd9fb5"
    };

    // Inicialização do Firebase
    let db;
    try {
      firebase.initializeApp(firebaseConfig);
      db = firebase.firestore();
      console.log('✅ Firebase inicializado com sucesso');
    } catch (error) {
      console.error('❌ Erro ao inicializar Firebase:', error);
    }

    // 🔥 CALLBACKS DO reCAPTCHA
    function onRecaptchaSuccess(token) {
      console.log('✅ reCAPTCHA validado com sucesso');
      document.getElementById('submit-btn').disabled = false;
    }

    function onRecaptchaExpired() {
      console.log('⚠️ reCAPTCHA expirado');
      document.getElementById('submit-btn').disabled = true;
    }

    function onRecaptchaError() {
      console.log('❌ Erro no reCAPTCHA');
      document.getElementById('submit-btn').disabled = true;
    }

    // Contador de caracteres
    document.getElementById('question').addEventListener('input', function() {
      document.getElementById('char-count').textContent = `${this.value.length}/600`;
    });

    // Controle de limite de perguntas
    let questionCount = 0;
    const MAX_QUESTIONS = 2;
    const TIME_LIMIT = 24 * 60 * 60 * 1000;

    function checkQuestionLimit() {
      const savedCount = localStorage.getItem('questionCount');
      const savedTime = localStorage.getItem('lastSubmissionTime');
      
      if (savedCount && savedTime) {
        questionCount = parseInt(savedCount);
        const lastTime = parseInt(savedTime);
        const timePassed = Date.now() - lastTime;
        
        if (timePassed < TIME_LIMIT && questionCount >= MAX_QUESTIONS) {
          disableForm();
          startTimer(TIME_LIMIT - timePassed);
        }
      }
    }

    function disableForm() {
      document.getElementById('submit-btn').disabled = true;
      document.getElementById('limit-msg').textContent = 
        `Limite de ${MAX_QUESTIONS} perguntas atingido. Tente novamente em:`;
      document.getElementById('timer-msg').style.display = 'block';
    }

    function startTimer(duration) {
      const timerMsg = document.getElementById('timer-msg');
      const timer = setInterval(() => {
        duration -= 1000;
        if (duration <= 0) {
          clearInterval(timer);
          resetQuestionLimit();
          document.getElementById('submit-btn').disabled = false;
          document.getElementById('limit-msg').textContent = '';
          document.getElementById('timer-msg').style.display = 'none';
          return;
        }
        const hours = Math.floor(duration / (1000 * 60 * 60));
        const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((duration % (1000 * 60)) / 1000);
        timerMsg.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
      }, 1000);
    }

    function resetQuestionLimit() {
      questionCount = 0;
      localStorage.removeItem('questionCount');
      localStorage.removeItem('lastSubmissionTime');
    }

    // Envio do formulário
    document.getElementById('ask-form').addEventListener('submit', async function(e) {
      e.preventDefault();
      
      if (!grecaptcha.getResponse()) {
        alert('Por favor, complete o reCAPTCHA');
        return;
      }
      
      if (questionCount >= MAX_QUESTIONS) {
        alert(`Limite de ${MAX_QUESTIONS} perguntas por dia atingido.`);
        return;
      }
      
      const categoria = document.getElementById('category').value;
      const pergunta = document.getElementById('question').value.trim();
      
      if (!categoria || !pergunta) {
        alert('Por favor, preencha todos os campos.');
        return;
      }

      const submitBtn = document.getElementById('submit-btn');
      submitBtn.disabled = true;
      submitBtn.textContent = 'Enviando...';
      
      try {
        await db.collection('perguntas').add({
          pergunta: pergunta,
          categoria: categoria,
          status: 'pendente',
          timestamp: new Date()
        });
        
        questionCount++;
        localStorage.setItem('questionCount', questionCount.toString());
        localStorage.setItem('lastSubmissionTime', Date.now().toString());
        
        if (questionCount >= MAX_QUESTIONS) {
          disableForm();
          startTimer(TIME_LIMIT);
        }
        
        this.reset();
        grecaptcha.reset();
        document.getElementById('char-count').textContent = '0/600';
        submitBtn.disabled = false;
        submitBtn.textContent = 'Enviar anonimamente';
        
        alert('✅ Pergunta enviada com sucesso! A resposta será publicada aqui após moderação.');
        
      } catch (error) {
        console.error('Erro:', error);
        alert('Erro ao enviar pergunta. Tente novamente.');
        submitBtn.disabled = false;
        submitBtn.textContent = 'Enviar anonimamente';
      }
    });

    // 🔥 CARREGAR RESPOSTAS ORGANIZADAS EM ABAS
    async function carregarRespostas() {
      const loadingEl = document.getElementById('loading-answers');
      const noAnswersEl = document.getElementById('no-answers');
      const tabsContainer = document.getElementById('tabs-container');
      
      try {
        console.log('Carregando respostas por tema...');
        
        const snapshot = await db.collection('perguntas')
          .orderBy('timestamp', 'desc')
          .get();
        
        // Organizar respostas por tema
        const respostasPorTema = {};
        const temasDisponiveis = [
          'Oratória', 'Saúde mental', 'Corpo humano', 'Reflexões', 
          'Dicas', 'Assuntos aleatórios', 'Curiosidades'
        ];
        
        temasDisponiveis.forEach(tema => {
          respostasPorTema[tema] = [];
        });
        
        snapshot.forEach(doc => {
          const data = doc.data();
          if (data.resposta && data.resposta.trim() !== '') {
            const tema = data.categoria || 'Assuntos aleatórios';
            if (!respostasPorTema[tema]) {
              respostasPorTema[tema] = [];
            }
            respostasPorTema[tema].push({ id: doc.id, ...data });
          }
        });
        
        const temasComRespostas = Object.keys(respostasPorTema).filter(
          tema => respostasPorTema[tema].length > 0
        );
        
        loadingEl.style.display = 'none';
        
        if (temasComRespostas.length === 0) {
          noAnswersEl.style.display = 'block';
          tabsContainer.style.display = 'none';
          return;
        }
        
        noAnswersEl.style.display = 'none';
        tabsContainer.style.display = 'block';
        
        criarAbas(temasComRespostas, respostasPorTema);
        
      } catch (error) {
        console.error('Erro ao carregar respostas:', error);
        loadingEl.innerHTML = `<div class="error">Erro ao carregar respostas: ${error.message}</div>`;
      }
    }

    // Criar abas dinamicamente
    function criarAbas(temas, respostasPorTema) {
      const tabsHeader = document.querySelector('.tabs-header');
      const tabsContent = document.querySelector('.tabs-content');
      
      tabsHeader.innerHTML = '';
      tabsContent.innerHTML = '';
      
      temas.forEach((tema, index) => {
        const tabButton = document.createElement('button');
        tabButton.className = `tab-button ${index === 0 ? 'active' : ''}`;
        tabButton.textContent = tema;
        tabButton.setAttribute('role', 'tab');
        tabButton.setAttribute('aria-selected', index === 0 ? 'true' : 'false');
        tabButton.setAttribute('aria-controls', `tab-${tema.toLowerCase().replace(/\s+/g, '-')}`);
        
        tabButton.addEventListener('click', () => {
          document.querySelectorAll('.tab-button').forEach(btn => {
            btn.classList.remove('active');
            btn.setAttribute('aria-selected', 'false');
          });
          
          document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
          });
          
          tabButton.classList.add('active');
          tabButton.setAttribute('aria-selected', 'true');
          document.getElementById(`tab-${tema.toLowerCase().replace(/\s+/g, '-')}`).classList.add('active');
        });
        
        tabsHeader.appendChild(tabButton);
      });
      
      temas.forEach((tema, index) => {
        const tabContent = document.createElement('div');
        tabContent.className = `tab-content ${index === 0 ? 'active' : ''}`;
        tabContent.id = `tab-${tema.toLowerCase().replace(/\s+/g, '-')}`;
        tabContent.setAttribute('role', 'tabpanel');
        
        const respostas = respostasPorTema[tema];
        
        if (respostas.length === 0) {
          tabContent.innerHTML = `
            <div class="empty-tab">
              <p>Nenhuma resposta publicada ainda para o tema <strong>${tema}</strong>.</p>
              <p>As respostas aparecerão aqui após a moderação.</p>
            </div>
          `;
        } else {
          tabContent.innerHTML = respostas.map(resposta => `
            <div class="resposta-card">
              <div class="resposta-header">
                <span class="data-resposta">
                  ${resposta.answeredAt?.toDate?.().toLocaleDateString('pt-BR') || 
                    resposta.timestamp?.toDate?.().toLocaleDateString('pt-BR') || 
                    'Data não disponível'}
                </span>
              </div>
              <div class="resposta-conteudo">
                <p>${resposta.resposta}</p>
              </div>
            </div>
          `).join('');
        }
        
        tabsContent.appendChild(tabContent);
      });
    }

    // Inicialização
    document.addEventListener('DOMContentLoaded', function() {
      document.getElementById('year').textContent = new Date().getFullYear();
      checkQuestionLimit();
      
      // Acessibilidade
      document.getElementById('toggle-contrast').addEventListener('click', function() {
        document.body.classList.toggle('high-contrast');
        this.setAttribute('aria-pressed', document.body.classList.contains('high-contrast'));
      });
      
      document.getElementById('bump-font').addEventListener('click', function() {
        document.body.classList.toggle('large-font');
        this.setAttribute('aria-pressed', document.body.classList.contains('large-font'));
      });
      
      // Carregar respostas
      setTimeout(() => {
        if (db) {
          carregarRespostas();
        } else {
          document.getElementById('loading-answers').innerHTML = 
            '<div class="error">Erro de conexão. Recarregue a página.</div>';
        }
      }, 1000);
    });
  </script>
</body>
</html>
