<?php
include 'auth.php';
include 'db.php';

$formId = isset($_GET['id']) ? (int) $_GET['id'] : 0;
if ($formId <= 0) {
    die('Formulário inválido!');
}

$stmtFormulario = $pdo->prepare('SELECT * FROM formularios WHERE id = :id');
$stmtFormulario->execute(array('id' => $formId));
$formulario = $stmtFormulario->fetch(PDO::FETCH_ASSOC);
if (!$formulario) {
    die('Formulário não encontrado!');
}

$stmtTotais = $pdo->prepare('SELECT COUNT(*) AS total, SUM(CASE WHEN COALESCE(lida, 0) = 0 THEN 1 ELSE 0 END) AS nao_lidas FROM formulario_respostas WHERE formulario_id = :id');
$stmtTotais->execute(array('id' => $formId));
$totais = $stmtTotais->fetch(PDO::FETCH_ASSOC);
if (!$totais) {
    $totais = array('total' => 0, 'nao_lidas' => 0);
}

$stmtLidas = $pdo->prepare('UPDATE formulario_respostas SET lida = 1 WHERE formulario_id = :id AND COALESCE(lida, 0) = 0');
$stmtLidas->execute(array('id' => $formId));

$stmtCampos = $pdo->prepare("SELECT id, label, tipo FROM formulario_campos WHERE formulario_id = :id AND COALESCE(tipo, '') <> 'warning' AND COALESCE(hidden, 0) = 0 ORDER BY id ASC");
$stmtCampos->execute(array('id' => $formId));
$campos = $stmtCampos->fetchAll(PDO::FETCH_ASSOC);

$nomeFormulario = isset($formulario['nome']) ? (string) $formulario['nome'] : 'Formulário';
$categoriaFormulario = isset($formulario['categoria']) && trim((string) $formulario['categoria']) !== ''
    ? (string) $formulario['categoria']
    : 'Sem categoria';
$isFichaAdmissao = ($nomeFormulario === 'FICHA DE IDENTIFICAÇÃO - ADMISSÃO');

function h_form_resposta($value)
{
    return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Respostas — <?= h_form_resposta($nomeFormulario) ?></title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<link rel="icon" type="image/png" href="img/Logo.png">
<style>
  :root {
    --shell-padding: 1rem;
  }
  html, body {
    height: 100%;
  }
  body {
    overflow: hidden;
  }
  #appShell {
    height: 100vh;
    display: flex;
    flex-direction: column;
  }
  #contentShell {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
  }
  #responseListShell {
    flex: 1;
    min-height: 0;
    overflow: auto;
    padding-right: .25rem;
  }
  #responseListShell::-webkit-scrollbar {
    width: 10px;
  }
  #responseListShell::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 999px;
  }
  .metric-card,
  .panel-card {
    border: 1px solid #e2e8f0;
    background: #ffffff;
    border-radius: 1.25rem;
    box-shadow: 0 1px 2px rgba(15, 23, 42, .04);
  }
  .metric-card {
    padding: .9rem 1rem;
  }
  .metric-card strong {
    display: block;
    margin-top: .2rem;
    font-size: 1.2rem;
    line-height: 1;
    color: #0f172a;
  }
  .top-button,
  .action-button {
    border-radius: .9rem;
    font-size: .875rem;
    font-weight: 600;
    padding: .72rem .95rem;
    transition: .18s ease;
  }
  .response-card, .resposta-card {
    position: relative;
    border: 1px solid #e2e8f0;
    background: #fff;
    border-radius: 1.4rem;
    padding: 1rem;
    box-shadow: 0 1px 2px rgba(15, 23, 42, .04);
    transition: .18s ease;
  }
  .response-card:hover, .resposta-card:hover {
    transform: translateY(-1px);
    box-shadow: 0 10px 18px rgba(15, 23, 42, .06);
  }
  .response-checkbox {
    position: absolute;
    top: 1rem;
    left: 1rem;
    width: 1.05rem;
    height: 1.05rem;
    accent-color: #2563eb;
    display: none;
    z-index: 3;
  }
  .response-checkbox.is-visible {
    display: block;
  }
  .response-card.is-selection-mode, .resposta-card.is-selection-mode {
    padding-left: 2.7rem;
  }
  .response-files img {
    width: 100%;
    height: 4.8rem;
    object-fit: cover;
    border-radius: .95rem;
    border: 1px solid #e2e8f0;
  }
  .response-details.is-hidden {
    display: none;
  }
  .mass-actions.is-hidden {
    opacity: 0;
    transform: translateY(.75rem);
    pointer-events: none;
  }
  .toast {
    position: fixed;
    top: 1rem;
    right: 1rem;
    z-index: 60;
    min-width: 220px;
    max-width: 380px;
    border-radius: 1rem;
    padding: .9rem 1rem;
    color: #fff;
    box-shadow: 0 12px 24px rgba(15, 23, 42, .18);
  }
  .toast.success { background: #0f766e; }
  .toast.error { background: #b91c1c; }
  .toast.info { background: #1d4ed8; }
  @media (max-width: 1024px) {
    body {
      overflow: auto;
    }
    #appShell {
      height: auto;
      min-height: 100vh;
    }
    #contentShell,
    #responseListShell {
      min-height: auto;
      overflow: visible;
      padding-right: 0;
    }
  }
</style>
</head>
<body class="bg-slate-100 text-slate-800">
<div id="appShell">
  <header class="border-b border-slate-200 bg-white/95 backdrop-blur">
    <div class="mx-auto flex max-w-7xl flex-wrap items-center justify-between gap-3 px-4 py-3 sm:px-6">
      <div class="min-w-0">
        <div class="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">Respostas do formulário</div>
        <h1 class="truncate text-xl font-bold text-slate-900"><?= h_form_resposta($nomeFormulario) ?></h1>
        <div class="mt-1 flex flex-wrap items-center gap-2 text-sm text-slate-500">
          <span class="rounded-full bg-slate-100 px-2.5 py-1 text-xs font-semibold text-slate-600"><?= h_form_resposta($categoriaFormulario) ?></span>
          <span>#<?= (int) $formId ?></span>
        </div>
      </div>

      <div class="flex flex-wrap gap-2">
        <a href="formularios.php" class="top-button border border-slate-300 bg-white text-slate-700 hover:bg-slate-50">Voltar</a>
        <button type="button" id="btnAtualizar" class="top-button border border-slate-300 bg-white text-slate-700 hover:bg-slate-50">Atualizar</button>
        <button type="button" id="btnCopiarLink" class="top-button bg-slate-900 text-white hover:bg-slate-800">Copiar link</button>
      </div>
    </div>
  </header>

  <main id="contentShell" class="mx-auto flex w-full max-w-7xl flex-1 flex-col gap-3 px-4 py-4 sm:px-6">
    <section class="panel-card p-3">
      <div class="grid gap-3 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,1.35fr)] xl:items-center">
        <div class="rounded-[1.1rem] bg-gradient-to-r from-slate-950 via-slate-900 to-blue-700 px-4 py-4 text-white">
          <div class="text-[11px] font-semibold uppercase tracking-[0.18em] text-blue-100">Resumo</div>
          <div class="mt-1 text-lg font-bold"><?= h_form_resposta($nomeFormulario) ?></div>
          <p class="mt-1 text-sm text-blue-100">Filtros em cima, respostas embaixo e ações rápidas sem bagunça.</p>
        </div>

        <div class="grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
          <div class="metric-card">
            <span class="text-xs font-medium text-slate-500">Total</span>
            <strong><?= (int) $totais['total'] ?></strong>
          </div>
          <div class="metric-card">
            <span class="text-xs font-medium text-slate-500">Filtradas</span>
            <strong id="metricFiltradas"><?= (int) $totais['total'] ?></strong>
          </div>
          <div class="metric-card">
            <span class="text-xs font-medium text-slate-500">Novas ao abrir</span>
            <strong><?= (int) $totais['nao_lidas'] ?></strong>
          </div>
          <div class="metric-card">
            <span class="text-xs font-medium text-slate-500">Campos</span>
            <strong><?= count($campos) ?></strong>
          </div>
        </div>
      </div>
    </section>

    <section class="panel-card p-3">
      <div class="grid gap-2 xl:grid-cols-[220px_minmax(0,1fr)_165px_165px_auto]">
        <select id="campoFiltro" class="rounded-2xl border border-slate-300 px-3 py-2.5 text-sm text-slate-700 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
          <option value="">Todos os campos</option>
          <?php foreach ($campos as $campo): ?>
            <option value="<?= (int) $campo['id'] ?>"><?= h_form_resposta($campo['label']) ?></option>
          <?php endforeach; ?>
        </select>

        <input type="text" id="searchInput" placeholder="Buscar por nome, unidade, cargo, CPF..." class="rounded-2xl border border-slate-300 px-3 py-2.5 text-sm text-slate-700 placeholder:text-slate-400 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
        <input type="date" id="dataInicio" class="rounded-2xl border border-slate-300 px-3 py-2.5 text-sm text-slate-700 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
        <input type="date" id="dataFim" class="rounded-2xl border border-slate-300 px-3 py-2.5 text-sm text-slate-700 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">

        <div class="flex flex-wrap gap-2 xl:justify-end">
          <button type="button" id="btnExportar" class="action-button bg-blue-600 text-white hover:bg-blue-700">Excel</button>
          <a href="importar_respostas.php?formId=<?= (int) $formId ?>" class="action-button bg-emerald-600 text-white hover:bg-emerald-700">Importar</a>
          <button type="button" id="btnLimparFiltros" class="action-button border border-slate-300 bg-white text-slate-700 hover:bg-slate-50">Limpar</button>
        </div>
      </div>

      <div class="mt-3 flex flex-wrap items-center justify-between gap-2 border-t border-slate-100 pt-3">
        <div class="text-sm text-slate-500" id="statusResultados">Carregando respostas...</div>
        <div class="flex flex-wrap gap-2">
          <button type="button" id="btnExpandirTodos" class="action-button border border-slate-300 bg-white text-slate-700 hover:bg-slate-50">Expandir tudo</button>
          <button type="button" id="btnSelecionarModo" class="action-button border border-slate-300 bg-white text-slate-700 hover:bg-slate-50">Selecionar</button>
        </div>
      </div>
    </section>

    <section class="panel-card flex min-h-0 flex-1 flex-col p-3">
      <div id="responseListShell">
        <div id="respostasContainer" class="space-y-3"></div>
      </div>
      <div id="paginacaoContainer" class="mt-3 flex flex-wrap justify-center gap-2 border-t border-slate-100 pt-3"></div>
    </section>
  </main>
</div>

<div id="acoesEmMassa" class="mass-actions is-hidden fixed bottom-4 right-4 z-40 flex flex-wrap items-center gap-2 transition duration-200">
  <div class="rounded-2xl border border-slate-200 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 shadow-sm"><span id="selectedCount">0</span> selecionada(s)</div>
  <button id="btnExcluirTodos" type="button" class="action-button bg-red-600 text-white shadow-sm hover:bg-red-700">Excluir</button>
  <?php if ($isFichaAdmissao): ?>
    <button id="btnGerarFichaTodos" type="button" class="action-button bg-emerald-600 text-white shadow-sm hover:bg-emerald-700">Ficha</button>
  <?php endif; ?>
  <button id="btnExportarImagens" type="button" class="action-button bg-indigo-600 text-white shadow-sm hover:bg-indigo-700">Imagens</button>
</div>

<div id="toastContainer"></div>

<script>
(function () {
  const respostasContainer = document.getElementById('respostasContainer');
  const paginacaoContainer = document.getElementById('paginacaoContainer');
  const searchInput = document.getElementById('searchInput');
  const campoFiltro = document.getElementById('campoFiltro');
  const dataInicio = document.getElementById('dataInicio');
  const dataFim = document.getElementById('dataFim');
  const statusResultados = document.getElementById('statusResultados');
  const metricFiltradas = document.getElementById('metricFiltradas');
  const btnExportar = document.getElementById('btnExportar');
  const btnAtualizar = document.getElementById('btnAtualizar');
  const btnCopiarLink = document.getElementById('btnCopiarLink');
  const btnExcluirTodos = document.getElementById('btnExcluirTodos');
  const btnGerarFichaTodos = document.getElementById('btnGerarFichaTodos');
  const btnExportarImagens = document.getElementById('btnExportarImagens');
  const btnSelecionarModo = document.getElementById('btnSelecionarModo');
  const btnExpandirTodos = document.getElementById('btnExpandirTodos');
  const btnLimparFiltros = document.getElementById('btnLimparFiltros');
  const acoesEmMassa = document.getElementById('acoesEmMassa');
  const selectedCount = document.getElementById('selectedCount');
  const toastContainer = document.getElementById('toastContainer');
  const formId = <?= (int) $formId ?>;

  let currentPage = 1;
  let selectionMode = false;
  let expandAll = false;

  function debounce(fn, delay) {
    let timer = null;
    return function () {
      const args = arguments;
      clearTimeout(timer);
      timer = setTimeout(function () {
        fn.apply(null, args);
      }, delay || 300);
    };
  }

  function escapeHtml(value) {
    return String(value)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;');
  }

  function showToast(message, type) {
    const toast = document.createElement('div');
    toast.className = 'toast ' + (type || 'info');
    toast.textContent = message;
    toastContainer.appendChild(toast);
    setTimeout(function () {
      toast.remove();
    }, 2600);
  }

  function buildQueryParams(page) {
    return new URLSearchParams({
      id: String(formId),
      page: String(page || 1),
      q: searchInput.value.trim(),
      campo: campoFiltro.value,
      dataInicio: dataInicio.value,
      dataFim: dataFim.value
    });
  }

  function isPeriodValid() {
    if (dataInicio.value && dataFim.value && dataInicio.value > dataFim.value) {
      statusResultados.textContent = 'A data inicial não pode ser maior que a data final.';
      metricFiltradas.textContent = '0';
      return false;
    }
    return true;
  }

  function getSelectedCheckboxes() {
    return Array.prototype.slice.call(document.querySelectorAll('.response-checkbox:checked'));
  }

  function getCheckboxResponseId(checkbox) {
    if (checkbox.dataset && checkbox.dataset.id) {
      return checkbox.dataset.id;
    }
    const card = checkbox.closest('.response-card, .resposta-card');
    return card && card.dataset ? card.dataset.id : '';
  }

  function updateMassActions() {
    const selected = getSelectedCheckboxes();
    selectedCount.textContent = String(selected.length);
    acoesEmMassa.classList.toggle('is-hidden', selected.length === 0);
  }


  function resetSelectionState() {
    selectionMode = false;
    const checkboxes = document.querySelectorAll('.response-checkbox, .select-card');
    Array.prototype.forEach.call(checkboxes, function (checkbox) {
      checkbox.checked = false;
    });
    applySelectionMode();
  }
  function applySelectionMode() {
    const checkboxes = document.querySelectorAll('.response-checkbox, .select-card');
    const cards = document.querySelectorAll('.response-card, .resposta-card');

    Array.prototype.forEach.call(checkboxes, function (checkbox) {
      checkbox.classList.toggle('is-visible', selectionMode);
      if (!selectionMode) {
        checkbox.checked = false;
      }
    });

    Array.prototype.forEach.call(cards, function (card) {
      card.classList.toggle('is-selection-mode', selectionMode);
    });

    btnSelecionarModo.textContent = selectionMode ? 'Ocultar seleção' : 'Selecionar';
    updateMassActions();
  }

  function setDetailsState(card, show) {
    const details = card.querySelector('.detalhes-card, .response-details');
    const toggleButton = card.querySelector('.toggle-card');
    if (!details) {
      return;
    }

    details.classList.toggle('hidden', !show);
    details.classList.toggle('is-hidden', !show);
    if (toggleButton) {
      toggleButton.textContent = show ? 'Ocultar' : 'Detalhes';
    }
  }

  function applyExpandAll() {
    const cards = document.querySelectorAll('.response-card, .resposta-card');
    Array.prototype.forEach.call(cards, function (card) {
      setDetailsState(card, expandAll);
    });
    btnExpandirTodos.textContent = expandAll ? 'Recolher tudo' : 'Expandir tudo';
  }

  function generatePagination(totalPages, page) {
    const maxButtons = 7;
    let start = Math.max(1, page - Math.floor(maxButtons / 2));
    let end = Math.min(totalPages, start + maxButtons - 1);
    start = Math.max(1, end - maxButtons + 1);
    let html = '';

    if (page > 1) {
      html += '<button class="page-btn rounded-2xl border border-slate-200 bg-white px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50" data-page="' + (page - 1) + '">«</button>';
    }

    for (let i = start; i <= end; i += 1) {
      const activeClass = i === page
        ? 'bg-blue-600 text-white border-blue-600'
        : 'bg-white text-slate-700 border-slate-200 hover:bg-slate-50';
      html += '<button class="page-btn rounded-2xl border px-3 py-2 text-sm font-semibold ' + activeClass + '" data-page="' + i + '">' + i + '</button>';
    }

    if (page < totalPages) {
      html += '<button class="page-btn rounded-2xl border border-slate-200 bg-white px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50" data-page="' + (page + 1) + '">»</button>';
    }

    return html;
  }

  function normalizeFileName(name) {
    return String(name || '').replace(/[^\w.\-]/g, '_');
  }

  function detectFileName(url, fallback) {
    try {
      const clean = String(url || '').split('?')[0];
      const fileName = clean.split('/').pop() || fallback;
      return normalizeFileName(fileName || fallback);
    } catch (error) {
      return fallback;
    }
  }

  function getImageLinks(card) {
    return Array.prototype.slice.call(card.querySelectorAll('.arquivos-container a, .response-files a')).filter(function (link) {
      if (link.querySelector('img')) {
        return true;
      }
      const href = link.getAttribute('href') || '';
      return /\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(href);
    });
  }

  async function exportSelectedImages() {
    const selected = getSelectedCheckboxes();
    if (!selected.length) {
      showToast('Selecione ao menos uma resposta.', 'error');
      return;
    }

    btnExportarImagens.disabled = true;
    const oldText = btnExportarImagens.textContent;
    btnExportarImagens.textContent = 'Gerando ZIP...';

    try {
      const zip = new JSZip();
      let totalFiles = 0;

      for (const checkbox of selected) {
        const card = checkbox.closest('.response-card, .resposta-card');
        if (!card) {
          continue;
        }

        const links = getImageLinks(card);
        if (!links.length) {
          continue;
        }

        const folder = zip.folder('resposta_' + checkbox.dataset.id);
        let counter = 1;

        for (const link of links) {
          try {
            const href = link.getAttribute('href');
            if (!href) {
              continue;
            }

            const fileUrl = new URL(href, window.location.origin).href;
            const response = await fetch(fileUrl);
            if (!response.ok) {
              continue;
            }

            const blob = await response.blob();
            if (String(blob.type || '').indexOf('image/') !== 0) {
              continue;
            }

            let name = detectFileName(fileUrl, 'imagem_' + counter);
            if (!/\.[a-z0-9]+$/i.test(name)) {
              const ext = (blob.type.split('/')[1] || 'jpg').replace(/[^a-z0-9]/gi, '');
              name += '.' + ext;
            }

            folder.file(name, blob);
            totalFiles += 1;
            counter += 1;
          } catch (error) {
            console.error(error);
          }
        }
      }

      if (!totalFiles) {
        showToast('Nenhuma imagem encontrada nas respostas selecionadas.', 'error');
        return;
      }

      const zipBlob = await zip.generateAsync({ type: 'blob' });
      saveAs(zipBlob, 'imagens_formulario_' + formId + '.zip');
      showToast('ZIP das imagens gerado com sucesso.', 'success');
    } finally {
      btnExportarImagens.disabled = false;
      btnExportarImagens.textContent = oldText;
    }
  }

  function submitDeletion(payload) {
    const form = document.createElement('form');
    form.method = 'post';
    form.action = 'deletar_resposta.php';

    Object.keys(payload).forEach(function (key) {
      const input = document.createElement('input');
      input.type = 'hidden';
      input.name = key;
      input.value = Array.isArray(payload[key]) ? payload[key].join(',') : String(payload[key]);
      form.appendChild(input);
    });

    document.body.appendChild(form);
    form.submit();
  }

  function bindResponseCards() {
    const cards = document.querySelectorAll('.response-card, .resposta-card');

    Array.prototype.forEach.call(cards, function (card) {
      const checkbox = card.querySelector('.response-checkbox, .select-card');
      const toggleButton = card.querySelector('.toggle-card');
      const editButton = card.querySelector('[data-action="editar"]');
      const deleteButton = card.querySelector('[data-action="excluir"]');
      const fichaButton = card.querySelector('[data-action="ficha"]');
      const details = card.querySelector('.detalhes-card, .response-details');

      if (checkbox) {
        checkbox.classList.add('response-checkbox');
        checkbox.addEventListener('click', function (event) {
          event.stopPropagation();
          updateMassActions();
        });
      }

      if (toggleButton) {
        toggleButton.addEventListener('click', function (event) {
          event.stopPropagation();
          const isHidden = details ? details.classList.contains('hidden') || details.classList.contains('is-hidden') : true;
          setDetailsState(card, isHidden);
        });
      }

      if (editButton) {
        editButton.addEventListener('click', function (event) {
          event.stopPropagation();
          window.location.href = 'editar_resposta.php?id=' + card.dataset.id;
        });
      }

      if (deleteButton) {
        deleteButton.addEventListener('click', function (event) {
          event.stopPropagation();
          if (confirm('Excluir esta resposta?')) {
            submitDeletion({ id: card.dataset.id });
          }
        });
      }

      if (fichaButton) {
        fichaButton.addEventListener('click', function (event) {
          event.stopPropagation();
          window.open('gerar_ficha.php?id=' + card.dataset.id, '_blank');
        });
      }

      card.addEventListener('click', function (event) {
        if (
          event.target.closest('button') ||
          event.target.closest('a') ||
          event.target.closest('input') ||
          event.target.closest('.detalhes-card') ||
          event.target.closest('.response-details')
        ) {
          return;
        }

        if (selectionMode && checkbox) {
          checkbox.checked = !checkbox.checked;
          updateMassActions();
          return;
        }

        if (details) {
          const isHidden = details.classList.contains('hidden') || details.classList.contains('is-hidden');
          setDetailsState(card, isHidden);
        }
      });
    });

    applySelectionMode();
    applyExpandAll();
  }

  async function loadResponses(page) {
    if (!isPeriodValid()) {
      respostasContainer.innerHTML = '<div class="rounded-3xl border border-amber-200 bg-amber-50 p-8 text-center text-amber-700">Corrija o período para continuar.</div>';
      paginacaoContainer.innerHTML = '';
      resetSelectionState();
      return;
    }

    respostasContainer.innerHTML = '<div class="rounded-3xl border border-slate-200 bg-slate-50 p-8 text-center text-slate-500">Carregando respostas...</div>';
    paginacaoContainer.innerHTML = '';
    statusResultados.textContent = 'Carregando respostas...';
    acoesEmMassa.classList.add('is-hidden');

    try {
      const response = await fetch('buscar_respostas.php?' + buildQueryParams(page || 1).toString(), {
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
      });
      const data = await response.json().catch(function () { return {}; });

      if (!response.ok) {
        throw new Error(data.error || 'Erro ao carregar respostas.');
      }

      currentPage = Number(data.page || page || 1);
      respostasContainer.innerHTML = data.respostas || '';
      paginacaoContainer.innerHTML = generatePagination(Number(data.totalPages || 1), currentPage);
      metricFiltradas.textContent = String(data.total || 0);
      statusResultados.textContent = (data.total || 0) + ' resposta(s) • página ' + currentPage + ' de ' + (data.totalPages || 1);

      Array.prototype.forEach.call(document.querySelectorAll('.page-btn'), function (button) {
        button.addEventListener('click', function () {
          loadResponses(Number(button.dataset.page || 1));
        });
      });

      bindResponseCards();
      updateMassActions();
    } catch (error) {
      const message = error && error.message ? error.message : 'Erro ao carregar respostas.';
      respostasContainer.innerHTML = '<div class="rounded-3xl border border-red-200 bg-red-50 p-8 text-center text-red-600">' + escapeHtml(message) + '</div>';
      paginacaoContainer.innerHTML = '';
      statusResultados.textContent = message;
      metricFiltradas.textContent = '0';
      resetSelectionState();
    }
  }

  btnAtualizar.addEventListener('click', function () {
    loadResponses(currentPage);
    showToast('Lista atualizada.', 'info');
  });

  btnCopiarLink.addEventListener('click', function () {
    const url = new URL('formulario_view.php?id=' + formId, window.location.href).href;
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(url).then(function () {
        showToast('Link copiado com sucesso.', 'success');
      }).catch(function () {
        window.prompt('Copie o link abaixo:', url);
      });
      return;
    }
    window.prompt('Copie o link abaixo:', url);
  });

  btnSelecionarModo.addEventListener('click', function () {
    selectionMode = !selectionMode;
    applySelectionMode();
  });

  btnExpandirTodos.addEventListener('click', function () {
    expandAll = !expandAll;
    applyExpandAll();
  });

  btnExcluirTodos.addEventListener('click', function () {
    const ids = getSelectedCheckboxes().map(function (checkbox) {
      return getCheckboxResponseId(checkbox);
    });

    if (!ids.length) {
      showToast('Selecione ao menos uma resposta.', 'error');
      return;
    }

    if (confirm('Excluir as respostas selecionadas?')) {
      submitDeletion({ ids: ids });
    }
  });

  if (btnGerarFichaTodos) {
    btnGerarFichaTodos.addEventListener('click', function () {
      const ids = getSelectedCheckboxes().map(function (checkbox) {
        return getCheckboxResponseId(checkbox);
      });
      if (!ids.length) {
        showToast('Selecione ao menos uma resposta.', 'error');
        return;
      }
      window.location.href = 'gerar_ficha_em_massa.php?formId=' + formId + '&ids=' + encodeURIComponent(ids.join(','));
    });
  }

  btnExportarImagens.addEventListener('click', exportSelectedImages);

  btnExportar.addEventListener('click', function () {
    if (!isPeriodValid()) {
      showToast('Corrija o período antes de exportar.', 'error');
      return;
    }
    window.location.href = 'exportar_respostas.php?' + buildQueryParams(1).toString();
  });

  btnLimparFiltros.addEventListener('click', function () {
    searchInput.value = '';
    campoFiltro.value = '';
    dataInicio.value = '';
    dataFim.value = '';
    loadResponses(1);
  });

  const debouncedLoad = debounce(function () {
    loadResponses(1);
  }, 320);

  searchInput.addEventListener('input', debouncedLoad);
  campoFiltro.addEventListener('change', function () {
    loadResponses(1);
  });
  dataInicio.addEventListener('change', function () {
    loadResponses(1);
  });
  dataFim.addEventListener('change', function () {
    loadResponses(1);
  });

  document.addEventListener('keydown', function (event) {
    if (event.key === 'Escape' && selectionMode) {
      selectionMode = false;
      applySelectionMode();
    }
  });

  loadResponses(currentPage);
})();
</script>
</body>
</html>
