<?php
@session_start();

/* ===== DB ===== */
if (file_exists(__DIR__.'/db.php')) { require __DIR__.'/db.php'; $pdo = pdo();
} else {
  define('DB_HOST','localhost'); define('DB_NAME','tu_base'); define('DB_USER','tu_usuario'); define('DB_PASS','tu_pass');
  try{
    $pdo = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8mb4", DB_USER, DB_PASS, [
      PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC
    ]);
  }catch(Exception $e){ http_response_code(500); die("DB error: ".$e->getMessage()); }
}

/* ===== Helpers ===== */
function base_url_prefix(){
  $proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
  $host  = $_SERVER['HTTP_HOST'] ?? 'localhost';
  $base  = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');
  return $proto.$host.$base;
}
function normalize_media_url($src){
  $src = trim((string)$src);
  if ($src === '') return '';
  if (preg_match('#^https?://#i', $src)) return $src;
  if (preg_match('#^/?uploads/#i', $src)) {
    $prefix = base_url_prefix();
    $src = ltrim($src, '/');
    return rtrim($prefix,'/').'/'.$src;
  }
  return rtrim(base_url_prefix(),'/').'/'.ltrim($src,'/');
}
function is_youtube($u){ return (bool)preg_match('#(youtube\.com|youtu\.be)#i',$u); }
function yt_id($u){
  if (preg_match('#youtu\.be/([^?&/]+)#i', $u, $m)) return $m[1];
  if (preg_match('#v=([^&]+)#i', $u, $m)) return $m[1];
  if (preg_match('#/embed/([^?&/]+)#i', $u, $m)) return $m[1];
  return '';
}
function is_vimeo($u){ return (bool)preg_match('#vimeo\.com#i',$u); }
function vimeo_id($u){
  if (preg_match('#vimeo\.com/(\d+)#i', $u, $m)) return $m[1];
  if (preg_match('#player\.vimeo\.com/video/(\d+)#i', $u, $m)) return $m[1];
  return '';
}
function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

function render_block($b){
  $type = $b['type'] ?? '';
  switch ($type) {
    case 'h1':
      return '<h2 class="h1">'.($b['content'] ?? 'Título').'</h2>';

    case 'p':
      return '<p>'.($b['content'] ?? '').'</p>';

    case 'quote':
      return '<blockquote>'.($b['content'] ?? '').'</blockquote>';

    case 'link': {
      $href = e($b['href'] ?? '#');
      $txt  = $b['content'] ?? $href;
      return '<p><a class="a" href="'.$href.'" target="_blank" rel="nofollow noopener">'.$txt.'</a></p>';
    }

    case 'img': {
      $src = normalize_media_url($b['src'] ?? '');
      if (!$src) return '';
      return '<figure><img class="img" src="'.e($src).'" alt=""></figure>';
    }

    case 'embed':
      return (string)($b['embedHtml'] ?? '');

    case 'video': {
      $raw = $b['src'] ?? '';
      $src = normalize_media_url($raw);
      if (!$src) return '';
      if (is_youtube($src)) {
        $id = yt_id($src);
        if ($id) {
          return '<div class="ratio"><iframe src="https://www.youtube.com/embed/'.e($id).'" title="YouTube video" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe></div>';
        }
      }
      if (is_vimeo($src)) {
        $id = vimeo_id($src);
        if ($id) {
          return '<div class="ratio"><iframe src="https://player.vimeo.com/video/'.e($id).'" title="Vimeo video" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen></iframe></div>';
        }
      }
      // Directo/local (mp4/webm/ogg)
      $t = strtolower(pathinfo(parse_url($src, PHP_URL_PATH) ?? '', PATHINFO_EXTENSION));
      $mime = ($t==='webm'?'video/webm':($t==='ogg'?'video/ogg':'video/mp4'));
      return '<div class="video"><video controls preload="metadata"><source src="'.e($src).'" type="'.$mime.'"></video></div>';
    }
  }
  return '';
}

function render_blocks($json){
  $arr = [];
  try { $arr = json_decode($json ?? '[]', true) ?: []; } catch (Throwable $e) { $arr = []; }
  if (!is_array($arr)) $arr = [];
  $html = '';
  foreach ($arr as $b) $html .= render_block($b);
  return $html;
}

/* ===== Data ===== */
$st = $pdo->query("SELECT id,titulo,estado,portada_url,contenido_json,updated_at
                   FROM noticias
                   WHERE estado IN ('borrador','publicado')
                   ORDER BY updated_at DESC
                   LIMIT 50");
$items = $st->fetchAll();

?><!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Noticias</title>
<style>
:root{--ink:#0f1a24;--soft:#f6f8fb;--line:#e2e8f0;--accent:#1f72b6}
*{box-sizing:border-box} body{margin:0;font-family:system-ui,Segoe UI,Roboto,Inter,Arial,sans-serif;color:var(--ink);background:#fff}
.wrap{max-width:1100px;margin:0 auto;padding:16px}
.h1{font-size:22px;margin:0 0 6px}
.card{border:1px solid var(--line);border-radius:12px;padding:14px;background:#fff}
.grid{display:grid;grid-template-columns:1fr;gap:14px}
.head{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px}
a.a{color:var(--accent);text-decoration:none}
a.a:hover{text-decoration:underline}
figure{margin:0}
.img{max-width:100%;display:block;border-radius:10px}
.ratio{position:relative;width:100%;padding-top:56.25%;border-radius:10px;overflow:hidden;border:1px solid var(--line);background:#000}
.ratio iframe{position:absolute;inset:0;width:100%;height:100%;border:0;display:block}
.video video{width:100%;height:auto;border-radius:10px;border:1px solid var(--line);background:#000}
.meta{color:#475569;font-size:12px}
.item-title{font-weight:700;font-size:18px;margin:0}
.item-link{display:inline-block;margin-top:8px}
.sep{height:1px;background:var(--line);margin:12px 0}
</style>
</head>
<body>
  <div class="wrap">
    <div class="head">
      <h1 style="margin:0">Noticias</h1>
      <a class="a" href="admin_noticias_lite.php">Admin</a>
    </div>

    <div class="grid">
      <?php if(!$items): ?>
        <div class="card">Sin noticias por ahora.</div>
      <?php else: foreach($items as $it): ?>
        <article class="card">
          <h2 class="item-title"><a class="a" href="nota.php?id=<?= (int)$it['id'] ?>"><?= e($it['titulo'] ?: 'Sin título') ?></a></h2>
          <div class="meta"><?= e($it['estado']) ?> — <?= e($it['updated_at']) ?></div>
          <div class="sep"></div>
          <div><?= render_blocks($it['contenido_json']) ?></div>
          <a class="a item-link" href="nota.php?id=<?= (int)$it['id'] ?>">Ver detalle »</a>
        </article>
      <?php endforeach; endif; ?>
    </div>
  </div>
</body>
</html>