<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CLASSIFIED ADS & COUPONS | Official Portal, Public Notices & Promo Codes</title>
  <meta name="description" content="Browse verified classified ads, local supermarket circulars, discount coupons, and official public notices across the United States.">
  <link rel="canonical" href="https://classifiedads-coupons.cc/">
  <link rel="icon" type="image/png" href="/favicon.png">
  <link rel="shortcut icon" href="/favicon.ico">
  
  <!-- Preload Critical LCP Assets: Logo (17KB WebP) and CSS (30KB) -->
  <link rel="preload" as="image" href="/logo.webp" type="image/webp" fetchpriority="high">
  <link rel="preload" href="/styles.min.css" as="style">
  <link rel="stylesheet" href="/styles.min.css">

  <!-- Preconnect to external CDNs -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link rel="preconnect" href="https://cdnjs.cloudflare.com">

  <!-- Non-blocking FontAwesome Icons (No preload to avoid high-priority network queue) -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" media="print" onload="this.media='all'">
  <noscript><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"></noscript>

  <!-- Non-blocking Google Fonts with font-display=swap -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bangers&family=Cinzel:wght@700;900&family=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,700;1,6..72,400&family=JetBrains+Mono:wght@700;800&family=Inter:wght@400;500;600;700;800;900&display=swap" media="print" onload="this.media='all'">
  <noscript><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bangers&family=Cinzel:wght@700;900&family=Newsreader:ital,opsz,wght@0,6..72,400;0,6..72,700;1,6..72,400&family=JetBrains+Mono:wght@700;800&family=Inter:wght@400;500;600;700;800;900&display=swap"></noscript>

  <!-- US Dataset Only for Root Domain (192 KB deferred - saves 900KB of unused JS on initial load) -->
  <script defer src="/usDataset.js"></script>
  
  <!-- Módulos Clientes de APIs, Router SEO y Sitemaps (Deferred) -->
  <script defer src="/couponApiClient.js"></script>
  <script defer src="/boeApiClient.js"></script>
  <script defer src="/multiCountryOfficialClient.js"></script>
  <script defer src="/router.js"></script>
  <script defer src="/sitemapGenerator.js"></script>
  <script defer src="/adLifecycleManager.js"></script>

  <!-- Google AdSense Smart Deferred Loader (Executes on user interaction or idle to prevent TBT penalty) -->
  <script>
    (function() {
      let loaded = false;
      function loadAdSense() {
        if (loaded) return;
        loaded = true;
        const s = document.createElement('script');
        s.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3961379407467415';
        s.async = true;
        s.crossOrigin = 'anonymous';
        document.head.appendChild(s);
      }
      ['scroll', 'touchstart', 'mousemove', 'click', 'keydown'].forEach(evt => {
        window.addEventListener(evt, loadAdSense, { once: true, passive: true });
      });
      setTimeout(loadAdSense, 4000);
    })();
  </script>
</head>
<body class="text-ink font-sans antialiased min-h-screen pb-12">

  <!-- MASTHEAD / CABECERA ESTILO PRENSA IMPRESA -->
  <header class="max-w-7xl mx-auto px-4 pt-6 pb-4">
    <div class="border-b-4 border-ink pb-4 text-center">
      <div class="flex justify-between items-center border-b border-ink pb-1 mb-2 text-xs font-news italic">
        <span>"Alcanza una audiencia cualificada en prensa impresa y soporte digital"</span>
        <span class="font-bold uppercase tracking-wider hidden md:inline">AVISOS CLASIFICADOS + EDICTOS BOE + FOLLETOS Y CUPONES API</span>
        <span id="current-month-badge" class="font-bold text-ink not-italic bg-amber-100 text-amber-950 border border-amber-300 px-2 py-0.5 rounded font-sans">
          <i class="fa-regular fa-calendar-days text-newsred mr-1"></i> <span id="current-month-text">October 2026</span>
        </span>
      </div>
      <div class="flex items-center justify-center gap-4 my-2"><picture><source srcset="/logo.webp" type="image/webp"><img id="brand-header-icon" src="/logo.png" alt="CLASSIFIED ADS & COUPONS - Official US Portal" width="112" height="112" fetchpriority="high" class="w-20 h-20 md:w-28 md:h-28 object-contain"></picture><h1 id="brand-main-title" class="font-masthead text-3xl sm:text-5xl md:text-6xl font-black uppercase tracking-tight text-ink">
        AVISOS CLASIFICADOS <span class="text-newsred">&</span> CUPÓNES
      </h1></div>
    </div>

    <!-- WIDGET PASO A PASO -->
    <div class="my-4 bg-white border-2 border-ink rounded-lg p-3 shadow-sm flex flex-col md:flex-row items-center justify-between gap-4">
      <div class="flex items-center gap-3">
        <div class="w-10 h-10 rounded-full bg-slate-900 text-white font-masthead font-bold flex items-center justify-center text-lg shadow">
          AC
        </div>
        <div>
          <h4 class="font-bold text-xs uppercase tracking-wide text-ink">Visibilidad Máxima Digital e Impresa</h4>
          <p class="text-[11px] text-gray-600 font-news italic">Publica tu aviso o cupón y aparece en web, app y edición impresa regional.</p>
        </div>
      </div>
      
      <div class="flex items-center gap-4 text-xs font-semibold text-gray-800">
        <div class="flex items-center gap-2">
          <span class="w-7 h-7 rounded-full bg-amber-400 text-slate-950 font-bold flex items-center justify-center border border-black">1</span>
          <span>Publica tu Anuncio / Cupón</span>
        </div>
        <div class="flex items-center gap-2">
          <span class="w-7 h-7 rounded-full bg-amber-400 text-slate-950 font-bold flex items-center justify-center border border-black">2</span>
          <span>Disponible en Web y Prensa</span>
        </div>
        <button onclick="openPublishModal()" class="bg-newsred text-white text-xs font-bold px-3.5 py-1.5 rounded hover:bg-red-700 transition shadow">
          + Publicar Ahora
        </button>
      </div>
    </div>



    <!-- BARRA DE BÚSQUEDA Y FILTRADO -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-3 bg-white p-3 border border-gray-300 rounded-lg shadow-sm">
      <div class="md:col-span-2 relative">
        <i class="fa-solid fa-magnifying-glass absolute left-3 top-3 text-gray-400"></i>
        <input type="text" id="search-input" aria-label="Search classified ads and coupons" onkeyup="filterItems()" placeholder="¿Qué busco en AVISOS CLASIFICADOS & CUPÓNES? Ej: BOE, Subasta, DIA..." class="w-full pl-9 pr-3 py-2 text-sm border border-gray-300 rounded focus:ring-2 focus:ring-ink focus:outline-none">
      </div>
      <div>
        <select id="type-select" aria-label="Filter by advertisement type" onchange="filterItems()" class="w-full py-2 px-3 text-sm border border-gray-300 rounded bg-white focus:ring-2 focus:ring-ink focus:outline-none">
          <option value="all">Mostrar Todos los Modelos</option>
          <option value="clasificado">Clasificados Breves</option>
          <option value="oficial">Edictos & Comunicados BOE</option>
          <option value="coupon">Cupones Troquelados</option>
          <option value="supermarket">Folletos Supermercado</option>
        </select>
      </div>
      <div>
        <button onclick="resetFilters()" aria-label="Reset search filters" class="w-full py-2 px-3 text-sm font-medium bg-gray-100 text-gray-700 hover:bg-gray-200 border border-gray-300 rounded flex items-center justify-center gap-1.5">
          <i class="fa-solid fa-rotate-left"></i> Restablecer Filtros
        </button>
      </div>
    </div>
  </header>

  <!-- MÓDULO UNIFICADO: GUÍA COMERCIAL, SECTORES & NAVEGACIÓN DE FILTROS DE PRENSA -->
  <section class="max-w-7xl mx-auto px-4 mb-6">
    <div class="bg-white border-2 border-ink rounded-xl p-4 shadow-sm space-y-4">
      
      <!-- CABECERA DEL CONTENEDOR UNIFICADO CON TÍTULO Y BOTÓN DE PUBLICAR -->
      <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 pb-3 border-b-2 border-ink">
        <div>
          <h3 class="font-masthead text-lg font-bold text-ink flex items-center gap-2">
            <i class="fa-solid fa-store text-newsorange"></i> Guía Comercial & Sectores de AVISOS CLASIFICADOS & CUPÓNES
          </h3>
          <p class="text-xs text-gray-500 font-news italic">Haz clic en una especialidad o categoría para filtrar avisos y cupones</p>
        </div>

        <button onclick="openPublishModal()" class="bg-newsred text-white font-bold text-xs uppercase px-4 py-2 rounded shadow border border-red-800 hover:bg-red-700 transition flex items-center gap-1.5 shrink-0">
          <i class="fa-solid fa-plus-circle text-sm"></i> Publicar Anuncio / Edicto / Cupón
        </button>
      </div>

      <!-- BOTONES DE FILTRADO DE PESTAÑAS (NAV PILLS FORMALES Y EJECUTIVOS) -->
      <div class="flex flex-wrap items-center gap-1.5 text-xs font-bold uppercase py-1" id="category-pills">
        <button onclick="setCategory('all')" class="cat-pill active px-3.5 py-1.5 bg-slate-900 text-white rounded-md border border-slate-900 hover:bg-black transition shadow-xs">
          Todos los Avisos
        </button>
        <button onclick="setCategory('edictos')" class="cat-pill px-3.5 py-1.5 bg-slate-800 text-white rounded-md border border-slate-900 hover:bg-slate-900 transition shadow-xs">
          Edictos BOE Oficiales
        </button>
        <button onclick="setCategory('supermercado')" class="cat-pill px-3.5 py-1.5 bg-amber-800 text-white rounded-md border border-amber-900 hover:bg-amber-900 transition shadow-xs">
          Supermercados & Ofertas
        </button>
        <button onclick="setCategory('inmuebles')" class="cat-pill px-3.5 py-1.5 bg-emerald-800 text-white rounded-md border border-emerald-900 hover:bg-emerald-900 transition shadow-xs">
          Inmuebles & Vivienda
        </button>
        <button onclick="setCategory('motor')" class="cat-pill px-3.5 py-1.5 bg-stone-800 text-white rounded-md border border-stone-900 hover:bg-stone-900 transition shadow-xs">
          Motor & Talleres
        </button>
        <button onclick="setCategory('servicios')" class="cat-pill px-3.5 py-1.5 bg-indigo-900 text-white rounded-md border border-indigo-950 hover:bg-black transition shadow-xs">
          Servicios & Gremios
        </button>
        <button onclick="setCategory('hosteleria')" class="cat-pill px-3.5 py-1.5 bg-red-800 text-white rounded-md border border-red-900 hover:bg-red-900 transition shadow-xs">
          Pizzerías & Bares
        </button>
        <button onclick="setCategory('cupones')" class="cat-pill px-3.5 py-1.5 bg-newsred text-white rounded-md border border-red-800 hover:bg-red-800 transition shadow-xs">
          Cupones Troquelados
        </button>
      </div>

      <!-- ESPECIALIDADES Y SECTORES ILUSTRADOS (ESTILO EJECUTIVO UNIFICADO) -->
      <div class="pt-3 border-t border-gray-200">
        <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-2.5">
          <button onclick="filterSector('supermercado')" class="sector-card bg-slate-50 border border-slate-300 rounded-lg p-2.5 text-left flex items-center gap-2.5 hover:bg-slate-100 hover:border-slate-900 transition">
            <div class="w-9 h-9 rounded-lg bg-slate-900 text-amber-400 flex items-center justify-center text-base shrink-0 shadow-sm border border-slate-950"><i class="fa-solid fa-cart-shopping"></i></div>
            <div>
              <div class="font-bold text-xs text-slate-950 uppercase tracking-tight">Supermercados</div>
              <div class="text-[10px] text-slate-600 font-mono">Frutas & Ofertas</div>
            </div>
          </button>

          <button onclick="filterSector('edictos')" class="sector-card bg-slate-50 border border-slate-300 rounded-lg p-2.5 text-left flex items-center gap-2.5 hover:bg-slate-100 hover:border-slate-900 transition">
            <div class="w-9 h-9 rounded-lg bg-slate-900 text-blue-300 flex items-center justify-center text-base shrink-0 shadow-sm border border-slate-950"><i class="fa-solid fa-scale-balanced"></i></div>
            <div>
              <div class="font-bold text-xs text-slate-950 uppercase tracking-tight">Edictos & Avisos</div>
              <div class="text-[10px] text-slate-600 font-mono">BOE & Municipales</div>
            </div>
          </button>

          <button onclick="filterSector('hosteleria')" class="sector-card bg-slate-50 border border-slate-300 rounded-lg p-2.5 text-left flex items-center gap-2.5 hover:bg-slate-100 hover:border-slate-900 transition">
            <div class="w-9 h-9 rounded-lg bg-slate-900 text-rose-300 flex items-center justify-center text-base shrink-0 shadow-sm border border-slate-950"><i class="fa-solid fa-pizza-slice"></i></div>
            <div>
              <div class="font-bold text-xs text-slate-950 uppercase tracking-tight">Pizzerías & Bares</div>
              <div class="text-[10px] text-slate-600 font-mono">Comida a domicilio</div>
            </div>
          </button>

          <button onclick="filterSector('pasteleria')" class="sector-card bg-slate-50 border border-slate-300 rounded-lg p-2.5 text-left flex items-center gap-2.5 hover:bg-slate-100 hover:border-slate-900 transition">
            <div class="w-9 h-9 rounded-lg bg-slate-900 text-pink-300 flex items-center justify-center text-base shrink-0 shadow-sm border border-slate-950"><i class="fa-solid fa-cake-candles"></i></div>
            <div>
              <div class="font-bold text-xs text-slate-950 uppercase tracking-tight">Pastelerías</div>
              <div class="text-[10px] text-slate-600 font-mono">Pan & Dulces</div>
            </div>
          </button>

          <button onclick="filterSector('servicios')" class="sector-card bg-slate-50 border border-slate-300 rounded-lg p-2.5 text-left flex items-center gap-2.5 hover:bg-slate-100 hover:border-slate-900 transition">
            <div class="w-9 h-9 rounded-lg bg-slate-900 text-amber-300 flex items-center justify-center text-base shrink-0 shadow-sm border border-slate-950"><i class="fa-solid fa-bolt"></i></div>
            <div>
              <div class="font-bold text-xs text-slate-950 uppercase tracking-tight">Electricistas</div>
              <div class="text-[10px] text-slate-600 font-mono">Urgencias 24h</div>
            </div>
          </button>

          <button onclick="filterSector('servicios')" class="sector-card bg-slate-50 border border-slate-300 rounded-lg p-2.5 text-left flex items-center gap-2.5 hover:bg-slate-100 hover:border-slate-900 transition">
            <div class="w-9 h-9 rounded-lg bg-slate-900 text-cyan-300 flex items-center justify-center text-base shrink-0 shadow-sm border border-slate-950"><i class="fa-solid fa-wrench"></i></div>
            <div>
              <div class="font-bold text-xs text-slate-950 uppercase tracking-tight">Fontaneros</div>
              <div class="text-[10px] text-slate-600 font-mono">Desatascos & Agua</div>
            </div>
          </button>

          <button onclick="filterSector('veterinaria')" class="sector-card bg-slate-50 border border-slate-300 rounded-lg p-2.5 text-left flex items-center gap-2.5 hover:bg-slate-100 hover:border-slate-900 transition">
            <div class="w-9 h-9 rounded-lg bg-slate-900 text-emerald-300 flex items-center justify-center text-base shrink-0 shadow-sm border border-slate-950"><i class="fa-solid fa-paw"></i></div>
            <div>
              <div class="font-bold text-xs text-slate-950 uppercase tracking-tight">Veterinarios</div>
              <div class="text-[10px] text-slate-600 font-mono">Mascotas & Clínica</div>
            </div>
          </button>

          <button onclick="filterSector('opticas')" class="sector-card bg-slate-50 border border-slate-300 rounded-lg p-2.5 text-left flex items-center gap-2.5 hover:bg-slate-100 hover:border-slate-900 transition">
            <div class="w-9 h-9 rounded-lg bg-slate-900 text-sky-300 flex items-center justify-center text-base shrink-0 shadow-sm border border-slate-950"><i class="fa-solid fa-glasses"></i></div>
            <div>
              <div class="font-bold text-xs text-slate-950 uppercase tracking-tight">Ópticas & Salud</div>
              <div class="text-[10px] text-slate-600 font-mono">Gafas Gratis / Dto</div>
            </div>
          </button>

          <button onclick="filterSector('motor')" class="sector-card bg-slate-50 border border-slate-300 rounded-lg p-2.5 text-left flex items-center gap-2.5 hover:bg-slate-100 hover:border-slate-900 transition">
            <div class="w-9 h-9 rounded-lg bg-slate-900 text-orange-300 flex items-center justify-center text-base shrink-0 shadow-sm border border-slate-950"><i class="fa-solid fa-car"></i></div>
            <div>
              <div class="font-bold text-xs text-slate-950 uppercase tracking-tight">Autoescuelas</div>
              <div class="text-[10px] text-slate-600 font-mono">Carnet de conducir</div>
            </div>
          </button>

          <button onclick="filterSector('gimnasio')" class="sector-card bg-slate-50 border border-slate-300 rounded-lg p-2.5 text-left flex items-center gap-2.5 hover:bg-slate-100 hover:border-slate-900 transition">
            <div class="w-9 h-9 rounded-lg bg-slate-900 text-red-400 flex items-center justify-center text-base shrink-0 shadow-sm border border-slate-950"><i class="fa-solid fa-dumbbell"></i></div>
            <div>
              <div class="font-bold text-xs text-slate-950 uppercase tracking-tight">Gimnasios & Fitness</div>
              <div class="text-[10px] text-slate-600 font-mono">Matrícula gratis</div>
            </div>
          </button>

          <button onclick="filterSector('reformas')" class="sector-card bg-slate-50 border border-slate-300 rounded-lg p-2.5 text-left flex items-center gap-2.5 hover:bg-slate-100 hover:border-slate-900 transition">
            <div class="w-9 h-9 rounded-lg bg-slate-900 text-stone-300 flex items-center justify-center text-base shrink-0 shadow-sm border border-slate-950"><i class="fa-solid fa-palette"></i></div>
            <div>
              <div class="font-bold text-xs text-slate-950 uppercase tracking-tight">Pintores & Obras</div>
              <div class="text-[10px] text-slate-600 font-mono">Reformas integrales</div>
            </div>
          </button>

          <button onclick="filterSector('colegios')" class="sector-card bg-slate-50 border border-slate-300 rounded-lg p-2.5 text-left flex items-center gap-2.5 hover:bg-slate-100 hover:border-slate-900 transition">
            <div class="w-9 h-9 rounded-lg bg-slate-900 text-indigo-300 flex items-center justify-center text-base shrink-0 shadow-sm border border-slate-950"><i class="fa-solid fa-graduation-cap"></i></div>
            <div>
              <div class="font-bold text-xs text-slate-950 uppercase tracking-tight">Cursos & Guarderías</div>
              <div class="text-[10px] text-slate-600 font-mono">Formación infantil</div>
            </div>
          </button>
        </div>
      </div>

    </div>
  </section>

  <!-- SECCIÓN DENSA: COLUMNAS DE ANUNCIOS BREVES POR CÓDIGO -->
  <section class="max-w-7xl mx-auto px-4 mb-6">
    <div class="bg-white newspaper-border p-4 rounded-lg">
      <div class="flex justify-between items-center mb-3 pb-2 border-b-2 border-ink">
        <h3 class="font-masthead text-base font-bold uppercase tracking-tight text-ink flex items-center gap-2">
          <i class="fa-solid fa-list-ol text-red-600"></i> Avisos Breves por Secciones Coded (Cultura Prensa Clasificada)
        </h3>
        <span class="text-xs font-mono font-bold bg-gray-200 px-2 py-0.5 rounded text-gray-800">CÓDIGOS: 101 - 404</span>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-4 gap-4 text-xs">
        <div class="border-r border-gray-300 pr-3 space-y-3">
          <div class="bg-ink text-white font-mono font-bold px-2 py-0.5 flex justify-between">
            <span>101 SERVICIOS HOGAR</span>
            <span>CÓD. 101</span>
          </div>
          <div class="dense-text-ad border-b border-gray-200 pb-2">
            <span class="font-bold uppercase">PLOMERO GASISTA MATRICULADO:</span> Instalaciones de agua, gas, calefacción, limpieza de radiadores. Tel: 644-112-233.
          </div>
          <div class="dense-text-ad border-b border-gray-200 pb-2">
            <span class="font-bold uppercase">CERRAJERÍA URGENTE 24H:</span> Apertura de puertas, cambio de bombines, cajas fuertes. Sin romper. Tel: 600-554-321.
          </div>
          <div class="dense-text-ad">
            <span class="font-bold uppercase">REPARACIÓN DE LAVARROPAS:</span> Repuestos originales. Todas las marcas. Trabajos con garantía. Tel: 622-009-887.
          </div>
        </div>

        <div class="border-r border-gray-300 pr-3 space-y-3">
          <div class="bg-ink text-white font-mono font-bold px-2 py-0.5 flex justify-between">
            <span>202 VIVIENDA Y LOCALES</span>
            <span>CÓD. 202</span>
          </div>
          <div class="dense-text-ad border-b border-gray-200 pb-2">
            <span class="font-bold uppercase">ALQUILER LOCAL COMERCIAL:</span> 120m², centro céntrico, salida de humos, escaparate amplio. Tel: 688-990-011.
          </div>
          <div class="dense-text-ad border-b border-gray-200 pb-2">
            <span class="font-bold uppercase">VENDO PARCELA RÚSTICA:</span> 2.500m² con agua de pozo, acceso asfaltado. Ideal fin de semana. Tel: 655-123-456.
          </div>
          <div class="dense-text-ad">
            <span class="font-bold uppercase">OPORTUNIDAD PISO:</span> 2 dorm, reformas recientes, ascensor. Valencia centro. 135.000€. Tel: 611-334-556.
          </div>
        </div>

        <div class="border-r border-gray-300 pr-3 space-y-3">
          <div class="bg-ink text-white font-mono font-bold px-2 py-0.5 flex justify-between">
            <span>303 MOTOR & ACCESORIOS</span>
            <span>CÓD. 303</span>
          </div>
          <div class="dense-text-ad border-b border-gray-200 pb-2">
            <span class="font-bold uppercase">COMPRO COCHES USADOS:</span> Pago al contado en el acto. Con o sin ITV, embargos o averías. Tel: 699-887-766.
          </div>
          <div class="dense-text-ad border-b border-gray-200 pb-2">
            <span class="font-bold uppercase">NEUMÁTICOS OCASIÓN:</span> Primeras marcas al 80% de vida útil. Montaje y equilibrado gratis. Tel: 911-223-344.
          </div>
          <div class="dense-text-ad">
            <span class="font-bold uppercase">MOTO YAMAHA MT-07:</span> Año 2021, 15.000km, limitada para carnet A2, estado impecable. 5.900€. Tel: 677-443-221.
          </div>
        </div>

        <div class="space-y-3">
          <div class="bg-slate-900 text-white font-mono font-bold px-2 py-0.5 flex justify-between">
            <span>404 EDICTOS BOE</span>
            <span>CÓD. 404</span>
          </div>
          <div class="dense-text-ad border-b border-gray-200 pb-2">
            <span class="font-bold uppercase">AYUNTAMIENTO CONVOCATORIA:</span> Procedimiento de licitación para concesión de servicio municipal. Ref: BOE-B-2026-3012.
          </div>
          <div class="dense-text-ad border-b border-gray-200 pb-2">
            <span class="font-bold uppercase">SUBASSTA JUDICIAL MADRID:</span> Subasta de vivienda urbana en calle Velázquez. Ref: BOE-A-2026-9918.
          </div>
          <div class="dense-text-ad">
            <span class="font-bold uppercase">BORME CONVOCATORIA JUNTA:</span> Se cita a los accionistas para la junta general ordinaria. Ref: BORME-1102.
          </div>
        </div>
      </div>
    </div>
  </section>

  <!-- CONTENIDO PRINCIPAL: LA CUADRÍCULA DE MODELOS (BENTO GRID MASIVO CON URLS LIMPIAS SEO) -->
  <main class="max-w-7xl mx-auto px-4">
    <div class="flex justify-between items-center mb-4 pb-2 border-b border-gray-300">
      <h3 class="font-news text-xl font-bold italic text-ink flex items-center gap-2">
        <i class="fa-solid fa-table-cells"></i> Módulos Publicados en AVISOS CLASIFICADOS & CUPÓNES
      </h3>
      <span id="results-count" class="text-xs bg-ink text-white font-bold px-2.5 py-1 rounded">
        Mostrando avisos
      </span>
    </div>

    <!-- GRID MASONRY RECUADROS MULTICOLUMNA -->
    <div id="grid-container" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
    </div>

    <!-- BOTÓN DE CARGA PROGRESIVA Y SCROLL INFINITO EN PORTADA -->
    <div class="mt-8 text-center" id="load-more-container">
      <button onclick="loadMoreItems()" class="bg-amber-400 hover:bg-amber-300 text-slate-950 font-bold font-mono text-sm px-6 py-3 rounded-lg border-2 border-black shadow-lg transition transform hover:-translate-y-0.5 inline-flex items-center gap-2">
        <i class="fa-solid fa-square-plus text-base"></i> Cargar Más Avisos, Edictos y Cupones (<span id="load-more-counter">24 más</span>)
      </button>
      <p class="text-xs text-gray-500 mt-2 font-news italic">Móstrando avisos en portada. Navega en las categorías superiores para explorar el directorio completo.</p>
    </div>
  </main>

  <!-- FOOTER -->
  <footer class="max-w-7xl mx-auto px-4 mt-12 pt-8 border-t-4 border-ink">
    <div class="grid grid-cols-1 md:grid-cols-3 gap-8 pb-8 text-sm">
      <div>
        <h4 id="footer-brand-title" class="font-masthead font-bold text-lg mb-2">CLASSIFIED ADS <span class="text-newsred">&</span> COUPONS</h4>
        <p id="footer-brand-desc" class="font-news text-xs text-gray-600 italic mb-3">
          Digital platform indexing verified local classifieds, supermarket flyers, retail coupons, and official public notices.
        </p>
        <span id="footer-brand-badge" class="inline-block bg-slate-900 text-amber-400 text-[11px] font-mono font-bold px-2 py-0.5 rounded border border-amber-400">
          <i class="fa-solid fa-shield-halved mr-1"></i> CCPA & FTC Compliance
        </span>
      </div>
      <div>
        <h5 id="press-sections-title" class="font-bold uppercase text-xs tracking-wider mb-3 border-b border-gray-400 pb-1">Press Sections</h5>
        <ul id="press-sections-list" class="space-y-1.5 text-xs text-gray-700 font-medium">
          <li><a href="javascript:void(0)" onclick="setCategory('edictos')" class="hover:underline">Federal Register & Official Notices</a></li>
          <li><a href="javascript:void(0)" onclick="setCategory('supermercado')" class="hover:underline">Supermarket Deals & Circulars</a></li>
          <li><a href="javascript:void(0)" onclick="setCategory('inmuebles')" class="hover:underline">Real Estate Directory</a></li>
          <li><a href="javascript:void(0)" onclick="setCategory('motor')" class="hover:underline">Automotive & Vehicles</a></li>
          <li><a href="javascript:void(0)" onclick="setCategory('servicios')" class="hover:underline">Professional Services Directory</a></li>
          <li><a href="javascript:void(0)" onclick="setCategory('cupones')" class="hover:underline">Discount Coupons & Promo Codes</a></li>
        </ul>
      </div>
      <div>
        <h5 id="footer-legal-title" class="font-bold uppercase text-xs tracking-wider mb-3 border-b border-gray-400 pb-1">Legal Information & CCPA</h5>
        <ul id="legal-links-list" class="space-y-1.5 text-xs text-gray-700 font-medium">
          <li><a href="/aviso_legal_us.html" class="hover:underline text-blue-900 font-bold"><i class="fa-solid fa-scale-balanced mr-1"></i> Legal Notice & Ownership</a></li>
          <li><a href="/privacidad_us.html" class="hover:underline text-emerald-800 font-bold"><i class="fa-solid fa-user-shield mr-1"></i> Privacy Policy (CCPA)</a></li>
          <li><a href="/cookies_us.html" class="hover:underline text-amber-800 font-bold"><i class="fa-solid fa-cookie-bite mr-1"></i> Cookie Policy & Disclosure</a></li>
          <li><a href="/terminos_us.html" class="hover:underline text-slate-800 font-bold"><i class="fa-solid fa-file-contract mr-1"></i> Terms of Use & DMCA</a></li>
        </ul>
      </div>
    </div>

    <div id="footer-copyright-text" class="text-center text-xs text-gray-500 border-t border-gray-300 pt-4 font-news italic pb-6">
      © 2026 CLASSIFIED ADS & COUPONS. Official US Portal operated by VORTICEPACIFICO ENGENHARIA LDA (NIPC PT518972895). Domain: https://classifiedads-coupons.cc. All rights reserved.
    </div>
  </footer>

  <!-- MODALS -->
  <div id="seo-modal" class="fixed inset-0 bg-black/60 backdrop-blur-sm hidden items-center justify-center p-4 z-50">
    <div class="bg-white rounded-lg max-w-lg w-full border-2 border-slate-900 p-6 shadow-2xl relative">
      <button onclick="closeSeoModal()" class="absolute top-3 right-3 text-gray-400 hover:text-gray-700 text-xl font-bold">&times;</button>
      <div class="border-b border-gray-200 pb-3 mb-4">
        <span class="bg-slate-900 text-amber-400 font-mono text-[10px] font-bold px-2 py-0.5 rounded">ENLACE OFICIAL</span>
        <h3 class="font-masthead text-xl font-bold text-ink mt-1">Enlace Directo & Datos Verificados</h3>
      </div>
      <div class="space-y-3 text-xs">
        <div>
          <label class="block font-bold text-gray-700 mb-1">Enlace Directo del Anuncio:</label>
          <input type="text" id="modal-seo-url" readonly class="w-full p-2 bg-gray-100 border border-gray-300 rounded font-mono text-[11px] text-blue-900 font-bold">
        </div>
        <div>
          <label class="block font-bold text-gray-700 mb-1">Ficha de Registro:</label>
          <pre id="modal-seo-schema" class="w-full p-2.5 bg-slate-900 text-emerald-400 rounded font-mono text-[10px] overflow-x-auto max-h-48 border border-slate-800"></pre>
        </div>
        <button onclick="closeSeoModal()" class="w-full bg-ink text-white font-bold py-2 rounded text-xs hover:bg-gray-800 transition">
          Cerrar Ventana
        </button>
      </div>
    </div>
  </div>

  <div id="api-modal" class="fixed inset-0 bg-black/60 backdrop-blur-sm hidden items-center justify-center p-4 z-50">
    <div class="bg-white rounded-lg max-w-md w-full border-2 border-slate-900 p-6 shadow-2xl relative">
      <button onclick="closeApiModal()" class="absolute top-3 right-3 text-gray-400 hover:text-gray-700 text-xl font-bold">&times;</button>
      <div class="border-b border-gray-200 pb-3 mb-4">
        <span class="bg-amber-400 text-slate-950 font-mono text-[10px] font-bold px-2 py-0.5 rounded">CONFIGURACIÓN API DE CUPONES</span>
        <h3 class="font-masthead text-xl font-bold text-ink mt-1">Conectar API de Cupones Externa</h3>
        <p class="text-xs text-gray-500">Introduce tu API Key de CouponAPI.org, LinkMyDeals o tu propio endpoint JSON</p>
      </div>

      <form onsubmit="handleSaveApi(event)" class="space-y-4 text-xs">
        <div>
          <label class="block font-bold text-gray-700 mb-1">API Key (CouponAPI.org / LinkMyDeals)</label>
          <input type="text" id="api-key-input" placeholder="Ej: 99a18b77c62d..." class="w-full p-2 border border-gray-300 rounded font-mono">
        </div>
        <div>
          <label class="block font-bold text-gray-700 mb-1">Endpoint REST API (JSON)</label>
          <input type="text" id="api-endpoint-input" placeholder="https://couponapi.org/api/getCoupons/" class="w-full p-2 border border-gray-300 rounded font-mono">
        </div>

        <div class="bg-blue-50 p-2.5 rounded border border-blue-200 text-blue-900 text-[11px] space-y-1">
          <p><i class="fa-solid fa-circle-info text-blue-600"></i> <strong>Modo Activo:</strong> Si la clave está vacía, el sistema usa el <em>Motor Simulado de API Cupones en Vivo</em>.</p>
        </div>

        <div class="flex gap-2 pt-2">
          <button type="submit" class="flex-1 bg-ink text-white font-bold py-2 rounded text-xs hover:bg-gray-800 transition">
            Guardar y Sincronizar
          </button>
          <button type="button" onclick="closeApiModal()" class="bg-gray-200 text-gray-800 font-bold px-4 py-2 rounded text-xs hover:bg-gray-300">
            Cancelar
          </button>
        </div>
      </form>
    </div>
  </div>

  <!-- MODAL DE CUPÓN INTERACTIVO CALL-TO-CLICK & RETENCIÓN DE USUARIOS -->
  <div id="coupon-modal" class="fixed inset-0 bg-black/70 backdrop-blur-sm hidden items-center justify-center p-4 z-50 overflow-y-auto">
    <div class="bg-white rounded-xl max-w-lg w-full border-4 border-red-600 p-6 shadow-2xl relative my-8">
      <button onclick="closeCouponModal()" class="absolute top-3 right-3 text-gray-400 hover:text-gray-700 text-2xl font-bold bg-gray-100 w-8 h-8 rounded-full flex items-center justify-center">&times;</button>
      
      <div class="text-center space-y-4">
        <!-- HEADER Y BADGE -->
        <div class="flex items-center justify-center gap-2 flex-wrap">
          <span class="inline-block bg-red-600 text-white text-xs font-black uppercase px-3 py-1 rounded-full shadow">
            CUPÓN TROQUELADO DIGITAL
          </span>
          <span id="modal-coupon-impressions" class="text-[11px] font-bold bg-amber-100 text-amber-900 border border-amber-300 px-2.5 py-0.5 rounded-full">
            <i class="fa-solid fa-fire text-newsred mr-1"></i> 1.482 impresiones hoy
          </span>
        </div>

        <h3 id="modal-coupon-title" class="font-masthead font-bold text-2xl text-ink leading-snug"></h3>
        <p id="modal-coupon-desc" class="text-xs text-gray-600 font-news italic px-2"></p>
        
        <!-- BARRITA DE URGENCIA / CUENTA REGRESIVA -->
        <div class="bg-red-50 border border-red-200 rounded-lg p-2 flex items-center justify-between text-xs text-red-950 font-bold px-4">
          <span><i class="fa-solid fa-fire text-red-600 mr-1.5 animate-pulse"></i> Oferta por Tiempo Limitado</span>
          <span class="font-mono bg-newsred text-white px-2 py-0.5 rounded text-[11px]"><i class="fa-regular fa-clock mr-1"></i> Caduca en <span id="coupon-timer">04:12:45</span></span>
        </div>

        <!-- RECUADRO TROQUELADO PRINCIPAL -->
        <div class="coupon-border p-4 rounded-xl relative bg-amber-50 shadow-inner">
          <span class="text-xs text-gray-500 uppercase font-mono font-bold block mb-1.5">CÓDIGO PROMOCIONAL / DESCUENTO</span>
          <div class="flex flex-col sm:flex-row items-center justify-center gap-3">
            <span id="modal-coupon-code" class="font-mono text-3xl font-black text-newsred tracking-widest bg-white px-4 py-2 rounded-lg border-2 border-dashed border-red-400 shadow"></span>
            <button onclick="copyCouponCode()" class="w-full sm:w-auto bg-newsred hover:bg-red-700 text-white text-sm font-extrabold px-5 py-3 rounded-lg shadow-md transition flex items-center justify-center gap-2 border-2 border-red-800 uppercase tracking-wide">
              <i class="fa-solid fa-scissors text-base"></i> Copiar Código Troquelado
            </button>
          </div>
        </div>

        <!-- CÓDIGO QR E INSTRUCCIÓN -->
        <div class="bg-gray-50 p-3 border border-gray-200 rounded-lg flex items-center justify-center gap-4">
          <img id="modal-coupon-qr" src="https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=CUPON-OFERTA-2026" alt="Código QR" class="w-24 h-24 border border-gray-300 p-1 bg-white shadow-sm rounded">
          <div class="text-left text-xs space-y-1">
            <p class="font-bold text-gray-900"><i class="fa-solid fa-qrcode text-red-600 mr-1"></i> Canjeable en Caja o Web</p>
            <p class="text-gray-500 text-[11px]">Muestra este código QR o introduce la clave en el carrito.</p>
            <p class="text-emerald-800 font-bold text-[11px]"><i class="fa-solid fa-circle-check mr-1 text-emerald-600"></i> Cupón Verificado y Activo</p>
          </div>
        </div>

        <!-- BOTONES DE ACCIÓN RÁPIDA CALL-TO-CLICK -->
        <div class="grid grid-cols-2 sm:grid-cols-4 gap-2 pt-1">
          <button onclick="printCurrentCoupon()" class="bg-slate-900 hover:bg-slate-800 text-white text-xs font-bold py-2 px-2 rounded-lg shadow transition flex items-center justify-center gap-1">
            <i class="fa-solid fa-print text-amber-400"></i> Imprimir PDF
          </button>
          <button onclick="shareCouponWhatsApp()" class="bg-emerald-600 hover:bg-emerald-700 text-white text-xs font-bold py-2 px-2 rounded-lg shadow transition flex items-center justify-center gap-1">
            <i class="fa-brands fa-whatsapp text-white"></i> WhatsApp
          </button>
          <button onclick="copyCouponLink()" class="bg-blue-600 hover:bg-blue-700 text-white text-xs font-bold py-2 px-2 rounded-lg shadow transition flex items-center justify-center gap-1">
            <i class="fa-solid fa-share-nodes text-white"></i> Compartir
          </button>
          <button onclick="redeemCouponOnline()" class="bg-amber-400 hover:bg-amber-300 text-slate-950 font-black text-xs py-2 px-2 rounded-lg shadow transition flex items-center justify-center gap-1 border border-black">
            <i class="fa-solid fa-arrow-up-right-from-square"></i> Usar Online
          </button>
        </div>

        <!-- INFORMACIÓN DE VALIDEZ Y UBICACIÓN -->
        <div class="text-left text-xs text-gray-600 space-y-1 bg-gray-100 p-2.5 rounded-lg font-news border border-gray-200">
          <p><i class="fa-solid fa-location-dot text-red-500 mr-1"></i> <strong>Validez Geográfica:</strong> <span id="modal-coupon-location"></span></p>
          <p><i class="fa-solid fa-calendar-check text-amber-600 mr-1"></i> <strong>Vencimiento Promoción:</strong> <span id="modal-coupon-expiry"></span></p>
        </div>

        <!-- BLOQUE DE RETENCIÓN: CUPONES RECOMENDADOS EN CADENA -->
        <div class="border-t-2 border-dashed border-gray-300 pt-3 text-left">
          <h4 class="font-bold text-xs text-gray-800 uppercase tracking-wide mb-2 flex items-center gap-1.5">
            <i class="fa-solid fa-fire-flame-curved text-newsred"></i> Quienes troquelaron este cupón también imprimieron:
          </h4>
          <div id="modal-recommended-coupons" class="grid grid-cols-3 gap-2">
            <!-- Renderizado dinámico de 3 cupones recomendados -->
          </div>
        </div>

        <button onclick="closeCouponModal()" class="w-full bg-gray-200 text-gray-800 font-bold py-2 text-xs rounded-lg hover:bg-gray-300 transition">
          Cerrar Ventana
        </button>
      </div>
    </div>
  </div>

  <div id="publish-modal" class="fixed inset-0 bg-black/60 backdrop-blur-sm hidden items-center justify-center p-4 z-50">
    <div class="bg-white rounded-lg max-w-lg w-full border-2 border-ink p-6 shadow-2xl relative max-h-[90vh] overflow-y-auto">
      <button onclick="closePublishModal()" class="absolute top-3 right-3 text-gray-400 hover:text-gray-700 text-xl font-bold">&times;</button>
      <div class="border-b border-gray-200 pb-3 mb-4">
        <h3 class="font-masthead text-2xl font-bold text-ink">PUBLICAR EN AVISOS CLASIFICADOS & CUPÓNES</h3>
        <p class="text-xs text-gray-500">Completa los datos de tu aviso clasificado, edicto oficial o cupón</p>
      </div>
      
      <form onsubmit="handlePublish(event)" class="space-y-4 text-xs">
        <div>
          <label class="block font-bold text-gray-700 mb-1">Tipo de Publicación</label>
          <div class="grid grid-cols-4 gap-2">
            <label class="border border-gray-300 p-1.5 rounded cursor-pointer flex items-center gap-1 hover:bg-gray-50 text-[11px]">
              <input type="radio" name="pub-type" value="clasificado" checked onclick="togglePubFields('clasificado')">
              <span>Breve</span>
            </label>
            <label class="border border-gray-300 p-1.5 rounded cursor-pointer flex items-center gap-1 hover:bg-gray-50 text-[11px]">
              <input type="radio" name="pub-type" value="oficial" onclick="togglePubFields('oficial')">
              <span>Edicto</span>
            </label>
            <label class="border border-gray-300 p-1.5 rounded cursor-pointer flex items-center gap-1 hover:bg-gray-50 text-[11px]">
              <input type="radio" name="pub-type" value="coupon" onclick="togglePubFields('coupon')">
              <span>Cupón</span>
            </label>
            <label class="border border-gray-300 p-1.5 rounded cursor-pointer flex items-center gap-1 hover:bg-gray-50 text-[11px]">
              <input type="radio" name="pub-type" value="supermarket" onclick="togglePubFields('supermarket')">
              <span>Folleto</span>
            </label>
          </div>
        </div>

        <div class="grid grid-cols-2 gap-3">
          <div>
            <label class="block font-bold text-gray-700 mb-1">Categoría / Sector</label>
            <select id="pub-category" class="w-full p-2 border border-gray-300 rounded">
              <option value="edictos">Edictos & Comunicados Oficiales</option>
              <option value="supermercado">Supermercados & Alimentación</option>
              <option value="hosteleria">Pizzerías & Bares</option>
              <option value="inmuebles">Inmuebles & Vivienda</option>
              <option value="motor">Motor & Talleres</option>
              <option value="servicios">Servicios & Gremios</option>
              <option value="opticas">Ópticas & Salud</option>
              <option value="veterinaria">Veterinarios</option>
              <option value="cupones">Cupones Troquelados</option>
            </select>
          </div>
          <div>
            <label class="block font-bold text-gray-700 mb-1">País / Cobertura</label>
            <select id="pub-country" class="w-full p-2 border border-gray-300 rounded">
              <option value="es">🇪🇸 España</option>
              <option value="pt">🇵🇹 Portugal</option>
              <option value="fr">🇫🇷 Francia</option>
              <option value="nl">🇳🇱 Países Bajos</option>
              <option value="uk">🇬🇧 Reino Unido</option>
              <option value="us">🇺🇸 EE.UU. / Internacional</option>
            </select>
          </div>
        </div>

        <div>
          <label class="block font-bold text-gray-700 mb-1">Título del Anuncio / Edicto / Oferta</label>
          <input type="text" id="pub-title" required placeholder="Ej: Edicto Convocatoria Junta / 2x1 en Pizzas / SEAT León" class="w-full p-2 border border-gray-300 rounded">
        </div>

        <div>
          <label class="block font-bold text-gray-700 mb-1">Texto del Aviso (Estilo Clasificado o Edicto)</label>
          <textarea id="pub-desc" rows="3" required placeholder="Texto completo, referencias oficiales, teléfono o condiciones..." class="w-full p-2 border border-gray-300 rounded"></textarea>
        </div>

        <div class="grid grid-cols-2 gap-3">
          <div>
            <label class="block font-bold text-gray-700 mb-1">Precio / % Dto / Ref. Oficial</label>
            <input type="text" id="pub-price" placeholder="Ej: Ref: ED-2026 / 12.500€ / -25% DTO" class="w-full p-2 border border-gray-300 rounded">
          </div>
          <div>
            <label class="block font-bold text-gray-700 mb-1">Teléfono / Email de Contacto</label>
            <input type="text" id="pub-phone" placeholder="Ej: +34 600 000 000" class="w-full p-2 border border-gray-300 rounded">
          </div>
        </div>

        <div id="coupon-extra-fields" class="hidden bg-red-50 p-3 rounded border border-red-200 space-y-2">
          <label class="block font-bold text-newsred mb-1">Código del Cupón Promocional</label>
          <input type="text" id="pub-code" placeholder="Ej: PROMO2026 / OFERTA15" class="w-full p-2 border border-red-300 rounded bg-white">
        </div>

        <button type="submit" class="w-full bg-newsred text-white font-bold py-2.5 rounded text-sm hover:bg-red-700 transition shadow">
          Publicar Anuncio Inmediatamente
        </button>
      </form>
    </div>
  </div>

  <!-- MODAL DE SITEMAPS XML Y ROBOTS.TXT -->
  <div id="sitemap-modal" class="fixed inset-0 bg-black/70 z-50 hidden items-center justify-center p-4">
    <div class="bg-white rounded-lg border-2 border-ink max-w-4xl w-full p-5 max-h-[90vh] overflow-y-auto shadow-2xl">
      <div class="flex justify-between items-center border-b border-gray-200 pb-3 mb-4">
        <h3 class="font-masthead text-lg font-bold text-ink flex items-center gap-2">
          <i class="fa-solid fa-sitemap text-amber-500"></i> Centro de Indexación SEO, Sitemaps XML & Robots.txt
        </h3>
        <button onclick="closeSitemapModal()" class="text-gray-500 hover:text-black font-bold text-xl">&times;</button>
      </div>

      <p class="text-xs text-gray-600 mb-4 font-news">
        Generación dinámica de sitemaps XML cumpliendo con los estándares de Google, Bing y Yahoo. Capacidad total estimada: <strong>66.248 URLs indexables</strong>.
      </p>

      <div class="grid grid-cols-2 sm:grid-cols-6 gap-1.5 mb-4">
        <button onclick="switchSitemapTab('index')" id="tab-sitemap-index" class="px-2 py-1.5 text-xs font-bold rounded bg-amber-400 text-black border border-black shadow">
          Index XML
        </button>
        <button onclick="switchSitemapTab('es')" id="tab-sitemap-es" class="px-2 py-1.5 text-xs font-bold rounded bg-gray-100 text-gray-700 hover:bg-gray-200 border border-gray-300">
          🇪🇸 /es/
        </button>
        <button onclick="switchSitemapTab('pt')" id="tab-sitemap-pt" class="px-2 py-1.5 text-xs font-bold rounded bg-gray-100 text-gray-700 hover:bg-gray-200 border border-gray-300">
          🇵🇹 /pt/
        </button>
        <button onclick="switchSitemapTab('fr')" id="tab-sitemap-fr" class="px-2 py-1.5 text-xs font-bold rounded bg-gray-100 text-gray-700 hover:bg-gray-200 border border-gray-300">
          🇫🇷 /fr/
        </button>
        <button onclick="switchSitemapTab('uk')" id="tab-sitemap-uk" class="px-2 py-1.5 text-xs font-bold rounded bg-gray-100 text-gray-700 hover:bg-gray-200 border border-gray-300">
          🇬🇧 /uk/
        </button>
        <button onclick="switchSitemapTab('robots')" id="tab-sitemap-robots" class="px-2 py-1.5 text-xs font-bold rounded bg-gray-100 text-gray-700 hover:bg-gray-200 border border-gray-300">
          robots.txt
        </button>
      </div>

      <div class="relative bg-slate-900 text-amber-300 p-4 rounded-lg font-mono text-xs overflow-x-auto max-h-80 border border-slate-800">
        <pre id="sitemap-modal-code" class="whitespace-pre-wrap"></pre>
      </div>

      <div class="mt-4 flex flex-wrap justify-between items-center gap-2">
        <span class="text-[11px] text-gray-500 font-mono">Estado: <span class="inline-block w-2 h-2 rounded-full bg-emerald-500 mr-1"></span> Servidor Local Backend Activo en http://localhost:3000</span>
        <div class="flex gap-2">
          <button onclick="copySitemapCode()" class="bg-gray-800 hover:bg-gray-700 text-white text-xs font-bold px-3 py-1.5 rounded transition flex items-center gap-1">
            <i class="fa-solid fa-copy"></i> Copiar Código
          </button>
          <button onclick="downloadSitemapCurrent()" class="bg-amber-400 hover:bg-amber-300 text-black text-xs font-bold px-3 py-1.5 rounded transition border border-black shadow flex items-center gap-1">
            <i class="fa-solid fa-download"></i> Descargar Archivo
          </button>
        </div>
      </div>
    </div>
  </div>

  <script>
    
        let currentCountryCode = 'us';

    
    function updateCurrentMonthDisplay(code = 'us') {
      const dateEl = document.getElementById('current-month-text');
      if (!dateEl) return;
      
      const now = new Date();
      const locales = {
        us: 'en-US',
        uk: 'en-GB',
        es: 'es-ES',
        pt: 'pt-PT',
        fr: 'fr-FR',
        nl: 'nl-NL'
      };
      
      const locale = locales[code] || locales['us'];
      const monthName = now.toLocaleDateString(locale, { month: 'long' });
      const year = now.getFullYear();
      const capitalizedMonth = monthName.charAt(0).toUpperCase() + monthName.slice(1);
      
      if (code === 'es' || code === 'pt') {
        dateEl.innerText = `${capitalizedMonth} de ${year}`;
      } else {
        dateEl.innerText = `${capitalizedMonth} ${year}`;
      }
    }

    function getCountryDatasetSync(code) {
      if (code === 'es') {
        if (typeof window !== 'undefined' && window.spainInitialData) return window.spainInitialData;
        if (typeof window !== 'undefined' && window.esDataset) return window.esDataset;
        if (typeof spainInitialData !== 'undefined') return spainInitialData;
        return null;
      }
      const key = code + 'Dataset';
      if (typeof window !== 'undefined' && window[key]) return window[key];
      try {
        const direct = eval('typeof ' + key + ' !== "undefined" ? ' + key + ' : null');
        if (direct) return direct;
      } catch (e) {}
      return null;
    }

    // Dynamic on-demand dataset loader
    function loadCountryDataset(code, callback) {
      const existing = getCountryDatasetSync(code);
      if (existing && existing.length > 0) {
        return callback(existing);
      }

      const s = document.createElement('script');
      s.src = `/${code === 'es' ? 'esDataset' : code + 'Dataset'}.js`;
      s.onload = () => {
        const d = getCountryDatasetSync(code);
        callback(d || []);
      };
      s.onerror = (err) => {
        console.error('Error cargando dataset para ' + code, err);
        callback([]);
      };
      document.head.appendChild(s);
    }

    function switchCountry(code) {
      currentCountryCode = code;
      const brandTitleEl = document.getElementById('brand-main-title');
      const brandTitles = {
        us: 'CLASSIFIED ADS <span class="text-newsred">&</span> COUPONS',
        es: 'AVISOS CLASIFICADOS <span class="text-newsred">&</span> CUPÓNES',
        pt: 'ANÚNCIOS CLASSIFICADOS <span class="text-newsred">&</span> CUPÕES',
        fr: 'ANNONCES CLASSÉES <span class="text-newsred">&</span> COUPONS',
        uk: 'CLASSIFIED ADS <span class="text-newsred">&</span> COUPONS',
        nl: 'GECLASSIFICEERDE ADVERTENTIES <span class="text-newsred">&</span> COUPONS'
      };

      if (brandTitleEl) brandTitleEl.innerHTML = brandTitles[code] || brandTitles['us'];

      ['us', 'es', 'pt', 'fr', 'uk', 'nl'].forEach(c => {
        const btn = document.getElementById('country-btn-' + c);
        if (btn) {
          if (c === code) {
            btn.className = "bg-slate-900 text-amber-400 border border-slate-950 px-2.5 py-1 rounded text-xs font-bold transition shadow-sm";
          } else {
            btn.className = "bg-white text-slate-800 hover:bg-slate-100 border border-gray-300 px-2.5 py-1 rounded text-xs font-semibold transition";
          }
        }
      });

      const countryFooterData = {
        us: {
          legalTitle: 'Legal Information & CCPA',
          noticeUrl: '/aviso_legal_us.html',
          privacyUrl: '/privacidad_us.html',
          cookiesUrl: '/cookies_us.html',
          termsUrl: '/terminos_us.html',
          notice: 'Legal Notice & Ownership',
          privacy: 'Privacy Policy (CCPA)',
          cookies: 'Cookie Policy & Disclosure',
          terms: 'Terms of Use & DMCA',
          pressTitle: 'Press Sections',
          pressList: [
            { cat: 'edictos', label: 'Federal Register & Official Notices' },
            { cat: 'supermercado', label: 'Supermarket Deals & Circulars' },
            { cat: 'inmuebles', label: 'Real Estate Directory' },
            { cat: 'motor', label: 'Automotive & Vehicles' },
            { cat: 'servicios', label: 'Professional Services' },
            { cat: 'cupones', label: 'Coupons & Promo Codes' }
          ],
          copyright: '© 2026 CLASSIFIED ADS & COUPONS. Official US Portal operated by VORTICEPACIFICO ENGENHARIA LDA (NIPC PT518972895). Domain: https://classifiedads-coupons.cc. All rights reserved.',
          badge: '<i class="fa-solid fa-shield-halved mr-1"></i> CCPA & FTC Compliance',
          desc: 'Digital platform indexing verified local classifieds, supermarket flyers, retail coupons, and official public notices in the United States.'
        },
        es: {
          legalTitle: 'Información Legal & RGPD',
          noticeUrl: '/es/aviso_legal.html',
          privacyUrl: '/es/privacidad.html',
          cookiesUrl: '/es/cookies.html',
          termsUrl: '/es/terminos.html',
          notice: 'Aviso Legal & Titularidad',
          privacy: 'Política de Privacidad (RGPD)',
          cookies: 'Política de Cookies (AEPD)',
          terms: 'Términos de Publicación BOE',
          pressTitle: 'Secciones de Prensa',
          pressList: [
            { cat: 'edictos', label: 'Edictos & Comunicados BOE' },
            { cat: 'supermercado', label: 'Supermercados & Ofertas' },
            { cat: 'inmuebles', label: 'Guía Inmobiliaria' },
            { cat: 'motor', label: 'Motor & Automoción' },
            { cat: 'servicios', label: 'Guía de Servicios Profesional' },
            { cat: 'cupones', label: 'Cupones & Ofertas Troqueladas' }
          ],
          copyright: '© 2026 AVISOS CLASIFICADOS & CUPÓNES. Dominio oficial España: https://classifiedads-coupons.cc/es/ - VORTICEPACIFICO ENGENHARIA LDA (NIPC PT518972895). Todos los derechos reservados.',
          badge: '<i class="fa-solid fa-shield-halved mr-1"></i> Cumplimiento RGPD & LSSI',
          desc: 'Plataforma digital que une prensa impresa, edictos oficiales del BOE, comercios de barrio y folletos de oferta en España.'
        },
        pt: {
          legalTitle: 'Informação Legal & RGPD',
          noticeUrl: '/pt/aviso_legal.html',
          privacyUrl: '/pt/privacidade.html',
          cookiesUrl: '/pt/cookies.html',
          termsUrl: '/pt/termos.html',
          notice: 'Aviso Legal & Titularidade',
          privacy: 'Política de Privacidade (RGPD)',
          cookies: 'Política de Cookies (e-Privacy)',
          terms: 'Termos de Publicação DRE',
          pressTitle: 'Secções de Imprensa',
          pressList: [
            { cat: 'edictos', label: 'Avisos & Comunicados DRE' },
            { cat: 'supermercado', label: 'Supermercados & Promoções' },
            { cat: 'inmuebles', label: 'Guia Imobiliário' },
            { cat: 'motor', label: 'Automóveis & Veículos' },
            { cat: 'servicios', label: 'Serviços Profissionais' },
            { cat: 'cupones', label: 'Cupões de Desconto' }
          ],
          copyright: '© 2026 ANÚNCIOS CLASSIFICADOS & CUPÕES. Domínio oficial Portugal: https://classifiedads-coupons.cc/pt/ - VORTICEPACIFICO ENGENHARIA LDA (NIPC PT518972895). Todos os direitos reservados.',
          badge: '<i class="fa-solid fa-shield-halved mr-1"></i> Conformidade DL 7/2004 & RGPD',
          desc: 'Plataforma digital agregadora de anúncios classificados, cupões de desconto e avisos oficiais do Diário da República em Portugal.'
        },
        fr: {
          legalTitle: 'Informations Légales & RGPD',
          noticeUrl: '/fr/aviso_legal.html',
          privacyUrl: '/fr/privatite.html',
          cookiesUrl: '/fr/cookies.html',
          termsUrl: '/fr/conditions.html',
          notice: 'Mentions Légales & Éditeur',
          privacy: 'Politique de Confidentialité (CNIL)',
          cookies: 'Gestion des Cookies (CNIL)',
          terms: 'Conditions Générales (CGU)',
          pressTitle: 'Rubriques de Presse',
          pressList: [
            { cat: 'edictos', label: 'Annonces Légales BODACC' },
            { cat: 'supermercado', label: 'Supermarchés & Catalogues' },
            { cat: 'inmuebles', label: 'Immobilier & Logement' },
            { cat: 'motor', label: 'Auto & Moto' },
            { cat: 'servicios', label: 'Services Professionnels' },
            { cat: 'cupones', label: 'Coupons de Réduction' }
          ],
          copyright: '© 2026 ANNONCES CLASSÉES & COUPONS. Domaine officiel France: https://classifiedads-coupons.cc/fr/ - VORTICEPACIFICO ENGENHARIA LDA (NIPC PT518972895). Tous droits réservés.',
          badge: '<i class="fa-solid fa-shield-halved mr-1"></i> Conformité LCEN & RGPD CNIL',
          desc: 'Plateforme numérique d\'annonces classées, promotions de supermarchés et annonces légales officielles du BODACC en France.'
        },
        uk: {
          legalTitle: 'Legal Information & UK-GDPR',
          noticeUrl: '/uk/aviso_legal.html',
          privacyUrl: '/uk/privacy.html',
          cookiesUrl: '/uk/cookies.html',
          termsUrl: '/uk/terms.html',
          notice: 'Legal Notice & Ownership',
          privacy: 'Privacy Policy (UK-GDPR)',
          cookies: 'Cookie Policy (PECR)',
          terms: 'Terms of Service & Gazette',
          pressTitle: 'Press Sections',
          pressList: [
            { cat: 'edictos', label: 'The Gazette Public Notices' },
            { cat: 'supermercado', label: 'Supermarket Offers & Circulars' },
            { cat: 'inmuebles', label: 'Property & Real Estate' },
            { cat: 'motor', label: 'Motors & Vehicles' },
            { cat: 'servicios', label: 'Professional Directory' },
            { cat: 'cupones', label: 'Vouchers & Promo Codes' }
          ],
          copyright: '© 2026 CLASSIFIED ADS & COUPONS. Official UK Portal operated by VORTICEPACIFICO ENGENHARIA LDA (NIPC PT518972895). Domain: https://classifiedads-coupons.cc/uk/. All rights reserved.',
          badge: '<i class="fa-solid fa-shield-halved mr-1"></i> UK-GDPR & ICO Compliance',
          desc: 'Digital portal for verified UK local classifieds, supermarket discounts, promotional vouchers, and public notices in the United Kingdom.'
        },
        nl: {
          legalTitle: 'Juridische Informatie & AVG',
          noticeUrl: '/nl/aviso_legal.html',
          privacyUrl: '/nl/privacy.html',
          cookiesUrl: '/nl/cookies.html',
          termsUrl: '/nl/voorwaarden.html',
          notice: 'Juridische Kennisgeving (BW)',
          privacy: 'Privacybeleid (AVG / AP)',
          cookies: 'Cookiebeleid (Telecommunicatiewet)',
          terms: 'Voorwaarden Staatscourant',
          pressTitle: 'Perssecties',
          pressList: [
            { cat: 'edictos', label: 'Staatscourant Bekendmakingen' },
            { cat: 'supermercado', label: 'Supermarkt Folders & Deals' },
            { cat: 'inmuebles', label: 'Vastgoed & Woningen' },
            { cat: 'motor', label: 'Auto & Voertuigen' },
            { cat: 'servicios', label: 'Professionele Gids' },
            { cat: 'cupones', label: 'Kortingsbonnen & Codes' }
          ],
          copyright: '© 2026 GECLASSIFICEERDE ADVERTENTIES & COUPONS. Officiëel domein Nederland: https://classifiedads-coupons.cc/nl/ - VORTICEPACIFICO ENGENHARIA LDA (NIPC PT518972895). Alle rechten voorbehouden.',
          badge: '<i class="fa-solid fa-shield-halved mr-1"></i> Nakoming AVG & AP',
          desc: 'Digitaal platform voor geclassificeerde advertenties, supermarkt folders, kortingscodes en officiële bekendmakingen uit de Staatscourant.'
        }
      };

      const leg = countryFooterData[code] || countryFooterData['us'];
      const legalLinksContainer = document.getElementById('legal-links-list');
      const footerLegalTitle = document.getElementById('footer-legal-title');
      const pressSectionsTitle = document.getElementById('press-sections-title');
      const pressSectionsList = document.getElementById('press-sections-list');
      const footerCopyrightText = document.getElementById('footer-copyright-text');
      const footerBrandBadge = document.getElementById('footer-brand-badge');
      const footerBrandDesc = document.getElementById('footer-brand-desc');

      if (footerLegalTitle) footerLegalTitle.innerText = leg.legalTitle;
      if (pressSectionsTitle) pressSectionsTitle.innerText = leg.pressTitle;
      if (footerCopyrightText) footerCopyrightText.innerText = leg.copyright;
      if (footerBrandBadge) footerBrandBadge.innerHTML = leg.badge;
      if (footerBrandDesc) footerBrandDesc.innerText = leg.desc;

      if (legalLinksContainer) {
        legalLinksContainer.innerHTML = `
          <li><a href="${leg.noticeUrl}" class="hover:underline text-blue-900 font-bold"><i class="fa-solid fa-scale-balanced mr-1"></i> ${leg.notice}</a></li>
          <li><a href="${leg.privacyUrl}" class="hover:underline text-emerald-800 font-bold"><i class="fa-solid fa-user-shield mr-1"></i> ${leg.privacy}</a></li>
          <li><a href="${leg.cookiesUrl}" class="hover:underline text-amber-800 font-bold"><i class="fa-solid fa-cookie-bite mr-1"></i> ${leg.cookies}</a></li>
          <li><a href="${leg.termsUrl}" class="hover:underline text-slate-800 font-bold"><i class="fa-solid fa-file-contract mr-1"></i> ${leg.terms}</a></li>
        `;
      }

      if (pressSectionsList) {
        pressSectionsList.innerHTML = leg.pressList.map(p => `
          <li><a href="javascript:void(0)" onclick="setCategory('${p.cat}')" class="hover:underline">${p.label}</a></li>
        `).join('');
      }

      
      updateCurrentMonthDisplay(code);

      loadCountryDataset(code, (loadedData) => {
        if (loadedData && loadedData.length > 0) {
          dataset = loadedData;
        }
        filterItems();
      });
    }

    const initialPath = window.location.pathname.toLowerCase();
    let initialCountryCode = 'us';
    if (initialPath.startsWith('/es') || initialPath.includes('/es/')) initialCountryCode = 'es';
    else if (initialPath.startsWith('/pt') || initialPath.includes('/pt/')) initialCountryCode = 'pt';
    else if (initialPath.startsWith('/fr') || initialPath.includes('/fr/')) initialCountryCode = 'fr';
    else if (initialPath.startsWith('/uk') || initialPath.includes('/uk/')) initialCountryCode = 'uk';
    else if (initialPath.startsWith('/nl') || initialPath.includes('/nl/')) initialCountryCode = 'nl';
    else if (initialPath.startsWith('/us') || initialPath.includes('/us/')) initialCountryCode = 'us';

    currentCountryCode = initialCountryCode;

    let dataset = getCountryDatasetSync(initialCountryCode) || [];
    let currentCategory = 'all';
    let currentCity = 'all';

    // SINCRONIZAR TODAS LAS APIS (BOE + CUPONES)
    async function syncAllApis() {
      const statusBadge = document.getElementById('api-status-badge');
      if (statusBadge) {
        statusBadge.innerText = 'Cargando APIS...';
        statusBadge.className = 'text-amber-400 font-mono animate-pulse';
      }

      const country = currentCountryCode || 'us';
      
      try {
        // Fetch en paralelo de Boletines Oficiales Multi-País + Cupones API
        const [apiCoupons, officialEdicts] = await Promise.all([
          window.couponClient ? window.couponClient.fetchCoupons(country) : Promise.resolve([]),
          window.multiCountryClient ? window.multiCountryClient.fetchEdictsByCountry(country) : Promise.resolve([])
        ]);

        if (officialEdicts && officialEdicts.length > 0) {
          const newEdicts = officialEdicts.filter(b => !dataset.some(existing => String(existing.id) === String(b.id)));
          dataset = [...newEdicts, ...dataset];
        }

        if (apiCoupons && apiCoupons.length > 0) {
          const newCoupons = apiCoupons.filter(c => !dataset.some(existing => String(existing.id) === String(c.id)));
          dataset = [...newCoupons, ...dataset];
        }

        const counterEl = document.getElementById('seo-total-counter');
        if (counterEl && window.seoRouter) {
          const stats = window.seoRouter.getSitemapStats();
          counterEl.innerText = `${stats.totalGenerated} URLs Indexables`;
        }

        if (statusBadge) {
          statusBadge.innerText = `APIS Conectadas (${dataset.length} Módulos Cargados)`;
          statusBadge.className = 'text-green-400 font-mono font-bold';
        }
      } catch (err) {
        console.warn('Resguardo de sincronización API:', err);
      }

      filterItems();
    }

    let displayedLimit = 350;

    function loadMoreItems() {
      displayedLimit += 30;
      filterItems();
    }

        function createCardElement(item) {
      const card = document.createElement('div');
      
      if (item.type === 'oficial') {
        const effectiveSize = (item.img && item.size && item.size.includes('col-span-2')) ? item.size : 'col-span-1';
        card.className = `official-border p-4 rounded-lg shadow-sm hover:shadow-md transition flex flex-col justify-between ${effectiveSize}`;
        card.innerHTML = `
          <div>
            <div class="flex justify-between items-start mb-2 border-b border-blue-200 pb-1.5">
              <span class="text-[10px] font-bold uppercase px-2 py-0.5 rounded bg-blue-900 text-white">
                <i class="fa-solid fa-building-columns mr-1"></i> ${item.badge}
              </span>
              <span class="text-[11px] font-mono text-blue-900 font-bold">
                <i class="fa-regular fa-image mr-1"></i> ${item.date || 'Oficial'}
              </span>
            </div>
            <h4 class="font-bold text-sm text-blue-950 uppercase tracking-tight mb-1">
              ${item.title}
            </h4>
            ${item.subtitle ? `<h5 class="font-semibold text-xs text-blue-900 mb-2 italic font-news">${item.subtitle}</h5>` : ''}
            <p class="text-xs text-slate-700 font-news leading-relaxed mb-3 bg-white p-2.5 rounded border border-slate-200">
              ${item.desc}
            </p>
          </div>
          <div class="pt-2 border-t border-blue-200 flex justify-between items-center text-xs">
            <button onclick="inspectSeoUrl('${item.id}')" aria-label="Direct link" class="text-[11px] font-mono text-blue-900 hover:underline flex items-center gap-1 font-bold">
              <i class="fa-solid fa-link"></i> Direct link
            </button>
            <span class="font-mono text-[11px] font-bold text-blue-900">${item.price}</span>
          </div>
        `;
      }
      else if (item.type === 'coupon') {
        const effectiveSize = (item.img && item.size && item.size.includes('col-span-2')) ? item.size : 'col-span-1';
        card.className = `coupon-card coupon-border p-4 rounded-xl shadow-sm hover:shadow-lg transition transform hover:-translate-y-0.5 flex flex-col justify-between ${effectiveSize} bg-amber-50/50`;
        let codeMasked = item.code ? (item.code.substring(0, 4) + '***') : 'CUP***';
        
        card.innerHTML = `
          <div>
            <div class="flex justify-between items-start mb-2">
              <span class="text-[10px] font-black uppercase px-2 py-0.5 rounded border ${item.badgeColor} shadow-xs">
                ${item.badge}
              </span>
              <span class="text-xs font-black text-white bg-newsred px-2 py-0.5 rounded shadow-xs">
                ${item.price}
              </span>
            </div>
            <h4 class="font-bold text-sm text-ink mb-1 hover:text-newsred cursor-pointer leading-snug" onclick="openCouponModal('${item.id}')">
              ${item.title}
            </h4>
            <p class="text-xs text-gray-600 font-news italic line-clamp-2 mb-2">
              ${item.desc}
            </p>
            
            <!-- RECUADRO CÓDIGO TROQUELADO -->
            <div onclick="openCouponModal('${item.id}')" class="bg-white border-2 border-dashed border-red-300 rounded-lg p-1.5 my-2 cursor-pointer hover:border-red-500 transition flex items-center justify-between px-3">
              <span class="text-[10px] text-gray-500 font-mono font-bold">CÓDIGO: <strong class="text-newsred">${codeMasked}</strong></span>
              <span class="text-[10px] font-bold text-amber-900 bg-amber-100 px-1.5 py-0.5 rounded">
                <i class="fa-solid fa-fire text-newsred mr-0.5"></i> Activo
              </span>
            </div>
          </div>

          <div class="pt-3 border-t border-dashed border-red-300 flex flex-col items-center gap-2">
            <button onclick="openCouponModal('${item.id}')" aria-label="Cut Coupon" class="w-full bg-newsred hover:bg-red-700 text-white text-sm font-extrabold py-2.5 px-4 rounded-lg shadow-md hover:shadow-lg transition flex items-center justify-center gap-2 border-2 border-red-800 uppercase tracking-wide cursor-pointer">
              <i class="fa-solid fa-scissors text-base"></i> Cut Coupon
            </button>
            <button onclick="inspectSeoUrl('${item.id}')" aria-label="Direct link" class="text-[10px] font-mono text-gray-500 hover:text-newsred hover:underline flex items-center gap-1 font-bold">
              <i class="fa-solid fa-link"></i> Direct link
            </button>
          </div>
        `;
      } 
      else if (item.type === 'supermarket') {
        const effectiveSize = (item.img && item.size && item.size.includes('col-span-2')) ? item.size : 'col-span-1';
        card.className = `bg-amber-50 border-2 border-amber-400 p-4 rounded-lg shadow flex flex-col justify-between ${effectiveSize}`;
        let imgHtml = item.img ? `<img src="${item.img}" alt="${item.title}" loading="lazy" decoding="async" class="w-full h-32 object-cover rounded mb-2 border border-amber-300">` : '';
        
        card.innerHTML = `
          <div>
            <div class="flex justify-between items-start mb-2">
              <span class="text-[10px] ${item.badgeColor} px-2 py-0.5 rounded">
                ${item.badge}
              </span>
              <span class="text-xs font-black text-slate-900 bg-amber-400 px-2 py-0.5 rounded border border-black">
                ${item.price}
              </span>
            </div>
            ${imgHtml}
            <h4 class="font-extrabold text-sm text-amber-950 mb-1 uppercase tracking-tight">
              ${item.title}
            </h4>
            <p class="text-xs text-amber-900 font-sans leading-relaxed mb-3">
              ${item.desc}
            </p>
          </div>
          <div class="pt-2 border-t border-amber-300 flex justify-between items-center text-xs">
            <span class="text-[11px] text-amber-800"><i class="fa-solid fa-store text-amber-600"></i> ${item.location}</span>
            <a href="tel:${item.phone}" class="bg-amber-500 hover:bg-amber-400 text-slate-950 text-xs font-black px-3 py-1 rounded shadow transition flex items-center gap-1 border border-black">
              <i class="fa-solid fa-cart-shopping"></i> Ver Oferta
            </a>
          </div>
        `;
      } 
      else {
        const effectiveSize = (item.img && item.size && item.size.includes('col-span-2')) ? item.size : 'col-span-1';
        card.className = `bg-white newspaper-border p-4 rounded shadow-sm hover:shadow-md transition flex flex-col justify-between ${effectiveSize}`;
        let imgHtml = item.img ? `<img src="${item.img}" alt="${item.title}" loading="lazy" decoding="async" class="w-full h-32 object-cover rounded mb-2 border border-gray-200">` : '';

        card.innerHTML = `
          <div>
            <div class="flex justify-between items-start mb-2">
              <span class="text-[10px] font-bold uppercase px-2 py-0.5 rounded border ${item.badgeColor}">
                ${item.badge}
              </span>
              <span class="text-xs font-bold text-gray-900 bg-gray-100 px-2 py-0.5 rounded border border-gray-300">
                ${item.price}
              </span>
            </div>
            ${imgHtml}
            <h4 class="font-bold text-sm text-ink mb-1 uppercase tracking-tight">
              ${item.title}
            </h4>
            <p class="text-xs text-gray-700 font-news leading-relaxed mb-3">
              ${item.desc}
            </p>
          </div>
          <div class="pt-2 border-t border-gray-200 flex justify-between items-center text-xs">
            <span class="text-[11px] text-gray-500"><i class="fa-solid fa-map-marker-alt text-gray-400"></i> ${item.location}</span>
            <a href="tel:${item.phone}" class="bg-ink text-white text-xs font-bold px-2.5 py-1 rounded hover:bg-gray-800 transition flex items-center gap-1">
              <i class="fa-solid fa-phone"></i> Contactar
            </a>
          </div>
        `;
      }
      return card;
    }

    let renderBatchTimer = null;
    function renderGrid(items) {
      if (renderBatchTimer) {
        clearTimeout(renderBatchTimer);
        renderBatchTimer = null;
      }
      const container = document.getElementById('grid-container');
      const countEl = document.getElementById('results-count');
      const loadMoreBtnContainer = document.getElementById('load-more-container');
      const loadMoreCounter = document.getElementById('load-more-counter');
      container.innerHTML = '';

      const visibleItems = items.slice(0, displayedLimit);
      countEl.innerText = `Mostrando ${visibleItems.length} de ${items.length} módulos`;

      if (displayedLimit < items.length) {
        if (loadMoreBtnContainer) loadMoreBtnContainer.classList.remove('hidden');
        if (loadMoreCounter) loadMoreCounter.innerText = `${Math.min(24, items.length - displayedLimit)} más`;
      } else {
        if (loadMoreBtnContainer) loadMoreBtnContainer.classList.add('hidden');
      }

      if (items.length === 0) {
        container.innerHTML = `
          <div class="col-span-full py-12 text-center bg-white border border-gray-300 rounded-lg">
            <i class="fa-solid fa-folder-open text-4xl text-gray-400 mb-3"></i>
            <h4 class="font-bold text-gray-700">No se encontraron anuncios o edictos en este filtro</h4>
            <p class="text-xs text-gray-500">Prueba ajustando los filtros de búsqueda, categoría o país.</p>
          </div>
        `;
        return;
      }

      // Initial fast paint chunk (16 items) for 0ms TBT and instant FCP/LCP
      const initialChunkSize = 16;
      const initialItems = visibleItems.slice(0, initialChunkSize);
      const remainingItems = visibleItems.slice(initialChunkSize);

      const frag = document.createDocumentFragment();
      initialItems.forEach(item => frag.appendChild(createCardElement(item)));
      container.appendChild(frag);

      // Smooth micro-batching for remaining cards - renders full 300+ items rapidly without freezing main thread
      if (remainingItems.length > 0) {
        const scheduleNext = () => {
          renderBatchTimer = setTimeout(() => {
            const nextBatch = remainingItems.splice(0, 48);
            const nextFrag = document.createDocumentFragment();
            nextBatch.forEach(item => nextFrag.appendChild(createCardElement(item)));
            container.appendChild(nextFrag);
            if (remainingItems.length > 0) {
              scheduleNext();
            }
          }, 8);
        };
        scheduleNext();
      }
    }

    function filterItems() {
      const searchInput = document.getElementById('search-input');
      const typeSelect = document.getElementById('type-select');
      const search = searchInput ? searchInput.value.toLowerCase() : '';
      const type = typeSelect ? typeSelect.value : 'all';

      const filtered = dataset.filter(item => {
        const itemCountry = (item.country || '').toLowerCase();
        const activeCountry = (currentCountryCode || 'us').toLowerCase();
        const matchesCountry = (itemCountry === activeCountry) || (!item.country && activeCountry === 'us');
        const matchesCat = (currentCategory === 'all') || 
                           (item.category === currentCategory) || 
                           (item.category && item.category.includes(currentCategory)) || 
                           (currentCategory && currentCategory.includes(item.category));
        const matchesType = (type === 'all') || (item.type === type);
        const matchesCity = (currentCity === 'all') || (item.location && item.location.toLowerCase().includes(currentCity.toLowerCase()));
        const matchesSearch = (item.title && item.title.toLowerCase().includes(search)) || 
                              (item.desc && item.desc.toLowerCase().includes(search)) ||
                              (item.location && item.location.toLowerCase().includes(search));

        return matchesCountry && matchesCat && matchesType && matchesCity && matchesSearch;
      });

      renderGrid(filtered);
    }

    function setCategory(cat) {
      currentCategory = cat;
      currentCity = 'all';
      displayedLimit = 350;
      filterItems();
    }

    function filterSector(sectorCat) {
      currentCategory = sectorCat;
      currentCity = 'all';
      displayedLimit = 350;
      filterItems();
      document.getElementById('grid-container').scrollIntoView({ behavior: 'smooth' });
    }

    function resetFilters() {
      const searchInput = document.getElementById('search-input');
      const typeSelect = document.getElementById('type-select');
      if (searchInput) searchInput.value = '';
      if (typeSelect) typeSelect.value = 'all';
      currentCategory = 'all';
      currentCity = 'all';
      displayedLimit = 350;
      filterItems();
    }

    function inspectSeoUrl(id) {
      const item = dataset.find(x => String(x.id) === String(id));
      if (!item) return;

      const cleanUrl = window.seoRouter.generateCleanUrl(item);
      const schemaJson = {
        "@context": "https://schema.org",
        "@type": item.type === 'coupon' ? "Offer" : "ClassifiedAd",
        "name": item.title,
        "description": item.desc,
        "areaServed": item.location,
        "url": cleanUrl
      };

      document.getElementById('modal-seo-url').value = cleanUrl;
      document.getElementById('modal-seo-schema').innerText = JSON.stringify(schemaJson, null, 2);
      
      const modal = document.getElementById('seo-modal');
      modal.classList.remove('hidden');
      modal.classList.add('flex');
    }

    function closeSeoModal() {
      const modal = document.getElementById('seo-modal');
      modal.classList.add('hidden');
      modal.classList.remove('flex');
    }

    let activeModalItem = null;
    let activeModalCode = '';
    let couponCountdownInterval = null;

    function openCouponModal(id) {
      const item = dataset.find(x => String(x.id) === String(id));
      if (!item) return;

      activeModalItem = item;
      activeModalCode = item.code || 'CUPON2026';

      document.getElementById('modal-coupon-title').innerText = item.title;
      document.getElementById('modal-coupon-desc').innerText = item.desc;
      document.getElementById('modal-coupon-code').innerText = activeModalCode;
      document.getElementById('modal-coupon-location').innerText = item.location;
      document.getElementById('modal-coupon-expiry').innerText = item.expiry || 'Hasta agotar existencias';

      // QR Code Dinámico
      const qrImg = document.getElementById('modal-coupon-qr');
      if (qrImg) {
        qrImg.src = `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(activeModalCode + '-' + item.title)}`;
      }

      // Contador de Impresiones en Vivo (Social Proof)
      const impEl = document.getElementById('modal-coupon-impressions');
      if (impEl) {
        const randomViews = Math.floor(Math.random() * 850) + 1150;
        impEl.innerHTML = `<i class="fa-solid fa-fire text-newsred mr-1"></i> ${randomViews.toLocaleString('es-ES')} impresiones hoy`;
      }

      // Temporizador de Urgencia (Cuenta regresiva)
      startCouponCountdown();

      // Generar Cupones Recomendados para Retención Continuada
      renderRecommendedCoupons(item);

      const modal = document.getElementById('coupon-modal');
      modal.classList.remove('hidden');
      modal.classList.add('flex');
    }

    function startCouponCountdown() {
      if (couponCountdownInterval) clearInterval(couponCountdownInterval);
      let totalSeconds = 4 * 3600 + 12 * 60 + 45; // 4 horas 12 mins 45 segs
      const timerEl = document.getElementById('coupon-timer');

      couponCountdownInterval = setInterval(() => {
        if (totalSeconds <= 0) {
          clearInterval(couponCountdownInterval);
          if (timerEl) timerEl.innerText = "¡Últimos minutos!";
          return;
        }
        totalSeconds--;
        const h = String(Math.floor(totalSeconds / 3600)).padStart(2, '0');
        const m = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0');
        const s = String(totalSeconds % 60).padStart(2, '0');
        if (timerEl) timerEl.innerText = `${h}:${m}:${s}`;
      }, 1000);
    }

    function renderRecommendedCoupons(currentItem) {
      const container = document.getElementById('modal-recommended-coupons');
      if (!container) return;

      // Buscar 3 cupones relacionados
      const recommendations = dataset.filter(x => 
        (x.type === 'coupon' || x.category === 'cupones' || x.category === 'hosteleria') && 
        String(x.id) !== String(currentItem.id)
      ).slice(0, 3);

      container.innerHTML = '';
      recommendations.forEach(rec => {
        const recCard = document.createElement('div');
        recCard.className = 'bg-amber-50 border border-dashed border-red-400 p-2 rounded-lg cursor-pointer hover:bg-amber-100 hover:border-red-600 transition flex flex-col justify-between text-left shadow-sm';
        recCard.onclick = () => openCouponModal(rec.id);
        recCard.innerHTML = `
          <div>
            <span class="text-[9px] font-black text-newsred bg-red-100 px-1.5 py-0.5 rounded uppercase font-mono block mb-1 truncate">
              ${rec.badge || 'CUPÓN'}
            </span>
            <h5 class="font-bold text-[11px] text-ink line-clamp-2 leading-tight mb-1 hover:text-newsred">
              ${rec.title}
            </h5>
          </div>
          <div class="mt-1 pt-1 border-t border-red-200 flex justify-between items-center text-[10px]">
            <span class="font-mono font-bold text-newsred">${rec.code || 'DESCUENTO'}</span>
            <i class="fa-solid fa-scissors text-xs text-newsred"></i>
          </div>
        `;
        container.appendChild(recCard);
      });
    }

    function closeCouponModal() {
      if (couponCountdownInterval) clearInterval(couponCountdownInterval);
      const modal = document.getElementById('coupon-modal');
      modal.classList.add('hidden');
      modal.classList.remove('flex');
    }

    function copyCouponCode() {
      navigator.clipboard.writeText(activeModalCode);
      showToastNotification(`¡Código '${activeModalCode}' copiado al portapapeles!`);
    }

    function printCurrentCoupon() {
      if (!activeModalItem) return;
      const printWindow = window.open('', '_blank', 'width=700,height=500');
      printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
          <title>Imprimir Cupón - ${activeModalItem.title}</title>
          <style>
            body { font-family: Arial, sans-serif; padding: 20px; text-align: center; }
            .coupon-box { border: 3px dashed #dc2626; padding: 25px; max-width: 500px; margin: 0 auto; background: #fffdf5; border-radius: 12px; }
            h2 { color: #111827; margin-top: 0; }
            .code { font-size: 32px; font-family: monospace; font-weight: bold; color: #dc2626; letter-spacing: 3px; background: #fee2e2; padding: 10px 20px; display: inline-block; border-radius: 8px; margin: 15px 0; border: 2px dashed #b91c1c; }
            .footer { font-size: 12px; color: #6b7280; margin-top: 15px; border-top: 1px solid #e5e7eb; padding-top: 10px; }
          </style>
        </head>
        <body>
          <div class="coupon-box">
            <p style="font-weight:bold; color:#dc2626; text-transform:uppercase; margin-0;">AVISOS CLASIFICADOS & CUPÓNES - CUPÓN IMPRIMIBLE</p>
            <h2>${activeModalItem.title}</h2>
            <p>${activeModalItem.desc}</p>
            <div class="code">${activeModalCode}</div>
            <p><strong>Ubicación:</strong> ${activeModalItem.location} | <strong>Vencimiento:</strong> ${activeModalItem.expiry || 'Validez 30 días'}</p>
            <div class="footer">Presenta este recorte físico en caja. Operado por VORTICEPACIFICO ENGENHARIA LDA (NIPC PT518972895).</div>
          </div>
          <script>window.onload = function() { window.print(); };<\/script>
        </body>
        </html>
      `);
      printWindow.document.close();
    }

    function shareCouponWhatsApp() {
      if (!activeModalItem) return;
      const text = `¡Mira este cupón de descuento en ${activeModalItem.location}!: *${activeModalItem.title}*\nCódigo Promocional: *${activeModalCode}*\nVer en la web: https://classifiedads-coupons.cc/es/cupon/`;
      window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(text)}`, '_blank');
    }

    function copyCouponLink() {
      if (!activeModalItem) return;
      const cleanUrl = window.seoRouter ? window.seoRouter.generateCleanUrl(activeModalItem) : window.location.href;
      navigator.clipboard.writeText(cleanUrl);
      showToastNotification('¡Enlace del cupón copiado al portapapeles!');
    }

    function redeemCouponOnline() {
      if (!activeModalItem) return;
      copyCouponCode();
      showToastNotification('Redirigiendo a la web oficial del anunciante...');
      setTimeout(() => {
        window.open('https://classifiedads-coupons.cc/es/cupon/', '_blank');
      }, 800);
    }

    function showToastNotification(message) {
      let toast = document.getElementById('call-to-click-toast');
      if (!toast) {
        toast = document.createElement('div');
        toast.id = 'call-to-click-toast';
        toast.className = 'fixed bottom-5 right-5 bg-slate-900 text-amber-400 font-bold px-4 py-3 rounded-lg shadow-2xl z-50 border-2 border-amber-400 text-xs flex items-center gap-2 transition transform translate-y-0';
        document.body.appendChild(toast);
      }
      toast.innerHTML = `<i class="fa-solid fa-circle-check text-emerald-400 text-base"></i> ${message}`;
      toast.style.display = 'flex';
      setTimeout(() => {
        toast.style.display = 'none';
      }, 3000);
    }

    function openApiModal() {
      document.getElementById('api-key-input').value = window.couponClient.apiKey;
      document.getElementById('api-endpoint-input').value = window.couponClient.apiEndpoint;
      const modal = document.getElementById('api-modal');
      modal.classList.remove('hidden');
      modal.classList.add('flex');
    }

    function closeApiModal() {
      const modal = document.getElementById('api-modal');
      modal.classList.add('hidden');
      modal.classList.remove('flex');
    }

    function handleSaveApi(e) {
      e.preventDefault();
      const apiKey = document.getElementById('api-key-input').value.trim();
      const endpoint = document.getElementById('api-endpoint-input').value.trim();
      window.couponClient.saveConfig(apiKey, endpoint);
      closeApiModal();
      syncAllApis();
    }

    function openPublishModal() {
      const modal = document.getElementById('publish-modal');
      modal.classList.remove('hidden');
      modal.classList.add('flex');
    }

    function closePublishModal() {
      const modal = document.getElementById('publish-modal');
      modal.classList.add('hidden');
      modal.classList.remove('flex');
    }

    function togglePubFields(type) {
      const extra = document.getElementById('coupon-extra-fields');
      if (type === 'coupon') {
        extra.classList.remove('hidden');
      } else {
        extra.classList.add('hidden');
      }
    }

    function handlePublish(e) {
      e.preventDefault();
      const type = document.querySelector('input[name="pub-type"]:checked').value;
      const cat = document.getElementById('pub-category').value;
      const country = document.getElementById('pub-country').value;
      const title = document.getElementById('pub-title').value;
      const desc = document.getElementById('pub-desc').value;
      const price = document.getElementById('pub-price').value || 'Consultar';
      const phone = document.getElementById('pub-phone').value || '+34 600 000 000';
      const code = document.getElementById('pub-code').value || 'OFERTA2026';

      let badgeText = cat.toUpperCase() + '';
      let badgeColor = 'bg-gray-100 text-gray-800 border-gray-300';

      if (type === 'coupon') {
        badgeText = 'CUPÓN';
        badgeColor = 'bg-red-100 text-newsred border-red-300';
      } else if (type === 'supermarket') {
        badgeText = 'SUPERMERCADO';
        badgeColor = 'super-promo-badge';
      } else if (type === 'oficial') {
        badgeText = 'EDICTO OFICIAL';
        badgeColor = 'official-border text-blue-900';
      }

      const newItem = {
        id: Date.now(),
        type: type,
        category: cat,
        country: country,
        badge: badgeText,
        badgeColor: badgeColor,
        title: title,
        desc: desc,
        price: price,
        phone: phone,
        code: code,
        location: 'Publicación Reciente',
        expiry: 'Próximos 30 días',
        featured: true,
        size: 'col-span-1'
      };

      dataset.unshift(newItem);
      closePublishModal();
      filterItems();
      alert('¡Tu aviso u edicto ha sido publicado con éxito en AVISOS CLASIFICADOS & CUPÓNES!');
    }

    /* LÓGICA DEL MODAL DE SITEMAPS XML Y ROBOTS.TXT */
    let currentSitemapTab = 'index';
    let currentSitemapContent = '';

    function openSitemapModal() {
      switchSitemapTab('index');
      const modal = document.getElementById('sitemap-modal');
      modal.classList.remove('hidden');
      modal.classList.add('flex');
    }

    function closeSitemapModal() {
      const modal = document.getElementById('sitemap-modal');
      modal.classList.add('hidden');
      modal.classList.remove('flex');
    }

    function switchSitemapTab(tab) {
      currentSitemapTab = tab;
      const tabs = ['index', 'es', 'pt', 'fr', 'uk', 'robots'];
      tabs.forEach(t => {
        const btn = document.getElementById(`tab-sitemap-${t}`);
        if (btn) {
          if (t === tab) {
            btn.className = 'px-2 py-1.5 text-xs font-bold rounded bg-amber-400 text-black border border-black shadow';
          } else {
            btn.className = 'px-2 py-1.5 text-xs font-bold rounded bg-gray-100 text-gray-700 hover:bg-gray-200 border border-gray-300';
          }
        }
      });

      const codeEl = document.getElementById('sitemap-modal-code');
      if (tab === 'index') {
        currentSitemapContent = window.sitemapGenerator.generateSitemapIndex();
      } else if (tab === 'robots') {
        currentSitemapContent = window.sitemapGenerator.generateRobotsTxt();
      } else {
        currentSitemapContent = window.sitemapGenerator.generateCountrySitemap(tab);
      }

      codeEl.textContent = currentSitemapContent;
    }

    function copySitemapCode() {
      navigator.clipboard.writeText(currentSitemapContent);
      alert(`¡Contenido de ${currentSitemapTab} copiado al portapapeles!`);
    }

    function downloadSitemapCurrent() {
      const filename = currentSitemapTab === 'robots' ? 'robots.txt' : `sitemap-${currentSitemapTab}.xml`;
      const mime = currentSitemapTab === 'robots' ? 'text/plain' : 'application/xml';
      const blob = new Blob([currentSitemapContent], { type: mime });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = filename;
      link.click();
    }

    function initApp() {
      const path = window.location.pathname.toLowerCase();
      let code = 'us';
      if (path.startsWith('/es/') || path === '/es') code = 'es';
      else if (path.startsWith('/pt/') || path === '/pt') code = 'pt';
      else if (path.startsWith('/fr/') || path === '/fr') code = 'fr';
      else if (path.startsWith('/uk/') || path === '/uk') code = 'uk';
      else if (path.startsWith('/nl/') || path === '/nl') code = 'nl';
      else if (path.startsWith('/us/') || path === '/us') code = 'us';

      switchCountry(code);
      syncAllApis();
    }

    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', initApp);
    } else {
      initApp();
    }
  </script>
</body>
</html>
