<?php
require_once __DIR__ . '/../../config/app.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/flash.php';
requireRol(ROL_COORDINADOR);

$user      = currentUser();
$db        = getDB();
$pageTitle = 'Bitácoras — Coordinador';
$idInst    = (int)($user['id_instituto'] ?? 0);

// ── Filtros ─────────────────────────────────────────────────
$filtroEst  = $_GET['estado']   ?? 'todas';
$q          = trim($_GET['q']   ?? '');
$idCarrera  = (int)($_GET['carrera'] ?? 0);
$idPeriodo  = (int)($_GET['periodo'] ?? 0);

$estados_validos = ['borrador','enviada','validada','observada','todas'];
if (!in_array($filtroEst, $estados_validos)) $filtroEst = 'todas';

// ── Construir WHERE ─────────────────────────────────────────
$where  = ['1=1']; $params = [];
if ($filtroEst !== 'todas') {
    $where[] = 'b.estado = :est'; $params[':est'] = $filtroEst;
}
if ($q) {
    $where[] = "(CONCAT(u.nombres,' ',u.apellidos) LIKE :q OR em.razon_social LIKE :q)";
    $params[':q'] = '%'.$q.'%';
}
if ($idCarrera) { $where[] = 'car.id_carrera = :car'; $params[':car'] = $idCarrera; }
if ($idPeriodo) { $where[] = 'pr.id_periodo  = :per'; $params[':per'] = $idPeriodo; }
if ($idInst) { $where[] = 'car.id_instituto = :inst'; $params[':inst'] = $idInst; }
$wStr = implode(' AND ', $where);

// ── Cargar bitácoras ────────────────────────────────────────
$stBit = $db->prepare("
    SELECT b.*,
           CONCAT(u.nombres,' ',u.apellidos)  AS estudiante,
           u.cedula,
           car.nombre                          AS carrera,
           em.razon_social                     AS empresa,
           pe.nombre                           AS periodo,
           CONCAT(ut.nombres,' ',ut.apellidos) AS tutor_academico,
           pr.horas_requeridas, pr.horas_cumplidas,
           pr.id_practica
    FROM   bitacoras b
    JOIN   practicas pr   ON pr.id_practica  = b.id_practica
    JOIN   estudiantes e  ON e.id_estudiante = pr.id_estudiante
    JOIN   usuarios u     ON u.id_usuario    = e.id_usuario
    JOIN   carreras car   ON car.id_carrera  = e.id_carrera
    JOIN   empresas em    ON em.id_empresa   = pr.id_empresa
    JOIN   periodos_academicos pe ON pe.id_periodo = pr.id_periodo
    LEFT JOIN tutores t   ON t.id_tutor      = pr.id_tutor
    LEFT JOIN usuarios ut ON ut.id_usuario   = t.id_usuario
    WHERE  $wStr
    ORDER  BY b.estado = 'enviada' DESC,
              b.estado = 'observada' DESC,
              b.created_at DESC
    LIMIT  200
");
$stBit->execute($params);
$bitacoras = $stBit->fetchAll();

// ── Contadores por estado ───────────────────────────────────
$stCnt = $db->prepare("SELECT b.estado, COUNT(*) AS total FROM bitacoras b JOIN practicas pr ON pr.id_practica=b.id_practica JOIN estudiantes e ON e.id_estudiante=pr.id_estudiante JOIN carreras car ON car.id_carrera=e.id_carrera WHERE 1=1" . ($idInst ? " AND car.id_instituto=$idInst" : '') . " GROUP BY b.estado");
$stCnt->execute();
$cnts = array_column($stCnt->fetchAll(), 'total', 'estado');

// ── Catálogos filtro ────────────────────────────────────────
$stCar = $db->prepare("SELECT id_carrera, nombre FROM carreras WHERE activa=1" . ($idInst ? " AND id_instituto=$idInst" : '') . " ORDER BY nombre");
$stCar->execute(); $carreras = $stCar->fetchAll();
$periodos = $db->query("SELECT id_periodo, nombre FROM periodos_academicos WHERE 1=1" . ($idInst ? " AND id_instituto=$idInst" : "") . " ORDER BY id_periodo DESC")->fetchAll();

// ── KPIs resumen ────────────────────────────────────────────
$stHV = $db->prepare("SELECT COALESCE(SUM(b.horas_semana),0) FROM bitacoras b JOIN practicas pr ON pr.id_practica=b.id_practica JOIN estudiantes e ON e.id_estudiante=pr.id_estudiante JOIN carreras car ON car.id_carrera=e.id_carrera WHERE b.estado='validada'" . ($idInst ? " AND car.id_instituto=$idInst" : ''));
$stHV->execute(); $totalHorasVal = (int)$stHV->fetchColumn();
$totalBit      = array_sum($cnts);
$pctVal        = $totalBit > 0 ? round(($cnts['validada'] ?? 0) / $totalBit * 100) : 0;
?>
<?php $paginaActual = 'bitacoras'; ?>
<!DOCTYPE html>
<html lang="es">
<head>
  <?php include __DIR__.'/../../includes/head.php'; ?>
  <link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sidebar.css">
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/sidebar-coordinador.css">
</head>
<body>
<?php include __DIR__.'/../../includes/navbar.php'; ?>

<div class="app-shell">
  <?php include __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'sidebar-coordinador.php'; ?>

  <main class="main-area">
    <?= flashHtml() ?>

    <div class="page-header d-flex justify-content-between align-items-center flex-wrap gap-2 mb-4">
      <div>
        <h4 class="mb-1"><i class="fa fa-book-open me-2" style="color:#3b82f6;"></i>Seguimiento de Bitácoras</h4>
        <p class="text-muted mb-0" style="font-size:14px;">Supervisión del registro semanal de todos los estudiantes en práctica</p>
      </div>
    </div>

    <!-- KPIs -->
    <div class="row g-3 mb-4">
      <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm text-center py-3">
          <div style="font-size:26px;font-weight:800;color:#2563eb;"><?= $totalBit ?></div>
          <div style="font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:#6b7280;">Total bitácoras</div>
        </div>
      </div>
      <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm text-center py-3">
          <div style="font-size:26px;font-weight:800;color:#d97706;"><?= $cnts['enviada'] ?? 0 ?></div>
          <div style="font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:#6b7280;">Esperando validación</div>
        </div>
      </div>
      <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm text-center py-3">
          <div style="font-size:26px;font-weight:800;color:#16a34a;"><?= $cnts['validada'] ?? 0 ?></div>
          <div style="font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:#6b7280;">Validadas</div>
        </div>
      </div>
      <div class="col-6 col-lg-3">
        <div class="card border-0 shadow-sm text-center py-3">
          <div style="font-size:26px;font-weight:800;color:#16a34a;"><?= number_format($totalHorasVal) ?>h</div>
          <div style="font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:#6b7280;">Horas validadas</div>
        </div>
      </div>
    </div>

    <!-- Barra progreso global -->
    <div class="card border-0 shadow-sm mb-3 px-4 py-3">
      <div class="d-flex justify-content-between mb-1" style="font-size:12px;">
        <span class="text-muted">Tasa de bitácoras validadas</span>
        <strong style="color:<?= $pctVal >= 70 ? '#16a34a' : '#d97706' ?>;"><?= $pctVal ?>%</strong>
      </div>
      <div class="d-flex gap-1" style="height:8px;border-radius:6px;overflow:hidden;background:#e5e7eb;">
        <?php
        $segmentos = [
            'validada'  => ['#16a34a', $cnts['validada']  ?? 0],
            'enviada'   => ['#d97706', $cnts['enviada']   ?? 0],
            'observada' => ['#dc2626', $cnts['observada'] ?? 0],
            'borrador'  => ['#d1d5db', $cnts['borrador']  ?? 0],
        ];
        foreach ($segmentos as $key => [$color, $val]):
            $w = $totalBit > 0 ? round($val / $totalBit * 100) : 0;
            if ($w > 0):
        ?>
          <div style="width:<?= $w ?>%;background:<?= $color ?>;transition:width .4s;"
               title="<?= ucfirst($key) ?>: <?= $val ?>"></div>
        <?php endif; endforeach; ?>
      </div>
      <div class="d-flex gap-3 mt-2 flex-wrap">
        <?php foreach ([
            ['Validadas',  '#16a34a', $cnts['validada']  ?? 0],
            ['Enviadas',   '#d97706', $cnts['enviada']   ?? 0],
            ['Observadas', '#dc2626', $cnts['observada'] ?? 0],
            ['Borradores', '#9ca3af', $cnts['borrador']  ?? 0],
        ] as [$lbl, $col, $n]): ?>
          <div class="d-flex align-items-center gap-1" style="font-size:11px;">
            <div style="width:10px;height:10px;border-radius:2px;background:<?= $col ?>;flex-shrink:0;"></div>
            <span class="text-muted"><?= $lbl ?>:</span>
            <strong style="color:<?= $col ?>;"><?= $n ?></strong>
          </div>
        <?php endforeach; ?>
      </div>
    </div>

    <!-- Filtros -->
    <form method="GET" class="mb-3">
      <div class="card border-0 shadow-sm px-3 py-3">
        <div class="row g-2 align-items-end">
          <!-- Tabs estado -->
          <div class="col-12 mb-1">
            <div class="d-flex gap-2 flex-wrap">
              <?php
              $tabs = [
                'todas'     => ['Todas',      '#6b7280'],
                'enviada'   => ['Enviadas',   '#d97706'],
                'validada'  => ['Validadas',  '#16a34a'],
                'observada' => ['Observadas', '#dc2626'],
                'borrador'  => ['Borradores', '#9ca3af'],
              ];
              foreach ($tabs as $k => [$lbl, $col]):
                $n = $k === 'todas' ? $totalBit : ($cnts[$k] ?? 0);
              ?>
                <a href="?estado=<?= $k ?>&q=<?= urlencode($q) ?>&carrera=<?= $idCarrera ?>&periodo=<?= $idPeriodo ?>"
                   class="btn btn-sm <?= $filtroEst === $k ? 'btn-primary' : 'btn-outline-secondary' ?>">
                  <?= $lbl ?>
                  <?php if ($n): ?>
                    <span class="badge rounded-pill ms-1"
                          style="background:<?= $filtroEst === $k ? 'rgba(255,255,255,.3)' : $col ?>;color:#fff;font-size:9px;">
                      <?= $n ?>
                    </span>
                  <?php endif; ?>
                </a>
              <?php endforeach; ?>
            </div>
          </div>
          <div class="col-sm-4">
            <input type="hidden" name="estado" value="<?= htmlspecialchars($filtroEst) ?>">
            <input type="text" name="q" class="form-control form-control-sm"
                   placeholder="Estudiante o empresa..." value="<?= htmlspecialchars($q) ?>">
          </div>
          <div class="col-sm-3">
            <select name="carrera" class="form-select form-select-sm">
              <option value="0">Todas las carreras</option>
              <?php foreach ($carreras as $c): ?>
                <option value="<?= $c['id_carrera'] ?>" <?= $idCarrera == $c['id_carrera'] ? 'selected' : '' ?>>
                  <?= htmlspecialchars($c['nombre']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-sm-3">
            <select name="periodo" class="form-select form-select-sm">
              <option value="0">Todos los períodos</option>
              <?php foreach ($periodos as $p): ?>
                <option value="<?= $p['id_periodo'] ?>" <?= $idPeriodo == $p['id_periodo'] ? 'selected' : '' ?>>
                  <?= htmlspecialchars($p['nombre']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-sm-2 d-flex gap-2">
            <button type="submit" class="btn btn-primary btn-sm flex-fill">
              <i class="fa fa-filter me-1"></i>Filtrar
            </button>
            <?php if ($q || $idCarrera || $idPeriodo): ?>
              <a href="?estado=<?= $filtroEst ?>" class="btn btn-sm btn-outline-secondary">✕</a>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </form>

    <div class="mb-2" style="font-size:12px;color:#6b7280;">
      <?= count($bitacoras) ?> bitácora(s) encontrada(s)
    </div>

    <!-- Tabla -->
    <div class="card shadow-sm border-0">
      <div class="card-body p-0">
        <table class="table table-hover mb-0" style="font-size:13px;">
          <thead style="background:#f8f9fa;">
            <tr style="font-size:11px;text-transform:uppercase;letter-spacing:.05em;color:#6b7280;">
              <th class="px-3 py-3">Estudiante</th>
              <th class="py-3">Carrera</th>
              <th class="py-3">Empresa</th>
              <th class="py-3 text-center">Semana</th>
              <th class="py-3">Período</th>
              <th class="py-3 text-center">Horas</th>
              <th class="py-3">Estado</th>
              <th class="py-3">Tutor</th>
              <th class="py-3">Fecha envío</th>
              <th class="py-3 text-center">Acciones</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($bitacoras)): ?>
              <tr>
                <td colspan="10" class="text-center py-5">
                  <i class="fa fa-book-open fa-2x mb-2 d-block" style="color:#d1d5db;"></i>
                  <span class="text-muted">Sin bitácoras para el filtro seleccionado.</span>
                </td>
              </tr>
            <?php else: foreach ($bitacoras as $b):
              $borderColor = match($b['estado']) {
                'validada'  => '#16a34a',
                'enviada'   => '#d97706',
                'observada' => '#dc2626',
                default     => '#e5e7eb'
              };
            ?>
              <tr style="border-left:3px solid <?= $borderColor ?>;">
                <td class="px-3 py-2">
                  <strong><?= htmlspecialchars($b['estudiante']) ?></strong>
                  <div style="font-size:10px;color:#9ca3af;font-family:monospace;"><?= htmlspecialchars($b['cedula']) ?></div>
                </td>
                <td class="py-2" style="font-size:12px;color:#7c3aed;"><?= htmlspecialchars($b['carrera']) ?></td>
                <td class="py-2" style="font-size:12px;"><?= htmlspecialchars($b['empresa']) ?></td>
                <td class="py-2 text-center">
                  <strong>Sem. <?= $b['semana_numero'] ?></strong>
                  <div style="font-size:10px;color:#9ca3af;white-space:nowrap;">
                    <?= formatFecha($b['fecha_inicio_semana'], 'd/m') ?> — <?= formatFecha($b['fecha_fin_semana'], 'd/m') ?>
                  </div>
                </td>
                <td class="py-2" style="font-size:11px;color:#6b7280;"><?= htmlspecialchars($b['periodo']) ?></td>
                <td class="py-2 text-center">
                  <strong style="color:#2563eb;"><?= $b['horas_semana'] ?>h</strong>
                </td>
                <td class="py-2"><?= badgeEstado($b['estado']) ?></td>
                <td class="py-2" style="font-size:11px;color:#6b7280;">
                  <?= htmlspecialchars($b['tutor_academico'] ?? '—') ?>
                </td>
                <td class="py-2" style="font-size:11px;color:#9ca3af;white-space:nowrap;">
                  <?= formatFecha($b['created_at'], 'd/m/Y') ?>
                </td>
                <td class="py-2 text-center">
                  <button class="btn btn-sm btn-outline-secondary btn-ver"
                    data-id="<?= $b['id_bitacora'] ?>"
                    data-estudiante="<?= htmlspecialchars($b['estudiante']) ?>"
                    data-empresa="<?= htmlspecialchars($b['empresa']) ?>"
                    data-carrera="<?= htmlspecialchars($b['carrera']) ?>"
                    data-semana="<?= $b['semana_numero'] ?>"
                    data-fi="<?= formatFecha($b['fecha_inicio_semana']) ?>"
                    data-ff="<?= formatFecha($b['fecha_fin_semana']) ?>"
                    data-horas="<?= $b['horas_semana'] ?>"
                    data-estado="<?= $b['estado'] ?>"
                    data-actividades="<?= htmlspecialchars($b['actividades']) ?>"
                    data-logros="<?= htmlspecialchars($b['logros'] ?? '') ?>"
                    data-dificultades="<?= htmlspecialchars($b['dificultades'] ?? '') ?>"
                    data-comentario="<?= htmlspecialchars($b['comentario_tutor'] ?? '') ?>"
                    data-tutor="<?= htmlspecialchars($b['tutor_academico'] ?? '') ?>"
                    data-horas-req="<?= $b['horas_requeridas'] ?>"
                    data-horas-cum="<?= $b['horas_cumplidas'] ?>">
                    <i class="fa fa-eye"></i>
                  </button>
                </td>
              </tr>
            <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </div>

  </main>
</div>

<!-- ══ MODAL VER BITÁCORA ══ -->
<div class="modal fade" id="modalBit" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="m-titulo">Bitácora</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">

        <!-- Header de datos -->
        <div class="card border-0 mb-3" style="background:#f8f9fa;">
          <div class="card-body py-3">
            <div class="row g-2" style="font-size:12px;">
              <div class="col-sm-4">
                <div style="font-size:9px;color:#6b7280;text-transform:uppercase;letter-spacing:.6px;">Estudiante</div>
                <div id="m-est" style="font-weight:700;font-size:13px;"></div>
                <div id="m-car" style="font-size:11px;color:#7c3aed;"></div>
              </div>
              <div class="col-sm-4">
                <div style="font-size:9px;color:#6b7280;text-transform:uppercase;letter-spacing:.6px;">Empresa</div>
                <div id="m-emp" style="font-weight:600;"></div>
                <div style="font-size:9px;color:#6b7280;margin-top:2px;">Tutor: <span id="m-tutor"></span></div>
              </div>
              <div class="col-sm-4">
                <div class="row g-1">
                  <div class="col-6">
                    <div style="font-size:9px;color:#6b7280;text-transform:uppercase;letter-spacing:.6px;">Período</div>
                    <div id="m-per" style="font-size:12px;"></div>
                  </div>
                  <div class="col-6">
                    <div style="font-size:9px;color:#6b7280;text-transform:uppercase;letter-spacing:.6px;">Estado</div>
                    <div id="m-badge"></div>
                  </div>
                </div>
                <div style="margin-top:8px;">
                  <div style="font-size:9px;color:#6b7280;margin-bottom:3px;">
                    Avance: <span id="m-hcum" style="color:#2563eb;font-weight:700;"></span>
                    / <span id="m-hreq" style="color:#6b7280;"></span> h
                  </div>
                  <div style="background:#e5e7eb;border-radius:3px;height:4px;">
                    <div id="m-barra" style="height:4px;border-radius:3px;background:#2563eb;transition:width .3s;"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Info semana -->
        <div class="d-flex gap-3 mb-3 flex-wrap">
          <div class="text-center px-4 py-2 rounded" style="background:#dbeafe;border:1px solid #bfdbfe;">
            <div style="font-size:9px;color:#1d4ed8;text-transform:uppercase;letter-spacing:.6px;">Semana</div>
            <div id="m-sem" style="font-size:22px;font-weight:700;color:#1d4ed8;"></div>
          </div>
          <div class="text-center px-4 py-2 rounded" style="background:#dcfce7;border:1px solid #bbf7d0;">
            <div style="font-size:9px;color:#15803d;text-transform:uppercase;letter-spacing:.6px;">Horas</div>
            <div id="m-hrs" style="font-size:22px;font-weight:700;color:#15803d;"></div>
          </div>
          <div class="flex-grow-1 px-3 py-2 rounded" style="background:#f8f9fa;border:1px solid #e5e7eb;min-width:160px;">
            <div style="font-size:9px;color:#6b7280;text-transform:uppercase;letter-spacing:.6px;">Período de la semana</div>
            <div id="m-fecha" style="font-size:13px;margin-top:4px;"></div>
          </div>
        </div>

        <hr>

        <!-- Contenido -->
        <div class="mb-3">
          <div style="font-size:10px;font-weight:700;letter-spacing:.8px;text-transform:uppercase;color:#6b7280;margin-bottom:6px;">
            Actividades realizadas
          </div>
          <div id="m-act" class="p-3 rounded" style="background:#f8f9fa;border:1px solid #e5e7eb;font-size:13px;line-height:1.8;white-space:pre-wrap;max-height:150px;overflow-y:auto;"></div>
        </div>

        <div class="mb-3" id="blk-log">
          <div style="font-size:10px;font-weight:700;letter-spacing:.8px;text-transform:uppercase;color:#6b7280;margin-bottom:6px;">
            Logros alcanzados
          </div>
          <div id="m-log" class="p-3 rounded" style="background:#dcfce7;border:1px solid #bbf7d0;font-size:13px;line-height:1.8;white-space:pre-wrap;max-height:120px;overflow-y:auto;color:#15803d;"></div>
        </div>

        <div class="mb-3" id="blk-dif">
          <div style="font-size:10px;font-weight:700;letter-spacing:.8px;text-transform:uppercase;color:#6b7280;margin-bottom:6px;">
            Dificultades encontradas
          </div>
          <div id="m-dif" class="p-3 rounded" style="background:#fee2e2;border:1px solid #fecaca;font-size:13px;line-height:1.8;white-space:pre-wrap;max-height:120px;overflow-y:auto;color:#dc2626;"></div>
        </div>

        <div id="blk-coment" style="display:none;">
          <hr>
          <div style="font-size:10px;font-weight:700;letter-spacing:.8px;text-transform:uppercase;color:#d97706;margin-bottom:6px;">
            <i class="fa fa-comment me-1"></i>Comentario del tutor
          </div>
          <div id="m-coment" class="p-3 rounded" style="background:#fef3c7;border:1px solid #fde68a;font-size:13px;color:#92400e;"></div>
        </div>

      </div>
    </div>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/js/bootstrap.bundle.min.js"></script>
<script>
var badgeMap = {
  'enviada':  '<span class="badge" style="background:#fef3c7;color:#92400e;">Enviada</span>',
  'validada': '<span class="badge" style="background:#dcfce7;color:#15803d;">Validada</span>',
  'observada':'<span class="badge" style="background:#fee2e2;color:#dc2626;">Observada</span>',
  'borrador': '<span class="badge" style="background:#f3f4f6;color:#6b7280;">Borrador</span>',
};

// Convierte actividades (JSON array de objetos) a texto legible
function actividadesToText(val) {
  if (!val) return '—';
  if (typeof val === 'string') return val;
  if (Array.isArray(val)) {
    return val.map(function(a, i) {
      if (typeof a === 'string') return (i + 1) + '. ' + a;
      var texto = a.descripcion || a.actividad || a.nombre || a.titulo || a.texto || a.detalle || '';
      if (!texto) texto = JSON.stringify(a);
      return (i + 1) + '. ' + texto;
    }).join('\n');
  }
  if (typeof val === 'object') {
    return val.descripcion || val.actividad || val.nombre || JSON.stringify(val);
  }
  return String(val);
}

$(function () {
  $(document).on('click', '.btn-ver', function () {
    var d = $(this).data();

    $('#m-titulo').text('Bitácora — Semana ' + d.semana + ' · ' + d.estudiante);
    $('#m-est').text(d.estudiante);
    $('#m-car').text(d.carrera);
    $('#m-emp').text(d.empresa);
    $('#m-tutor').text(d.tutor || 'Sin asignar');
    $('#m-per').text(d.fi + ' – ' + d.ff);
    $('#m-badge').html(badgeMap[d.estado] || d.estado);

    var pct = d.horasReq > 0 ? Math.min(100, Math.round(d.horasCum / d.horasReq * 100)) : 0;
    $('#m-hcum').text(d.horasCum);
    $('#m-hreq').text(d.horasReq);
    $('#m-barra').css('width', pct + '%')
                 .css('background', pct >= 100 ? '#16a34a' : '#2563eb');

    $('#m-sem').text(d.semana);
    $('#m-hrs').text(d.horas + 'h');
    $('#m-fecha').text(d.fi + ' al ' + d.ff);
    $('#m-act').text(actividadesToText(d.actividades));

    if (d.logros) { $('#m-log').text(d.logros); $('#blk-log').show(); }
    else { $('#blk-log').hide(); }

    if (d.dificultades) { $('#m-dif').text(d.dificultades); $('#blk-dif').show(); }
    else { $('#blk-dif').hide(); }

    if (d.comentario) { $('#m-coment').text(d.comentario); $('#blk-coment').show(); }
    else { $('#blk-coment').hide(); }

    new bootstrap.Modal('#modalBit').show();
  });
});
</script>
</body>
</html>