<?php
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/helpers.php';

require_login();
if (($_SESSION['tipo'] ?? '') !== 'operador') {
  header('Location:/arapiraca/vereador.php');
  exit;
}

$sessao_id = isset($_GET['sessao']) ? (int)$_GET['sessao'] : 0;
if (!$sessao_id) {
  header('Location:/arapiraca/admin.php');
  exit;
}

/* --- marcar / desmarcar SOMENTE LEITURA nesta tela --- */
if (($_GET['op'] ?? '') === 'toggle_leitura') {
  $sm_id = (int)($_GET['sm_id'] ?? 0);
  if ($sm_id > 0) {
    $st = $pdo->prepare("
      SELECT somente_leitura
      FROM sessao_materias
      WHERE id = :id AND sessao_id = :s
    ");
    $st->execute([':id' => $sm_id, ':s' => $sessao_id]);
    $row = $st->fetch();

    if ($row) {
      // para PostgreSQL: boolean vem como 't'/'f', então convertemos
      $atual = !empty($row['somente_leitura']);
      $novo  = $atual ? 0 : 1;

      $up = $pdo->prepare("
        UPDATE sessao_materias
           SET somente_leitura = :novo
         WHERE id = :id AND sessao_id = :s
      ");
      $up->execute([':novo' => $novo, ':id' => $sm_id, ':s' => $sessao_id]);
    }
  }

  header('Location:/arapiraca/admin_materia_nova.php?sessao=' . $sessao_id);
  exit;
}

/* --- carrega vereadores + proponentes --- */
$vereadores = $pdo->query("
    SELECT id, nome, COALESCE(partido,'') AS partido, tipo_usuario
    FROM usuarios
    WHERE (tipo_usuario = 'vereador' OR tipo_usuario = 'proponente') AND ativo = 1
    ORDER BY nome
")->fetchAll();

/* --- tipos --- */
$tipos_pre = ['Ata', 'Indicação', 'Requerimento', 'Projeto de Lei', 'Ordem do Dia', 'Decreto Legislativo', 'Moção', 'Parecer'];

/* --- lista matérias --- */
$stmt = $pdo->prepare("
SELECT
  sm.id AS sm_id, sm.status, sm.resultado, sm.ordem,
  sm.votos_favor, sm.votos_contra, sm.votos_abstencao,
  sm.publicar_site,
  sm.somente_leitura,
  m.id AS materia_id, m.numero, m.ano, m.tipo AS tipo_materia,
  m.titulo, m.descricao, m.autor_id,
  u.nome AS autor_nome, u.partido AS autor_partido, u.tipo_usuario AS autor_tipo
FROM sessao_materias sm
JOIN materias m ON m.id = sm.materia_id
LEFT JOIN usuarios u ON u.id = m.autor_id
WHERE sm.sessao_id = :s
ORDER BY sm.ordem ASC, sm.id ASC
");
$stmt->execute([':s' => $sessao_id]);
$lista = $stmt->fetchAll();

$msg = null;
$err = null;

/* --- valores do form --- */
$titulo_form    = trim($_POST['titulo']    ?? '');
$desc_form      = trim($_POST['descricao'] ?? '');
$numero_form    = trim($_POST['numero']    ?? '001');
$ano_form       = (int)($_POST['ano']      ?? date('Y'));
$tipo_form      = trim($_POST['tipo']      ?? 'Projeto de Lei');
$autor_id_form  = (int)($_POST['autor_id'] ?? 0);

/* Para ancoragem/realce após salvar */
$new_sm_id = 0;

/* --- cadastrar nova matéria --- */
if (is_post() && ($_GET['op'] ?? '') !== 'editar_inline') {
  $titulo   = $titulo_form;
  $desc     = $desc_form;
  $numero   = $numero_form;
  $ano      = $ano_form;
  $tipo     = $tipo_form ?: 'Projeto de Lei';
  $autor_id = $autor_id_form;

  if ($titulo === '' || $autor_id <= 0) {
    $err = "Informe o título e selecione o propositor.";
  } else {
    // aceita vereador OU proponente
    $chk = $pdo->prepare("SELECT COUNT(*) FROM usuarios WHERE id=:id AND (tipo_usuario='vereador' OR tipo_usuario='proponente') AND ativo=1");
    $chk->execute([':id' => $autor_id]);
    if (!$chk->fetchColumn()) {
      $err = "Propositor inválido (precisa ser Vereador ou Proponente ativo).";
    }
  }

  if (!$err) {
    $pdo->beginTransaction();
    try {
      $pdo->prepare("
        INSERT INTO materias (numero, ano, tipo, titulo, descricao, autor_id)
        VALUES (:num, :ano, :tipo, :tit, :des, :autor)
      ")->execute([
        ':num'   => $numero,
        ':ano'   => $ano,
        ':tipo'  => $tipo,
        ':tit'   => $titulo,
        ':des'   => $desc,
        ':autor' => $autor_id
      ]);

      $materia_id = (int)$pdo->lastInsertId();

      $pdo->prepare("
        INSERT INTO sessao_materias (sessao_id, materia_id, ordem, status, publicar_site)
        VALUES (
          :s, :m,
          (SELECT COALESCE(MAX(ordem),0)+1 FROM (SELECT ordem FROM sessao_materias WHERE sessao_id=:s) t),
          'aguardando',
          1
        )
      ")->execute([':s' => $sessao_id, ':m' => $materia_id]);

      $new_sm_id = (int)$pdo->lastInsertId();

      $pdo->commit();
      $msg = "Matéria adicionada com sucesso.";

      // limpa form
      $titulo_form    = '';
      $desc_form      = '';
      $numero_form    = '001';
      $ano_form       = (int)date('Y');
      $tipo_form      = 'Projeto de Lei';
      $autor_id_form  = 0;

      // recarrega listagem
      $stmt->execute([':s' => $sessao_id]);
      $lista = $stmt->fetchAll();
    } catch (Throwable $e) {
      $pdo->rollBack();
      $err = "Erro ao salvar: " . $e->getMessage();
    }
  }
}

/* ===================== PEDIDOS DE VOZ ===================== */
$qAnd = $pdo->prepare("
  SELECT pf.*, u.nome, u.foto, UNIX_TIMESTAMP(pf.tempo_inicio) AS started_at
  FROM pedidos_fala pf
  JOIN usuarios u ON u.id = pf.vereador_id
  WHERE pf.sessao_id = :s AND pf.status = 'autorizada'
  ORDER BY pf.tempo_inicio DESC
  LIMIT 1
");
$qAnd->execute([':s' => $sessao_id]);
$voz_andamento = $qAnd->fetch();

$qPend = $pdo->prepare("
  SELECT pf.*, u.nome, u.foto
  FROM pedidos_fala pf
  JOIN usuarios u ON u.id = pf.vereador_id
  WHERE pf.sessao_id = :s AND pf.status = 'pendente'
  ORDER BY pf.id ASC
");
$qPend->execute([':s' => $sessao_id]);
$voz_pendentes = $qPend->fetchAll();

$qHist = $pdo->prepare("
  SELECT pf.*, u.nome
  FROM pedidos_fala pf
  JOIN usuarios u ON u.id = pf.vereador_id
  WHERE pf.sessao_id = :s AND pf.status IN ('finalizada','cancelada')
  ORDER BY pf.id DESC
  LIMIT 20
");
$qHist->execute([':s' => $sessao_id]);
$voz_historico = $qHist->fetchAll();
?>
<!doctype html>
<html lang="pt-br">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
  <link rel="stylesheet" href="/arapiraca/assets/style.css">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
  <title>Matérias da Sessão</title>
  <style>
    :root {
      --bg-grad-a: #eef2ff;
      --bg-grad-b: #f5f3ff;
      --card-bg: #ffffff;
      --border: #e5e7eb;
      --text: #0f172a;
      --muted: #64748b;
      --brand: #3b82f6;
      --brand-2: #2563eb;
      --green: #16a34a;
      --red: #ef4444;
      --amber: #f59e0b;
      --blue-badge: #dbeafe;
      --blue-badge-text: #1e40af;
      --gray-badge: #e5e7eb;
      --gray-badge-text: #374151;
      --shadow: 0 10px 30px rgba(2, 6, 23, .06);
      --flash: #fff7ed;
    }

    body {
      font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "Apple Color Emoji", "Segoe UI Emoji";
      background: radial-gradient(1200px 600px at 10% -10%, var(--bg-grad-a), transparent),
        radial-gradient(1200px 600px at 110% 0%, var(--bg-grad-b), transparent),
        #f8fafc;
      color: var(--text);
    }

    .header {
      position: sticky;
      top: 0;
      z-index: 10;
      backdrop-filter: blur(8px);
      background: rgba(255, 255, 255, .8);
      border-bottom: 1px solid var(--border);
    }

    .header-inner {
      max-width: 1200px;
      margin: 0 auto;
      padding: 12px 16px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 12px;
      flex-wrap: wrap;
    }

    .brand {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .brand .title {
      font-weight: 800;
      font-size: 1.1rem;
    }

    .actions {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
      position: relative;
    }

    .btn {
      --btn-bg: #fff;
      --btn-fg: #1f2a44;
      --btn-bd: var(--border);
      display: inline-flex;
      align-items: center;
      gap: 8px;
      background: var(--btn-bg);
      color: var(--btn-fg);
      border: 2px solid var(--btn-bd);
      text-decoration: none;
      border-radius: 10px;
      padding: .55rem .9rem;
      font-weight: 800;
      cursor: pointer;
      box-shadow: var(--shadow);
      transition: transform .15s ease, filter .15s ease, background .15s ease, border-color .15s ease;
    }

    .btn:hover {
      transform: translateY(-1px);
      filter: brightness(.98);
    }

    .btn.small {
      padding: .45rem .7rem;
      font-size: .88rem;
    }

    .btn.block {
      width: 100%;
      justify-content: center;
    }

    .btn-primary {
      --btn-bg: var(--brand);
      --btn-fg: #fff;
      --btn-bd: var(--brand);
      box-shadow: 0 8px 18px rgba(59, 130, 246, .18);
    }

    .btn-primary:hover {
      background: var(--brand-2);
      border-color: var(--brand-2);
    }

    .btn-success {
      --btn-bg: var(--green);
      --btn-fg: #fff;
      --btn-bd: var(--green);
    }

    .btn-danger {
      --btn-bg: var(--red);
      --btn-fg: #fff;
      --btn-bd: var(--red);
    }

    .btn-warning {
      --btn-bg: var(--amber);
      --btn-fg: #fff;
      --btn-bd: var(--amber);
    }

    .btn-secondary {
      --btn-bg: #fff;
      --btn-fg: #1f2a44;
      --btn-bd: var(--border);
    }

    .btn-outline-primary {
      --btn-bg: #fff;
      --btn-fg: var(--brand-2);
      --btn-bd: var(--brand-2);
    }

    .btn-outline-primary:hover {
      background: #eff6ff;
    }

    .notif {
      position: absolute;
      top: -6px;
      right: -6px;
      background: var(--red);
      color: #fff;
      border-radius: 999px;
      font-size: .72rem;
      padding: 2px 6px;
      line-height: 1;
      box-shadow: var(--shadow);
    }

    @keyframes pulse {
      0% {
        transform: scale(.9)
      }

      50% {
        transform: scale(1.15)
      }

      100% {
        transform: scale(1)
      }
    }

    .notif.pulse {
      animation: pulse 1s ease-out 3;
    }

    .voice-pill {
      position: absolute;
      top: calc(100% + 8px);
      right: 0;
      background: #0f172a;
      color: #fff;
      border: 2px solid var(--red);
      border-radius: 12px;
      padding: .45rem .7rem;
      display: flex;
      align-items: center;
      gap: .55rem;
      box-shadow: var(--shadow);
      font-weight: 700;
      z-index: 20;
    }

    .voice-pill .dot {
      width: 10px;
      height: 10px;
      border-radius: 999px;
      background: var(--red);
    }

    .voice-pill .close {
      background: transparent;
      border: 0;
      color: #fff;
      opacity: .8;
      cursor: pointer;
      font-size: 16px;
      line-height: 1;
    }

    @media (max-width: 640px) {
      .voice-pill {
        position: fixed;
        top: 70px;
        right: 12px;
      }
    }

    .wrap {
      max-width: 1200px;
      margin: 18px auto;
      padding: 0 16px;
    }

    .card {
      background: var(--card-bg);
      border: 1px solid var(--border);
      border-radius: 14px;
      box-shadow: var(--shadow);
    }

    .card h3 {
      margin: 0;
      font-size: 1.05rem;
    }

    .card .hd {
      padding: 14px 16px;
      border-bottom: 1px solid var(--border);
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
    }

    .card .bd {
      padding: 16px;
    }

    .table {
      width: 100%;
      border-collapse: collapse;
    }

    .table th,
    .table td {
      padding: .7rem .6rem;
      border-bottom: 1px solid var(--border);
      text-align: left;
      vertical-align: top;
    }

    .table thead th {
      font-size: .85rem;
      color: #334155;
      background: #f8fafc;
    }

    .muted {
      color: var(--muted);
    }

    .small {
      font-size: .92rem;
      color: #334155;
    }

    .badge {
      display: inline-block;
      padding: .2rem .55rem;
      border-radius: .6rem;
      font-weight: 700;
      font-size: .78rem;
    }

    .b-blue {
      background: var(--blue-badge);
      color: var(--blue-badge-text);
    }

    .b-gray {
      background: var(--gray-badge);
      color: var(--gray-badge-text);
    }

    .b-green {
      background: #d1fae5;
      color: #065f46;
    }

    .b-red {
      background: #fee2e2;
      color: #991b1b;
    }

    @keyframes flashRow {
      0% {
        background: var(--flash);
      }

      100% {
        background: transparent;
      }
    }

    tr.flash-once {
      animation: flashRow 1.2s ease-out 1;
    }

    .modal {
      position: fixed;
      inset: 0;
      display: none;
      z-index: 40;
    }

    .modal.open {
      display: block;
    }

    .modal .overlay {
      position: absolute;
      inset: 0;
      background: rgba(15, 23, 42, .45);
      backdrop-filter: blur(2px);
    }

    .modal .card {
      position: relative;
      z-index: 41;
      max-width: 960px;
      margin: 5vh auto;
      background: var(--card-bg);
      border: 1px solid var(--border);
      border-radius: 16px;
      box-shadow: var(--shadow);
    }

    .modal .hd {
      padding: 16px 18px;
      border-bottom: 1px solid var(--border);
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .modal .bd {
      padding: 16px 18px;
      max-height: 70vh;
      overflow: auto;
    }

    .modal .close {
      background: transparent;
      border: 0;
      font-size: 22px;
      cursor: pointer;
      color: #0f172a;
      line-height: 1;
    }

    .form-row {
      display: grid;
      grid-template-columns: 2fr 1fr;
      gap: 12px;
    }

    .form-row2 {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 12px;
      margin-top: 12px;
    }

    @media (max-width: 640px) {

      .form-row,
      .form-row2 {
        grid-template-columns: 1fr;
      }
    }

    label {
      font-weight: 700;
      font-size: .9rem;
      color: #1f2937;
      display: block;
      margin-bottom: 6px;
    }

    input,
    select,
    textarea {
      width: 100%;
      border: 2px solid var(--border);
      border-radius: 10px;
      padding: .6rem .75rem;
      font-size: 1rem;
      outline: none;
      transition: border .15s ease, box-shadow .15s ease;
    }

    textarea {
      min-height: 120px;
    }

    input:focus,
    select:focus,
    textarea:focus {
      border-color: var(--brand);
      box-shadow: 0 0 0 3px rgba(59, 130, 246, .12);
    }

    .actionsRow {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
    }

    .avatar {
      width: 44px;
      height: 44px;
      border-radius: 999px;
      object-fit: cover;
      background: #e5e7eb
    }

    .toast {
      position: fixed;
      right: 16px;
      bottom: 16px;
      background: #111827;
      color: #fff;
      padding: .7rem .9rem;
      border-radius: 10px;
      box-shadow: var(--shadow);
      opacity: 0;
      transform: translateY(8px);
      pointer-events: none;
    }

    .toast.show {
      opacity: 1;
      transform: translateY(0);
      transition: all .25s ease;
    }

    @media (max-width: 820px) {
      .header-inner {
        gap: 8px
      }

      .actions {
        width: 100%;
        justify-content: flex-start
      }

      .btn {
        padding: .5rem .75rem
      }

      .table thead {
        display: none
      }

      .table,
      .table tbody,
      .table tr,
      .table td {
        display: block;
        width: 100%
      }

      .table tr {
        border-bottom: 1px solid var(--border);
        padding: .6rem .6rem
      }

      .table td {
        border: 0;
        padding: .45rem 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 10px
      }

      .table td::before {
        content: attr(data-label);
        font-weight: 800;
        color: #475569;
        margin-right: 10px;
        text-align: left;
      }

      .actionsRow .btn {
        width: 100%;
        justify-content: center
      }
    }
  </style>
</head>

<body>

  <header class="header">
    <div class="header-inner">
      <div class="brand">
        <a class="btn btn-secondary" href="/arapiraca/admin.php"><i class="fa fa-arrow-left"></i> Voltar</a>
        <div class="title">Matérias da Sessão #<?= (int)$sessao_id ?></div>
      </div>

      <div class="actions" id="actionsBar">
        <a class="btn btn-primary" id="openNovaMateria"><i class="fa fa-file-circle-plus"></i> Nova</a>

        <a href="/arapiraca/admin_configuracoes.php"
          class="btn btn-outline-primary btn-pill d-inline-flex align-items-center gap-2">
          <i class="fa fa-gear"></i>
          <span>Configurações</span>
        </a>

        <a class="btn btn-outline-primary" id="btnVoz" style="position:relative">
          <i class="fa fa-microphone"></i> Pedidos de Voz
          <span id="badgeVoz" class="notif" hidden>0</span>
        </a>
        <!-- NOVO BOTÃO: RELATÓRIO PÚBLICO DA SESSÃO -->
        <a href="/arapiraca/relatorio_publico.php?sessao=<?= (int)$sessao_id ?>"
          class="btn btn-outline-primary d-inline-flex align-items-center gap-2"
          target="_blank" rel="noopener">
          <i class="fa fa-globe"></i>
          <span>Relatório público</span>
        </a>
        <!-- FIM NOVO BOTÃO -->

        <a class="btn btn-danger" href="/arapiraca/actions.php?op=encerrar_sessao&sessao_id=<?= (int)$sessao_id ?>"><i class="fa fa-stop"></i> Encerrar</a>
      </div>
    </div>
  </header>

  <div class="wrap">
    <?php if ($msg): ?>
      <div class="toast show" id="toast"><i class="fa fa-check-circle"></i> <?= h($msg) ?></div>
    <?php elseif ($err): ?>
      <div class="toast show" id="toast"><i class="fa fa-triangle-exclamation"></i> <?= h($err) ?></div>
    <?php endif; ?>

    <?php if ($new_sm_id): ?>
      <div id="created" data-smid="<?= (int)$new_sm_id ?>" hidden></div>
    <?php endif; ?>

    <div class="card" style="margin-top:12px">
      <div class="hd">
        <h3><i class="fa fa-list-check"></i> Matérias da sessão</h3>
      </div>
      <div class="bd" style="padding:0">
        <table class="table" id="tblMaterias">
          <thead>
            <tr>
              <th>#</th>
              <th>Título</th>
              <th>Propositor</th>
              <th>Status</th>

              <th style="width:520px">Ações</th>
            </tr>
          </thead>
          <tbody>
            <?php if (!$lista): ?>
              <tr>
                <td colspan="6" class="muted" style="padding:16px">Nenhuma matéria cadastrada.</td>
              </tr>
              <?php else: foreach ($lista as $r): ?>
                <?php
                $pub           = isset($r['publicar_site']) ? (int)$r['publicar_site'] : 1;
                $status        = $r['status'];               // aguardando|inativa|votacao_aberta|finalizada
                $hasResult     = !empty($r['resultado']);    // aprov/rejeit => votação encerrou
                $isOpen        = ($status === 'votacao_aberta');
                $isInactive    = ($status === 'inativa');
                $somenteLeitura = !empty($r['somente_leitura']);

                $canStart        = (!$isOpen && !$hasResult);
                $canToggleActive = (!$isOpen && !$hasResult);
                ?>
                <tr
                  id="row-sm-<?= (int)$r['sm_id'] ?>"
                  data-smid="<?= (int)$r['sm_id'] ?>"
                  data-materia-id="<?= (int)$r['materia_id'] ?>"
                  data-numero="<?= h($r['numero']) ?>"
                  data-ano="<?= h($r['ano']) ?>"
                  data-tipo="<?= h($r['tipo_materia']) ?>"
                  data-titulo="<?= h($r['titulo']) ?>"
                  data-descricao="<?= h($r['descricao']) ?>"
                  data-autor-id="<?= (int)$r['autor_id'] ?>">
                  <td data-label="#"><?= h($r['ordem']) ?></td>
                  <td data-label="Título" class="small"><?= h($r['titulo']) ?></td>
                  <td data-label="Propositor" class="small">
                    <?php if ($r['autor_nome']): ?>
                      <?= h($r['autor_nome']) ?><?= $r['autor_partido'] ? ' — ' . h($r['autor_partido']) : '' ?>
                      <?php if ($r['autor_tipo'] && $r['autor_tipo'] !== 'vereador'): ?>
                        <span class="badge b-gray" title="Proponente"><?= h($r['autor_tipo']) ?></span>
                      <?php endif; ?>
                    <?php else: ?>
                      <span class="muted">—</span>
                    <?php endif; ?>
                  </td>
                  <td data-label="Status">
                    <span class="badge b-gray"><?= h($r['status']) ?></span>

                    <?php if ($somenteLeitura): ?>
                      <span class="badge b-blue" title="Esta matéria será apenas lida, sem abrir votação automática.">Só leitura</span>
                    <?php else: ?>
                      <span class="badge b-green" title="Matéria disponível para leitura e votação.">Leitura + votação</span>
                    <?php endif; ?>

                    <?php if ($r['resultado']): ?>
                      <span class="badge <?= $r['resultado'] === 'aprovada' ? 'b-green' : 'b-red' ?>"><?= h($r['resultado']) ?></span>
                    <?php endif; ?>

                    <?php if ($hasResult): ?>
                      <?php if ($pub): ?>
                        <span class="badge b-green">Publicado</span>
                      <?php else: ?>
                        <span class="badge b-red">Não publicado</span>
                      <?php endif; ?>
                    <?php endif; ?>
                  </td>

                  <td data-label="Ações">
                    <div class="actionsRow">
                      <button class="btn btn-outline-primary small btn-edit" type="button" data-row="<?= (int)$r['sm_id'] ?>">
                        <i class="fa fa-pen"></i> Editar
                      </button>

                      <!-- Alternar modo: Somente leitura / Leitura + votação -->
                      <a class="btn small keep-pos <?= $somenteLeitura ? 'btn-warning' : 'btn-secondary' ?>"
                        data-row="<?= (int)$r['sm_id'] ?>"
                        href="/arapiraca/admin_materia_nova.php?sessao=<?= (int)$sessao_id ?>&op=toggle_leitura&sm_id=<?= (int)$r['sm_id'] ?>"
                        title="Define se esta matéria será apenas lida ou se poderá ir para votação">
                        <i class="fa fa-book"></i>
                        <?= $somenteLeitura ? 'Somente leitura' : 'Leitura/votação' ?>
                      </a>

                      <?php if ($canToggleActive): ?>
                        <?php if ($isInactive): ?>
                          <a class="btn btn-warning small keep-pos"
                            data-row="<?= (int)$r['sm_id'] ?>"
                            href="/arapiraca/actions.php?op=materia_marcar_ativa&id=<?= (int)$r['sm_id'] ?>&sessao_id=<?= (int)$sessao_id ?>">
                            <i class="fa fa-toggle-on"></i> ON
                          </a>
                        <?php else: ?>
                          <a class="btn btn-warning small keep-pos"
                            data-row="<?= (int)$r['sm_id'] ?>"
                            href="/arapiraca/actions.php?op=materia_marcar_inativa&id=<?= (int)$r['sm_id'] ?>&sessao_id=<?= (int)$sessao_id ?>">
                            <i class="fa fa-toggle-off"></i> OFF
                          </a>
                        <?php endif; ?>
                      <?php endif; ?>

                      <!-- Leitura (toggle) -->
                      <a class="btn btn-outline-primary small keep-pos btn-reading"
                        data-row="<?= (int)$r['sm_id'] ?>"
                        href="/arapiraca/actions.php?op=leitura_toggle&id=<?= (int)$r['sm_id'] ?>&sessao_id=<?= (int)$sessao_id ?>"
                        title="Enviar esta matéria para leitura no painel público (clique novamente para parar)">
                        <i class="fa fa-book-open-reader"></i> <span>Ler</span>
                      </a>

                      <?php if ($canStart && !$somenteLeitura): ?>
                        <a class="btn btn-success small keep-pos"
                          data-row="<?= (int)$r['sm_id'] ?>"
                          href="/arapiraca/actions.php?op=iniciar_votacao&id=<?= (int)$r['sm_id'] ?>&sessao_id=<?= (int)$sessao_id ?>">
                          <i class="fa fa-play"></i> votar
                        </a>
                      <?php elseif ($isOpen): ?>
                        <a class="btn btn-danger small keep-pos"
                          data-row="<?= (int)$r['sm_id'] ?>"
                          href="/arapiraca/actions.php?op=encerrar_votacao&id=<?= (int)$r['sm_id'] ?>&sessao_id=<?= (int)$sessao_id ?>">
                          <i class="fa fa-square"></i> Encerrar
                        </a>
                      <?php endif; ?>

                      <?php if ($hasResult): ?>
                        <?php if ($pub): ?>
                          <a class="btn btn-warning small keep-pos"
                            data-row="<?= (int)$r['sm_id'] ?>"
                            href="/arapiraca/actions.php?op=sm_toggle_publicar&id=<?= (int)$r['sm_id'] ?>&to=0&sessao_id=<?= (int)$sessao_id ?>">
                            <i class="fa fa-eye-slash"></i> Não publicar
                          </a>
                        <?php else: ?>
                          <a class="btn btn-warning small keep-pos"
                            data-row="<?= (int)$r['sm_id'] ?>"
                            href="/arapiraca/actions.php?op=sm_toggle_publicar&id=<?= (int)$r['sm_id'] ?>&to=1&sessao_id=<?= (int)$sessao_id ?>">
                            <i class="fa fa-eye"></i> Publicar
                          </a>
                        <?php endif; ?>
                      <?php endif; ?>


                    </div>
                  </td>
                </tr>
            <?php endforeach;
            endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- MODAL NOVA MATÉRIA -->
  <div class="modal" id="modalNovaMateria" aria-hidden="true" role="dialog" aria-modal="true">
    <div class="overlay" data-close></div>
    <div class="card" role="document" aria-labelledby="modalTitleMateria">
      <div class="hd">
        <h3 id="modalTitleMateria"><i class="fa fa-file-circle-plus"></i> Nova matéria</h3>
        <button class="close" type="button" aria-label="Fechar" data-close>&times;</button>
      </div>
      <div class="bd">
        <form method="post" id="formNovaMateria">
          <input type="hidden" name="op" value="criar">
          <div class="form-row">
            <div>
              <label>Título</label>
              <input name="titulo" required value="<?= h($titulo_form) ?>">
            </div>
            <div>
              <label>Tipo</label>
              <select name="tipo">
                <?php foreach ($tipos_pre as $t): ?>
                  <option value="<?= h($t) ?>" <?= $t === $tipo_form ? 'selected' : '' ?>><?= h($t) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          <div class="form-row2">
            <div>
              <label>Número</label>
              <input name="numero" value="<?= h($numero_form) ?>">
            </div>
            <div>
              <label>Ano</label>
              <input type="number" name="ano" value="<?= h($ano_form) ?>">
            </div>
            <div>
              <label>Propositor (Vereador/Proponente)</label>
              <select name="autor_id" required>
                <option value="">— selecione —</option>
                <?php foreach ($vereadores as $v): ?>
                  <option value="<?= (int)$v['id'] ?>" <?= ((int)$v['id'] === $autor_id_form) ? 'selected' : '' ?>>
                    <?= h($v['nome']) ?><?= $v['partido'] ? ' — ' . h($v['partido']) : '' ?><?= $v['tipo_usuario'] !== 'vereador' ? ' — proponente' : '' ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          <label>Descrição</label>
          <textarea name="descricao" placeholder="Resumo/ementa..."><?= h($desc_form) ?></textarea>
          <div style="margin-top:14px; display:flex; gap:8px; justify-content:flex-end; flex-wrap:wrap">
            <button class="btn btn-secondary" type="button" data-close><i class="fa fa-xmark"></i> Cancelar</button>
            <button class="btn btn-primary" type="submit"><i class="fa fa-save"></i> Adicionar</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- MODAL EDITAR MATÉRIA -->
  <div class="modal" id="modalEditMateria" aria-hidden="true" role="dialog" aria-modal="true">
    <div class="overlay" data-close></div>
    <div class="card" role="document" aria-labelledby="modalTitleMateriaEdit">
      <div class="hd">
        <h3 id="modalTitleMateriaEdit"><i class="fa fa-pen-to-square"></i> Editar matéria</h3>
        <button class="close" type="button" aria-label="Fechar" data-close>&times;</button>
      </div>
      <div class="bd">
        <form method="post" id="formEditMateria" action="/arapiraca/actions.php?op=materia_editar&sessao_id=<?= (int)$sessao_id ?>">
          <input type="hidden" name="materia_id" id="edit_materia_id">
          <input type="hidden" name="sm_id" id="edit_sm_id">
          <div class="form-row">
            <div>
              <label>Título</label>
              <input name="titulo" id="edit_titulo" required>
            </div>
            <div>
              <label>Tipo</label>
              <select name="tipo" id="edit_tipo">
                <?php foreach ($tipos_pre as $t): ?>
                  <option value="<?= h($t) ?>"><?= h($t) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          <div class="form-row2">
            <div>
              <label>Número</label>
              <input name="numero" id="edit_numero">
            </div>
            <div>
              <label>Ano</label>
              <input type="number" name="ano" id="edit_ano">
            </div>
            <div>
              <label>Propositor (Vereador/Proponente)</label>
              <select name="autor_id" id="edit_autor_id" required>
                <?php foreach ($vereadores as $v): ?>
                  <option value="<?= (int)$v['id'] ?>">
                    <?= h($v['nome']) ?><?= $v['partido'] ? ' — ' . h($v['partido']) : '' ?><?= $v['tipo_usuario'] !== 'vereador' ? ' — proponente' : '' ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          <label>Descrição</label>
          <textarea name="descricao" id="edit_descricao" placeholder="Resumo/ementa..."></textarea>
          <div style="margin-top:14px; display:flex; gap:8px; justify-content:flex-end; flex-wrap:wrap">
            <button class="btn btn-secondary" type="button" data-close><i class="fa fa-xmark"></i> Cancelar</button>
            <button class="btn btn-primary" type="submit"><i class="fa fa-save"></i> Salvar alterações</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- MODAL PEDIDOS DE VOZ -->
  <div class="modal" id="modalVoz" aria-hidden="true" role="dialog" aria-modal="true">
    <div class="overlay" data-close></div>
    <div class="card" role="document" aria-labelledby="modalTitleVoz">
      <div class="hd">
        <h3 id="modalTitleVoz"><i class="fa fa-microphone-lines"></i> Pedidos de Voz</h3>
        <button class="close" type="button" aria-label="Fechar" data-close>&times;</button>
      </div>
      <div class="bd">
        <div class="row-voz">
          <div class="col">
            <h4>Em andamento</h4>
            <div class="body" id="voz_em_andamento">
              <?php if ($voz_andamento): ?>
                <div class="item">
                  <img class="avatar" src="<?= h($voz_andamento['foto'] ? ('/arapiraca/' . ltrim($voz_andamento['foto'], '/')) : '/arapiraca/assets/avatar.png') ?>" onerror="this.src='/arapiraca/assets/avatar.png'" alt="Avatar">
                  <div>
                    <div>
                      <strong><?= h($voz_andamento['nome']) ?></strong>
                      <span class="badge b-blue"><?= (int)$voz_andamento['tempo_solicitado'] ?> min</span>
                    </div>
                    <div class="muted small">Início: <?= h($voz_andamento['tempo_inicio']) ?></div>
                  </div>
                  <div class="actionsRow">
                    <a class="btn btn-danger small keep-pos" data-row="<?= (int)$voz_andamento['id'] ?>" href="/arapiraca/actions.php?op=encerrar_fala&id=<?= $voz_andamento['id'] ?>&sessao_id=<?= $sessao_id ?>"><i class="fa fa-stop"></i> Encerrar</a>
                    <a class="btn btn-secondary small keep-pos" data-row="<?= (int)$voz_andamento['id'] ?>" href="/arapiraca/actions.php?op=prorrogar_fala&sessao_id=<?= $sessao_id ?>&delta=1"><i class="fa fa-plus"></i> +1 min</a>
                    <a class="btn btn-secondary small keep-pos" data-row="<?= (int)$voz_andamento['id'] ?>" href="/arapiraca/actions.php?op=cancelar_fala&id=<?= $voz_andamento['id'] ?>&sessao_id=<?= $sessao_id ?>"><i class="fa fa-ban"></i> Cancelar</a>
                  </div>
                </div>
              <?php else: ?>
                <p class="muted">Nenhuma fala em andamento.</p>
              <?php endif; ?>
            </div>
          </div>

          <div class="col">
            <h4>Fila (pendentes)</h4>
            <div class="body" id="voz_pendentes">
              <?php if ($voz_pendentes): foreach ($voz_pendentes as $p): ?>
                  <div class="item">
                    <img class="avatar" src="<?= h($p['foto'] ? ('/arapiraca/' . ltrim($p['foto'], '/')) : '/arapiraca/assets/avatar.png') ?>" onerror="this.src='/arapiraca/assets/avatar.png'" alt="Avatar">
                    <div>
                      <div>
                        <strong><?= h($p['nome']) ?></strong>
                        <span class="badge b-blue"><?= (int)$p['tempo_solicitado'] ?> min</span>
                      </div>
                      <?php if ($p['observacoes']): ?>
                        <div class="small muted"><?= h($p['observacoes']) ?></div>
                      <?php endif; ?>
                    </div>
                    <div class="actionsRow">
                      <form class="inline" method="post" action="/arapiraca/actions.php?autorizar_fala&sessao_id=<?= $sessao_id ?>">
                        <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                        <input type="number" name="min" min="1" max="60" value="<?= (int)$p['tempo_solicitado'] ?>" title="Minutos">
                        <button class="btn btn-primary small" type="submit"><i class="fa fa-check"></i> Autorizar</button>
                      </form>
                      <a class="btn btn-secondary small keep-pos" data-row="<?= (int)$p['id'] ?>" href="/arapiraca/actions.php?op=cancelar_fala&id=<?= $p['id'] ?>&sessao_id=<?= $sessao_id ?>"><i class="fa fa-ban"></i> Cancelar</a>
                    </div>
                  </div>
                <?php endforeach;
              else: ?>
                <p class="muted">Sem pedidos pendentes.</p>
              <?php endif; ?>
            </div>
          </div>

          <div class="col">
            <h4>Histórico</h4>
            <div class="body" id="voz_historico">
              <?php if ($voz_historico): foreach ($voz_historico as $h): ?>
                  <div class="item">
                    <div>
                      <div>
                        <strong><?= h($h['nome']) ?></strong>
                        <?= $h['status'] === 'finalizada'
                          ? '<span class="badge b-green">Finalizada</span>'
                          : '<span class="badge b-gray">Cancelada</span>' ?>
                      </div>
                      <div class="small muted">
                        Solicitado: <?= (int)$h['tempo_solicitado'] ?> min
                        <?php if ($h['tempo_inicio']): ?> — Início: <?= h($h['tempo_inicio']) ?><?php endif; ?>
                          <?php if ($h['tempo_fim']): ?> — Fim: <?= h($h['tempo_fim']) ?><?php endif; ?>
                      </div>
                    </div>
                  </div>
                <?php endforeach;
              else: ?>
                <p class="muted">Sem histórico.</p>
              <?php endif; ?>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script>
    // ===== toast auto-hide
    const toast = document.getElementById('toast');
    if (toast) {
      setTimeout(() => toast.classList.remove('show'), 2500);
    }

    // ===== helpers de modal
    function wireModal(modalEl, opener) {
      const closeEls = modalEl.querySelectorAll('[data-close], .overlay');

      function open() {
        modalEl.classList.add('open');
        modalEl.setAttribute('aria-hidden', 'false');
        document.body.style.overflow = 'hidden';
      }

      function close() {
        modalEl.classList.remove('open');
        modalEl.setAttribute('aria-hidden', 'true');
        document.body.style.overflow = '';
      }
      opener?.addEventListener('click', open);
      closeEls.forEach(el => el.addEventListener('click', close));
      document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && modalEl.classList.contains('open')) close();
      });
      return {
        open,
        close
      };
    }

    const modalMateria = wireModal(document.getElementById('modalNovaMateria'), document.getElementById('openNovaMateria'));
    <?php if ($err): ?> modalMateria.open();
    <?php endif; ?>

    const editModal = wireModal(document.getElementById('modalEditMateria'));
    document.querySelectorAll('.btn-edit').forEach(btn => {
      btn.addEventListener('click', e => {
        const tr = e.currentTarget.closest('tr');
        if (!tr) return;
        document.getElementById('edit_sm_id').value = tr.dataset.smid || '';
        document.getElementById('edit_materia_id').value = tr.dataset.materiaId || '';
        document.getElementById('edit_titulo').value = tr.dataset.titulo || '';
        document.getElementById('edit_numero').value = tr.dataset.numero || '';
        document.getElementById('edit_ano').value = tr.dataset.ano || '';
        document.getElementById('edit_descricao').value = tr.dataset.descricao || '';

        const tipoSel = document.getElementById('edit_tipo');
        [...tipoSel.options].forEach(o => o.selected = (o.value === (tr.dataset.tipo || '')));

        const autorSel = document.getElementById('edit_autor_id');
        [...autorSel.options].forEach(o => o.selected = (o.value === (tr.dataset.autorId || '')));

        editModal.open();
      });
    });

    const vozModal = wireModal(document.getElementById('modalVoz'), document.getElementById('btnVoz'));

    /* =================== PRESERVAR POSIÇÃO E LINHA =================== */
    const KEY_SCROLL = 'materias_scrollY';
    const KEY_ANCHOR = 'materias_anchor_sm';
    const tbl = document.getElementById('tblMaterias');

    function savePosition(smId) {
      try {
        sessionStorage.setItem(KEY_SCROLL, String(window.scrollY || 0));
        if (smId) sessionStorage.setItem(KEY_ANCHOR, String(smId));
      } catch (_) {}
    }

    function restorePosition() {
      try {
        const y = parseInt(sessionStorage.getItem(KEY_SCROLL) || '0', 10);
        const anchor = sessionStorage.getItem(KEY_ANCHOR) || '';
        if (y > 0) window.scrollTo({
          top: y,
          behavior: 'instant'
        });

        if (anchor) {
          const row = document.getElementById('row-sm-' + anchor);
          if (row) {
            row.scrollIntoView({
              block: 'center',
              behavior: 'smooth'
            });
            row.classList.add('flash-once');
            setTimeout(() => row.classList.remove('flash-once'), 1400);
          }
        }
        sessionStorage.removeItem(KEY_SCROLL);
        sessionStorage.removeItem(KEY_ANCHOR);
      } catch (_) {}
    }

    document.querySelectorAll('a.keep-pos').forEach(a => {
      a.addEventListener('click', (ev) => {
        const sm = ev.currentTarget.getAttribute('data-row') || '';
        savePosition(sm);
      });
    });

    document.querySelectorAll('form').forEach(f => {
      f.addEventListener('submit', () => {
        const sm = (f.querySelector('[name="sm_id"]')?.value) || '';
        savePosition(sm);
      });
    });

    (function() {
      const created = document.getElementById('created');
      if (created) {
        const sm = created.dataset.smid || '';
        if (sm) {
          try {
            sessionStorage.setItem(KEY_ANCHOR, String(sm));
          } catch (_) {}
        }
      }
      restorePosition();
    })();

    /* =================== VOZ polling =================== */
    const SESSAO_ID = <?= (int)$sessao_id ?>;

    function esc(s) {
      return String(s ?? '').replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
    }

    function htmlAndamento(a) {
      if (!a) return '<p class="muted">Nenhuma fala em andamento.</p>';
      const foto = a.foto || '/arapiraca/assets/avatar.png';
      const inicioStr = a.started_at ? new Date(a.started_at * 1000).toLocaleString('pt-BR') : esc(a.tempo_inicio || '');
      return `
        <div class="item">
          <img class="avatar" src="${foto}" onerror="this.src='/arapiraca/assets/avatar.png'" alt="Avatar">
          <div>
            <div><strong>${esc(a.nome)}</strong> <span class="badge b-blue">${a.tempo_solicitado|0} min</span></div>
            <div class="small muted">Início: ${inicioStr}</div>
          </div>
          <div class="actionsRow">
            <a class="btn btn-danger small keep-pos" data-row="${a.id}" href="/arapiraca/actions.php?op=encerrar_fala&id=${a.id}&sessao_id=${SESSAO_ID}"><i class="fa fa-stop"></i> Encerrar</a>
            <a class="btn btn-secondary small keep-pos" data-row="${a.id}" href="/arapiraca/actions.php?op=prorrogar_fala&sessao_id=${SESSAO_ID}&delta=1"><i class="fa fa-plus"></i> +1 min</a>
            <a class="btn btn-secondary small keep-pos" data-row="${a.id}" href="/arapiraca/actions.php?op=cancelar_fala&id=${a.id}&sessao_id=${SESSAO_ID}"><i class="fa fa-ban"></i> Cancelar</a>
          </div>
        </div>`;
    }

    function htmlPendente(p) {
      const foto = p.foto || '/arapiraca/assets/avatar.png';
      const obs = p.observacoes ? `<div class="small muted">${esc(p.observacoes)}</div>` : '';
      return `
        <div class="item">
          <img class="avatar" src="${foto}" onerror="this.src='/arapiraca/assets/avatar.png'" alt="Avatar">
          <div>
            <div><strong>${esc(p.nome)}</strong> <span class="badge b-blue">${p.tempo_solicitado|0} min</span></div>
            ${obs}
          </div>
          <div class="actionsRow">
            <form class="inline" method="post" action="/arapiraca/actions.php?autorizar_fala&sessao_id=${SESSAO_ID}">
              <input type="hidden" name="id" value="${p.id}">
              <input type="number" name="min" min="1" max="60" value="${p.tempo_solicitado|0}" title="Minutos">
              <button class="btn btn-primary small" type="submit"><i class="fa fa-check"></i> Autorizar</button>
            </form>
            <a class="btn btn-secondary small keep-pos" data-row="${p.id}" href="/arapiraca/actions.php?op=cancelar_fala&id=${p.id}&sessao_id=${SESSAO_ID}"><i class="fa fa-ban"></i> Cancelar</a>
          </div>
        </div>`;
    }

    function htmlHistorico(h) {
      const badge = h.status === 'finalizada' ?
        '<span class="badge b-green">Finalizada</span>' :
        '<span class="badge b-gray">Cancelada</span>';
      const i = h.tempo_inicio ? ` — Início: ${esc(h.tempo_inicio)}` : '';
      const f = h.tempo_fim ? ` — Fim: ${esc(h.tempo_fim)}` : '';
      return `
        <div class="item">
          <div>
            <div><strong>${esc(h.nome)}</strong> ${badge}</div>
            <div class="small muted">Solicitado: ${h.tempo_solicitado|0} min${i}${f}</div>
          </div>
        </div>`;
    }

    let lastPendIds = new Set();

    function showVoicePill(count) {
      hideVoicePill();
      const bar = document.getElementById('actionsBar');
      const pill = document.createElement('div');
      pill.className = 'voice-pill';
      pill.id = 'voicePill';
      pill.innerHTML = `<span class="dot"></span><span>${count} pedido${count>1?'s':''} de voz na fila</span><button class="close" aria-label="Fechar">&times;</button>`;
      pill.querySelector('.close').addEventListener('click', hideVoicePill);
      bar.appendChild(pill);
    }

    function hideVoicePill() {
      document.getElementById('voicePill')?.remove();
    }

    document.getElementById('btnVoz')?.addEventListener('click', hideVoicePill);

    function updateBadge(pendentes) {
      const badge = document.getElementById('badgeVoz');
      const count = (pendentes && pendentes.length) ? pendentes.length : 0;

      if (count > 0) {
        badge.hidden = false;
        badge.textContent = count;
        const nowIds = new Set(pendentes.map(p => p.id));
        let hasNew = false;
        nowIds.forEach(id => {
          if (!lastPendIds.has(id)) hasNew = true;
        });
        if (hasNew) {
          badge.classList.add('pulse');
          setTimeout(() => badge.classList.remove('pulse'), 1500);
          showVoicePill(count);
        }
        lastPendIds = nowIds;
      } else {
        badge.hidden = true;
        lastPendIds = new Set();
        hideVoicePill();
      }
    }

    function renderVoz(payload) {
      if (!payload || payload.ok === false) {
        return;
      }

      updateBadge(payload.pendentes || []);

      const editingMin = document.querySelector('#modalVoz input[name="min"]:focus');
      if (editingMin) {
        return;
      }

      const elAnd = document.getElementById('voz_em_andamento');
      const elPend = document.getElementById('voz_pendentes');
      const elHist = document.getElementById('voz_historico');

      if (elAnd) elAnd.innerHTML = htmlAndamento(payload.andamento);

      if (elPend) {
        elPend.innerHTML = (payload.pendentes && payload.pendentes.length) ?
          payload.pendentes.map(htmlPendente).join('') :
          '<p class="muted">Sem pedidos pendentes.</p>';
      }

      if (elHist) {
        elHist.innerHTML = (payload.historico && payload.historico.length) ?
          payload.historico.map(htmlHistorico).join('') :
          '<p class="muted">Sem histórico.</p>';
      }
    }

    async function tickVoz() {
      try {
        const url = new URL('/arapiraca/actions.php', location.origin);
        url.searchParams.set('op', 'voz_status');
        url.searchParams.set('sessao_id', String(SESSAO_ID));
        const r = await fetch(url, {
          cache: 'no-store'
        });
        const data = await r.json();
        renderVoz(data);
      } catch (e) {
        console.error(e);
      }
    }

    tickVoz();
    setInterval(tickVoz, 2000);
    document.addEventListener('visibilitychange', () => {
      if (!document.hidden) tickVoz();
    });

    /* =================== LEITURA: UI ON/OFF + bloqueio em votação =================== */
    function setReadingUI(activeSmId) {
      document.querySelectorAll('.btn-reading').forEach(btn => {
        const sm = parseInt(btn.getAttribute('data-row') || '0', 10);
        const isOn = !!activeSmId && sm === parseInt(activeSmId, 10);

        btn.classList.remove('btn-primary', 'btn-outline-primary', 'btn-success');
        const span = btn.querySelector('span');
        if (span) span.textContent = '';

        if (isOn) {
          btn.classList.add('btn-primary');
          btn.title = 'Leitura ligada (clique para parar)';
          btn.setAttribute('aria-pressed', 'true');
          if (span) span.appendChild(document.createTextNode('Leitura ON'));
        } else {
          btn.classList.add('btn-outline-primary');
          btn.title = 'Enviar esta matéria para leitura no painel público (clique novamente para parar)';
          btn.setAttribute('aria-pressed', 'false');
          if (span) span.appendChild(document.createTextNode('Ler'));
        }
      });
    }

    function setReadingDisabled(disabled) {
      document.querySelectorAll('.btn-reading').forEach(btn => {
        if (disabled) {
          btn.setAttribute('aria-disabled', 'true');
          btn.style.pointerEvents = 'none';
          btn.style.opacity = '0.6';
          btn.title = 'Votação em andamento — Leitura temporariamente indisponível';
        } else {
          btn.removeAttribute('aria-disabled');
          btn.style.pointerEvents = '';
          btn.style.opacity = '';
          btn.title = btn.getAttribute('aria-pressed') === 'true' ?
            'Leitura ligada (clique para parar)' :
            'Enviar esta matéria para leitura no painel público (clique novamente para parar)';
        }
      });
    }

    async function tickLeitura() {
      try {
        const url = new URL('/arapiraca/actions.php', location.origin);
        url.searchParams.set('op', 'status');
        url.searchParams.set('sessao_id', String(SESSAO_ID));
        const r = await fetch(url, {
          cache: 'no-store'
        });
        const data = await r.json();

        const leitura = data?.leitura || null;
        setReadingUI(leitura?.sm_id || 0);

        const m = data?.materia || null;
        const votacaoAberta = !!(m && (
          m.status === 'votacao_aberta' ||
          m.modo === 'votacao' ||
          m.etapa === 'votacao' ||
          m.votacao_aberta === true
        ));
        setReadingDisabled(votacaoAberta);
      } catch (e) {
        console.error(e);
      }
    }

    tickLeitura();
    setInterval(tickLeitura, 2000);
    document.addEventListener('visibilitychange', () => {
      if (!document.hidden) tickLeitura();
    });
  </script>

</body>

</html>