<?php
@session_start();
require __DIR__.'/db.php';
$pdo = pdo();

$items = $pdo->query("SELECT id,titulo,portada_url,contenido_json,created_at
                      FROM noticias
                      WHERE estado='publicado'
                      ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);

function norm_text($t){
  $t = str_replace([\"\xC2\xA0\",'&nbsp;'], ' ', (string)$t);
  $t = strip_tags($t);
  $t = preg_replace('/\s+/u',' ', $t);
  return trim($t);
}
function first_h1_text($json){
  $arr = json_decode($json, true);
  if (!is_array($arr)) return '';
  foreach ($arr as $b){
    if (($b['type']??$b['tipo']??'')==='h1'){
      $txt = norm_text($b['content']??$b['text']??'');
      if ($txt!=='') return $txt;
    }
  }
  return '';
}
function first_img_src($json){
  $arr = json_decode($json, true);
  if (!is_array($arr)) return '';
  foreach ($arr as $b){
    if (($b['type']??$b['tipo']??'')==='img'){
      $src = trim((string)($b['src'] ?? ''));
      if ($src!=='') return $src;
    }
  }
  return '';
}
function extract_excerpt($json){
  $arr = json_decode($json, true);
  if (!is_array($arr)) return '';
  foreach ($arr as $b){
    if (($b['type']??$b['tipo']??'')==='p'){
      $txt = norm_text($b['content']??$b['text']??'');
      if ($txt!=='') return mb_strimwidth($txt, 0, 180, '…', 'UTF-8');
    }
  }
  foreach ($arr as $b){
    $type = $b['type']??$b['tipo']??'';
    if (in_array($type, ['h1','quote','link'])){
      $txt = norm_text($b['content']??$b['text']??'');
      if ($txt!=='') return mb_strimwidth($txt, 0, 180, '…', 'UTF-8');
    }
  }
  return '';
}
?>
<!-- ====== Barra de fecha (azul) ====== -->
<div class="datebar">
  <div class="container inner"><span id="fecha-hoy">—</span></div>
</div>

<!-- ====== Solo franja azul del título ====== -->
<div class="nt-band">
  <div class="inner container">
    <h2>Notas</h2>
    <div class="rule"></div>
  </div>
</div>

<!-- ====== Contenido de Notas ====== -->
<section class="nt-wrap" id="notas">
  <div class="nt-grid">
    <?php if ($items): foreach ($items as $n):
      $h1    = first_h1_text($n['contenido_json']);
      $title = ($n['titulo'] && $n['titulo']!=='Sin título') ? $n['titulo'] : $h1;
      if ($title==='') $title='Sin título';
      $cover   = $n['portada_url'] ?: first_img_src($n['contenido_json']);
      $excerpt = extract_excerpt($n['contenido_json']);
      $fecha   = date('d/m/Y', strtotime($n['created_at']));
    ?>
      <article class="nt-card">
        <?php if($cover): ?>
          <a href="nota.php?id=<?= (int)$n['id'] ?>">
            <img class="nt-cover" src="<?= htmlspecialchars($cover, ENT_QUOTES, 'UTF-8') ?>" alt="<?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?>">
          </a>
        <?php else: ?>
          <div class="nt-cover"></div>
        <?php endif; ?>
        <div class="nt-body">
          <h3 class="nt-title"><a href="nota.php?id=<?= (int)$n['id'] ?>"><?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?></a></h3>
          <?php if($excerpt): ?><div class="nt-excerpt"><?= htmlspecialchars($excerpt, ENT_QUOTES, 'UTF-8') ?></div><?php endif; ?>
          <a class="nt-more" href="nota.php?id=<?= (int)$n['id'] ?>">Leer más</a>
        </div>
        <div class="nt-meta">
          <span><?= $fecha ?></span>
          <span class="nt-dot"></span>
          <span>No hay comentarios</span>
        </div>
      </article>
    <?php endforeach; else: ?>
      <div style="color:#5b6672">No hay noticias publicadas.</div>
    <?php endif; ?>
  </div>
</section>

<!-- ====== Estilos propios SOLO de notas (no tocan navbar/footer) ====== -->
<style>
  .datebar{background:#15324c;color:#fff;font-weight:600}
  .datebar .inner{height:40px;display:flex;align-items:center}
  .nt-band{background:#0f2a44;padding:14px 0;}
  .nt-band .inner{max-width:1200px;margin:0 auto;padding:0 20px;display:flex;align-items:center;gap:20px;color:#fff;}
  .nt-band h2{margin:0;font-size:22px;font-weight:800}
  .nt-band .rule{flex:1;height:2px;background:#e3edf7;opacity:.3}

  .nt-wrap{max-width:1200px;margin:0 auto;padding:22px 20px 44px;background:#fff;}
  .nt-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:22px}
  @media (max-width:1024px){.nt-grid{grid-template-columns:repeat(2,1fr)}}
  @media (max-width:640px){.nt-grid{grid-template-columns:1fr}}

  .nt-card{background:#fff;border:1px solid #e9eef3;border-radius:14px;overflow:hidden;display:flex;flex-direction:column}
  .nt-cover{width:100%;aspect-ratio:16/9;object-fit:cover;transition:transform .35s ease;background:#f1f4f8}
  .nt-card:hover .nt-cover{transform:scale(1.02)}
  .nt-body{padding:14px 16px}
  .nt-title{font-size:18px;line-height:1.25;font-weight:700;margin:0 0 8px}
  .nt-title a{text-decoration:none}
  .nt-title a:hover{text-decoration:underline}
  .nt-excerpt{color:#374151;margin-bottom:10px}
  .nt-more{display:inline-block;font-weight:600;font-size:14px;opacity:.8}
  .nt-more:hover{opacity:1;text-decoration:underline}
  .nt-meta{display:flex;gap:10px;align-items:center;font-size:12px;color:#5b6672;border-top:1px solid #eef2f6;padding:10px 16px}
  .nt-dot{width:4px;height:4px;border-radius:50%;background:#c9d1db;display:inline-block}
</style>

<!-- ====== JS para fecha (solo esta vista) ====== -->
<script>
  (function(){
    var el = document.getElementById('fecha-hoy');
    if(!el) return;
    try{
      var d=new Date(), f=new Intl.DateTimeFormat('es-AR',{weekday:'long',day:'2-digit',month:'long',year:'numeric'});
      var t=f.format(d).split(' ');
      el.textContent=(t[0].charAt(0).toUpperCase()+t[0].slice(1))+' '+t[1]+' '+t[2].charAt(0).toUpperCase()+t[2].slice(1)+', '+t[3];
    }catch(e){el.textContent='Hoy';}
  })();
</script>
