"use client";

import React, { useState, useEffect, useMemo } from "react";
import { motion, AnimatePresence } from "motion/react";
import {
  FileText,
  Settings,
  Layers,
  Globe,
  Search,
  Sparkles,
  Plus,
  Trash2,
  Edit3,
  Check,
  AlertCircle,
  Calendar,
  Megaphone,
  User,
  Clock,
  ArrowRight,
  ChevronRight,
  Eye,
  Share2,
  ShieldAlert,
  Send,
  X,
  Lock,
  ArrowUpRight,
  CheckSquare,
  Facebook,
  Twitter,
  Instagram,
  RefreshCw,
  ExternalLink
} from "lucide-react";

// Structure of Article
interface Article {
  id: string;
  title: string;
  category: string; // Nacional, Internacional, Pulso Legislativo, Memoria Digital
  summary: string;
  content: string;
  author: string;
  date: string;
  readTime: string;
  image: string;
  keywords: string[];
  qna: { question: string; answer: string }[];
  isFeatured?: boolean;
  isOpinion?: boolean;
  opinionAuthor?: { name: string; role: string; avatar: string };
}

// Structure of Ad Banner
interface AdBanner {
  id: string;
  title: string;
  imageUrl: string;
  targetUrl: string;
  isActive: boolean;
  placement: string[]; // List of article IDs or category names where this banner should display
}

export default function Home() {
  // --- STATE ---
  const [articles, setArticles] = useState<Article[]>([]);
  const [banners, setBanners] = useState<AdBanner[]>([]);
  const [globalSEO, setGlobalSEO] = useState({
    title: "Encuadre | Periodismo y Análisis Político",
    description: "Portal de noticias de actualidad política, análisis legislativo, debate nacional e internacional y memoria digital de alta precisión.",
    keywords: "politica, legislativo, congreso, debate, senado, nacional, analisis electoral"
  });

  // UI States
  const [selectedCategory, setSelectedCategory] = useState<string>("Todo");
  const [activeArticle, setActiveArticle] = useState<Article | null>(null);
  const [isCmsOpen, setIsCmsOpen] = useState(false);
  const [activeCmsTab, setActiveCmsTab] = useState<"blog" | "ads" | "seo">("blog");
  const [isDenunciaOpen, setIsDenunciaOpen] = useState(false);
  const [denunciaSubmitting, setDenunciaSubmitting] = useState(false);
  const [denunciaCode, setDenunciaCode] = useState<string | null>(null);

  // Form States for Anonymous Whistleblower
  const [denunciaForm, setDenunciaForm] = useState({
    subject: "",
    institution: "",
    description: "",
    isAnonymous: true,
    contactInfo: ""
  });

  // CMS Blog States
  const [iaPrompt, setIaPrompt] = useState("");
  const [iaSection, setIaSection] = useState("Pulso Legislativo");
  const [iaKeywords, setIaKeywords] = useState("");
  const [isGeneratingIa, setIsGeneratingIa] = useState(false);
  const [generationSteps, setGenerationSteps] = useState<string[]>([]);
  const [generationStepIndex, setGenerationStepIndex] = useState(0);
  
  // Custom Manual Article state
  const [manualArticle, setManualArticle] = useState({
    title: "",
    category: "Pulso Legislativo",
    summary: "",
    content: "",
    author: "Redacción Encuadre",
    keywords: "",
    suggestedImage: "politics"
  });
  const [isManualCreating, setIsManualCreating] = useState(false);

  // CMS Banner States
  const [newBanner, setNewBanner] = useState({
    title: "",
    imageUrl: "",
    targetUrl: "#",
    placement: [] as string[],
    isActive: true
  });

  // CMS Selected Article for Local SEO editing
  const [selectedSeoArticleId, setSelectedSeoArticleId] = useState<string>("");
  const [localSeoData, setLocalSeoData] = useState({
    title: "",
    summary: "",
    keywords: ""
  });

  // --- DEFAULT DATA POPULATION ---
  useEffect(() => {
    // Initial content pre-population, read from localStorage if exists
    const storedArticles = localStorage.getItem("encu_articles");
    const storedBanners = localStorage.getItem("encu_banners");
    const storedSEO = localStorage.getItem("encu_seo");

    if (storedArticles) {
      const parsed = JSON.parse(storedArticles);
      setTimeout(() => setArticles(parsed), 0);
    } else {
      const defaults: Article[] = [
        {
          id: "art-1",
          title: "El Senado aprueba la reforma al Sistema Electoral tras un debate de 14 horas",
          category: "Pulso Legislativo",
          summary: "Con 72 votos a favor y 50 en contra, se consolida la reestructuración del padrón electoral y se modifican las atribuciones de la junta autónoma nacional.",
          content: `<h2>Un hito legislativo histórico</h2><p>Tras un debate maratónico de más de 14 horas que se prolongó hasta la madrugada, el <strong>Senado de la República</strong> aprobó en lo general y lo particular la reforma estructural al Sistema Electoral. El proyecto, que ha polarizado la opinión pública en los últimos meses, introduce modificaciones críticas en la administración de los comicios.</p><h3>Principales modificaciones aprobadas</h3><ul><li><strong>Fusión de juntas locales:</strong> Se centralizarán las funciones de las oficinas distritales para reducir el gasto administrativo en un 15% anual de manera sostenida.</li><li><strong>Digitalización del padrón electoral:</strong> Se implementará de forma inmediata un sistema de identidad digital biométrica para blindar la autenticidad del sufragio.</li><li><strong>Reducción de financiamiento:</strong> El subsidio público ordinario a los partidos se ajustará de forma proporcional según la participación electoral efectiva del último comicio.</li></ul><p>El senador ponente, <strong>Andrés Mendoza</strong>, defendió firmemente la iniciativa argumentando que representará un ahorro sustancial para las arcas públicas. Por el contrario, los bloques opositores manifestaron que la centralización pone en riesgo la autonomía técnica del proceso de conteo de votos.</p><h3>Impacto a corto y mediano plazo</h3><p>La reforma obligará a una reestructuración interna en los próximos 90 días, un periodo crítico que coincide con los preparativos iniciales de las elecciones intermedias de gobernadores de la próxima gestión.</p>`,
          author: "Constanza Valdés (Corresponsal Legislativa)",
          date: "Hoy, 13 de Julio, 2026",
          readTime: "5 min lectura",
          image: "https://picsum.photos/seed/senado/800/450",
          keywords: ["reforma electoral", "senado", "voto ciudadano", "ley electoral", "debate parlamentario"],
          isFeatured: true,
          qna: [
            {
              question: "¿Cuándo entran en vigor las nuevas disposiciones de la ley electoral?",
              answer: "Entrarán en vigor al día siguiente de su publicación en el Diario Oficial, exceptuando la digitalización biométrica que tendrá un periodo de transición estructurado de 12 meses."
            },
            {
              question: "¿Cuáles son los recursos legales que interpondrá la oposición?",
              answer: "Se prevé la presentación formal de recursos de inconstitucionalidad ante el Tribunal Supremo en las próximas dos semanas hábiles."
            }
          ]
        },
        {
          id: "art-2",
          title: "Transición Energética: El Plan Nacional de Infraestructura apunta a un 40% de renovables para 2030",
          category: "Nacional",
          summary: "El Ministerio de Energía presenta una inversión masiva de 12,000 millones de dólares para potenciar parques eólicos y plantas solares comunitarias.",
          content: `<h2>Una hoja de ruta hacia la descarbonización integral</h2><p>El Gobierno ha presentado formalmente el nuevo <strong>Plan Nacional de Infraestructura Energética (PNIE)</strong>, cuyo objetivo primordial es elevar la participación de energías limpias en la matriz nacional al 40% en un periodo de cuatro años. La inversión proyectada representa la mayor inyección de capital en el sector de las últimas dos décadas.</p><h3>Ejes estratégicos del plan nacional</h3><p>El plan se cimenta sobre tres pilares fundamentales que buscan descentralizar la producción eléctrica y garantizar estabilidad:</p><ul><li><strong>Parques eólicos del norte:</strong> Desarrollo de cinco complejos eólicos con líneas de transmisión directa hacia los principales centros urbanos.</li><li><strong>Subsidios solares comunitarios:</strong> Financiamiento directo para la instalación de paneles en cooperativas agrarias y zonas rurales aisladas del tendido convencional.</li><li><strong>Modernización de la red:</strong> Renovación de subestaciones para soportar flujos intermitentes de energía limpia.</li></ul><p>La ministra de Energía destacó que el proyecto no solo reducirá las emisiones contaminantes, sino que creará más de <strong>25,000 empleos directos e indirectos</strong>, reactivando de forma decisiva las economías locales afectadas por la sequía.</p>`,
          author: "Carlos Alatorre (Editor de Economía y Energía)",
          date: "Ayer, 12 de Julio, 2026",
          readTime: "4 min lectura",
          image: "https://picsum.photos/seed/energy/800/450",
          keywords: ["energia renovable", "plan nacional", "transicion energetica", "infraestructura publica", "medio ambiente"],
          qna: [
            {
              question: "¿De dónde provendrán los fondos para el plan nacional de energía?",
              answer: "El 60% se financiará mediante la emisión de bonos verdes soberanos y el 40% restante a través de licitaciones públicas de inversión extranjera."
            },
            {
              question: "¿Cómo afectará este nuevo plan a las tarifas eléctricas residenciales?",
              answer: "El regulador proyecta una reducción gradual de hasta el 8% en las tarifas residenciales una vez que los complejos del norte operen a plena capacidad."
            }
          ]
        },
        {
          id: "art-3",
          title: "La Cumbre del Clima de Ginebra cierra con un histórico acuerdo de compensación para economías emergentes",
          category: "Internacional",
          summary: "Tras bloqueos diplomáticos severos, las naciones industrializadas acuerdan un fondo anual para reparar pérdidas territoriales causadas por el cambio climático.",
          content: `<h2>El 'Fondo de Resiliencia' se hace realidad</h2><p>En una sesión de clausura dramática que requirió dos prórrogas consecutivas de negociación, la <strong>Cumbre Internacional del Clima en Ginebra</strong> culminó con la firma de un tratado sin precedentes: la creación de un fondo financiero directo de compensación de pérdidas y daños destinados a países vulnerables en vías de desarrollo.</p><h3>Detalles del acuerdo firmado</h3><p>El acuerdo establece un compromiso vinculante para que los países con mayor huella de carbono histórica aporten anualmente a un fideicomiso global administrado de forma independiente.</p><ul><li><strong>Monto inicial comprometido:</strong> Se proyectan 100,000 millones de dólares anuales de forma incremental a partir de 2027.</li><li><strong>Criterio de asignación:</strong> Se dará prioridad absoluta a pequeños estados insulares y zonas costeras vulnerables al aumento del nivel del mar.</li><li><strong>Auditoría ambiental:</strong> El uso de los recursos estará condicionado a proyectos verificables de relocalización y obras de mitigación de desastres.</li></ul><p>La delegada de las naciones insulares calificó el acuerdo como un 'acto mínimo de justicia histórica', mientras que los representantes de las potencias manufactureras enfatizaron la necesidad de supervisar que cada dólar sea invertido con absoluta transparencia administrativa.</p>`,
          author: "Elena Rostova (Corresponsal en Europa)",
          date: "11 de Julio, 2026",
          readTime: "6 min lectura",
          image: "https://picsum.photos/seed/global/800/450",
          keywords: ["cumbre del clima", "acuerdo internacional", "justicia climatica", "ginebra", "compensaciones"],
          qna: [
            {
              question: "¿Qué países están obligados a aportar de manera directa a este fondo?",
              answer: "El tratado obliga a los miembros firmantes del G7 y de la Unión Europea, invitando voluntariamente a sumarse a otras potencias industriales."
            }
          ]
        },
        {
          id: "art-4",
          title: "A 25 años del 'Voto Digital': Lecciones del experimento que transformó la participación ciudadana",
          category: "Memoria Digital",
          summary: "Un análisis histórico de la primera votación en línea y cómo el software de código abierto blindó los resultados de la manipulación partidista.",
          content: `<h2>La génesis de la democracia digital descentralizada</h2><p>Hace exactamente un cuarto de siglo, una provincia de nuestro país hizo historia al convertirse en el primer distrito del continente en celebrar un referéndum vinculante mediante un sistema de <strong>voto digital cifrado</strong>. El experimento, mirado en su época con profundo escepticismo, sentó las bases para los sistemas modernos de participación directa ciudadana.</p><h3>La tecnología detrás del hito</h3><p>A diferencia de los sistemas propietarios actuales, el proyecto de 2001 se basó exclusivamente en una infraestructura de <strong>código abierto y escrutinio público</strong> para erradicar cualquier sombra de sospecha:</p><ul><li><strong>Criptografía simétrica:</strong> Cada ciudadano recibía una clave cifrada de un solo uso entregada de manera presencial previa validación de identidad.</li><li><strong>Servidores distribuidos:</strong> El conteo de datos se replicó de forma paralela en cinco servidores universitarios públicos.</li><li><strong>Auditoría ciudadana:</strong> El código fuente del sistema de votación estuvo disponible para revisión y corrección pública tres meses antes de la jornada.</li></ul><p>El resultado demostró que la transparencia tecnológica es capaz de disolver la desconfianza institucional. El índice de participación alcanzó una cifra histórica del 84%, superando en doce puntos la media histórica del voto presencial convencional de la década.</p>`,
          author: "Mateo Cisneros (Historiador de Tecnología y Política)",
          date: "10 de Julio, 2026",
          readTime: "4 min lectura",
          image: "https://picsum.photos/seed/digital/800/450",
          keywords: ["voto digital", "democracia tecnologica", "codigo abierto", "historia politica", "participacion ciudadana"],
          qna: [
            {
              question: "¿Qué fallas técnicas se reportaron durante la jornada de votación en 2001?",
              answer: "Se registraron intentos de ataques de denegación de servicio (DDoS) controlados y caídas momentáneas que fueron subsanadas en minutos gracias al sistema de respaldo universitario descentralizado."
            }
          ]
        },
        {
          id: "art-5",
          title: "La erosión del diálogo parlamentario en la era de los algoritmos de confrontación",
          category: "Opinión",
          summary: "El debate político ha dejado las comisiones legislativas para trasladarse a las redes de confrontación. ¿Es posible recuperar el consenso institucional?",
          content: `<p>Asistimos a una transformación preocupante en la arena legislativa: la sustitución del argumento razonado por el clip de 15 segundos diseñado exclusivamente para viralizar la polarización en redes. Los diputados y senadores ya no legislan para el beneficio colectivo de sus distritos; legislan para alimentar los algoritmos de sus plataformas digitales personales.</p><p>Esta dinámica ha erosionado gravemente la capacidad de lograr <strong>consensos institucionales</strong> bipartidistas. Los proyectos de ley se presentan con títulos provocadores para generar indignación instantánea, no soluciones estructurales. El debate parlamentario ya no busca persuadir al adversario en el hemiciclo, sino lincharlo virtualmente ante una audiencia segmentada.</p><p>Recuperar la salud de nuestras instituciones democráticas requiere volver a los canales formales de negociación, revalorizar las comisiones técnicas de redacción y limitar la espectacularización de la política. De lo contrario, seguiremos produciendo leyes deficientes bajo la batuta del aplauso digital efímero.</p>`,
          author: "Dra. Viviana Garcés (Analista Política y Académica)",
          date: "Hoy, 13 de Julio, 2026",
          readTime: "3 min lectura",
          image: "https://picsum.photos/seed/parliament/800/450",
          keywords: ["opinion", "dialogo politico", "polarizacion", "redes sociales", "parlamento"],
          isOpinion: true,
          opinionAuthor: {
            name: "Dra. Viviana Garcés",
            role: "Directora de Estudios Públicos, U. Nacional",
            avatar: "https://picsum.photos/seed/woman1/150/150"
          },
          qna: []
        },
        {
          id: "art-6",
          title: "Radiografía fiscal: ¿En qué gastan realmente las bancadas políticas de nuestro Congreso?",
          category: "Opinión",
          summary: "Un análisis profundo de los informes de asignaciones presupuestarias revela un incremento preocupante en servicios de asesoría externa y publicidad institucional.",
          content: `<p>Un análisis de datos públicos del último ejercicio fiscal revela patrones de gasto parlamentario que merecen un riguroso escrutinio ciudadano. La partida presupuestaria de 'Asesorías Externas y Apoyo Legislativo' ha registrado un incremento real del 22% interanual, superando con creces la inflación registrada de este ejercicio.</p><p>Lo llamativo es que la calidad técnica de las iniciativas de ley presentadas no muestra una mejora proporcional. Al examinar los contratos, se observa que una porción significativa de estas asesorías recae en agencias de relaciones públicas y marketing digital, camufladas como consultorías legislativas.</p><p>Es imperativo exigir que cada centavo de dinero público asignado a los legisladores sea plenamente auditable, justificando la necesidad técnica de cada informe contratado. La transparencia presupuestaria no debe ser un adorno retórico, sino el pilar de la confianza institucional.</p>`,
          author: "Ing. Manuel Ortega (Director de Datos en Encuadre)",
          date: "Ayer, 12 de Julio, 2026",
          readTime: "5 min lectura",
          image: "https://picsum.photos/seed/chart/800/450",
          keywords: ["gasto fiscal", "transparencia", "datos congreso", "auditoria", "presupuesto"],
          isOpinion: true,
          opinionAuthor: {
            name: "Ing. Manuel Ortega",
            role: "Especialista en Datos y Transparencia Pública",
            avatar: "https://picsum.photos/seed/man1/150/150"
          },
          qna: []
        }
      ];
      setTimeout(() => setArticles(defaults), 0);
      localStorage.setItem("encu_articles", JSON.stringify(defaults));
    }

    if (storedBanners) {
      const parsedBanners = JSON.parse(storedBanners);
      setTimeout(() => setBanners(parsedBanners), 0);
    } else {
      const defaultBanners: AdBanner[] = [
        {
          id: "ban-1",
          title: "Gran Foro de Reforma Constitucional y Democrática",
          imageUrl: "https://picsum.photos/seed/forumad/1100/180",
          targetUrl: "#",
          isActive: true,
          placement: ["Todo", "Pulso Legislativo", "Nacional"]
        },
        {
          id: "ban-2",
          title: "Suscripción Premium Encuadre Digital",
          imageUrl: "https://picsum.photos/seed/suscribead/350/250",
          targetUrl: "#",
          isActive: true,
          placement: ["Internacional", "Memoria Digital", "art-2", "art-4"]
        }
      ];
      setTimeout(() => setBanners(defaultBanners), 0);
      localStorage.setItem("encu_banners", JSON.stringify(defaultBanners));
    }

    if (storedSEO) {
      const parsedSEO = JSON.parse(storedSEO);
      setTimeout(() => setGlobalSEO(parsedSEO), 0);
    }
  }, []);

  // Sync states to local storage on changes
  const updateArticlesInStateAndStorage = (newArticles: Article[]) => {
    setArticles(newArticles);
    localStorage.setItem("encu_articles", JSON.stringify(newArticles));
  };

  const updateBannersInStateAndStorage = (newBanners: AdBanner[]) => {
    setBanners(newBanners);
    localStorage.setItem("encu_banners", JSON.stringify(newBanners));
  };

  const updateGlobalSEOStateAndStorage = (newSEO: typeof globalSEO) => {
    setGlobalSEO(newSEO);
    localStorage.setItem("encu_seo", JSON.stringify(newSEO));
  };

  // Set initial state for SEO article editor when articles load
  useEffect(() => {
    if (articles.length > 0 && !selectedSeoArticleId) {
      const firstId = articles[0].id;
      setTimeout(() => {
        setSelectedSeoArticleId(firstId);
      }, 0);
    }
  }, [articles, selectedSeoArticleId]);

  // Load selected article data for SEO editing
  useEffect(() => {
    if (selectedSeoArticleId) {
      const art = articles.find(a => a.id === selectedSeoArticleId);
      if (art) {
        const localData = {
          title: art.title,
          summary: art.summary,
          keywords: art.keywords.join(", ")
        };
        setTimeout(() => {
          setLocalSeoData(localData);
        }, 0);
      }
    }
  }, [selectedSeoArticleId, articles]);

  // Handle article deletion
  const handleDeleteArticle = (id: string) => {
    if (window.confirm("¿Está seguro de que desea eliminar este artículo?")) {
      const updated = articles.filter(a => a.id !== id);
      updateArticlesInStateAndStorage(updated);
      if (selectedSeoArticleId === id && updated.length > 0) {
        setSelectedSeoArticleId(updated[0].id);
      }
    }
  };

  // --- IA GENERATION LOGIC ---
  const handleGenerateIaArticle = async () => {
    setIsGeneratingIa(true);
    setGenerationStepIndex(0);
    
    const steps = [
      "Analizando las tendencias políticas y debates parlamentarios en tiempo real...",
      "Estructurando jerarquía de encabezados SEO semánticos (H2/H3)...",
      "Redactando gancho de entrada e integrando palabras clave orgánicamente...",
      "Formateando datos estadísticos clave y estructurando Preguntas Frecuentes (Q&A)...",
      "Validando densidad de palabras clave y metaetiquetas óptimas...",
      "¡Artículo redactado e indexado con éxito!"
    ];
    setGenerationSteps(steps);

    // Dynamic timing step animation
    const stepInterval = setInterval(() => {
      setGenerationStepIndex(prev => {
        if (prev < steps.length - 1) {
          return prev + 1;
        } else {
          clearInterval(stepInterval);
          return prev;
        }
      });
    }, 1200);

    try {
      const response = await fetch("/api/generate-article", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          topic: iaPrompt || undefined,
          section: iaSection,
          keyword: iaKeywords || undefined
        }),
      });

      const data = await response.json();

      if (!response.ok || !data.success) {
        throw new Error(data.error || "Fallo en la comunicación con el servidor Gemini.");
      }

      const rawArt = data.article;
      
      // Construct beautiful news object
      const newArt: Article = {
        id: `art-gen-${Date.now()}`,
        title: rawArt.title || "Artículo Generado por IA",
        category: rawArt.category || iaSection,
        summary: rawArt.summary || "Resumen del análisis periodístico automatizado.",
        content: rawArt.content || `<p>Contenido del artículo generado.</p>`,
        author: "Trend-Bot (Inteligencia Editorial)",
        date: "Hoy, 13 de Julio, 2026",
        readTime: `${Math.max(3, Math.round((rawArt.content || "").split(" ").length / 180))} min lectura`,
        image: `https://picsum.photos/seed/${rawArt.suggestedImage || "politics"}/800/450`,
        keywords: rawArt.keywords || (iaKeywords ? iaKeywords.split(",").map(k => k.trim()) : ["politica", "ia", "seo"]),
        qna: rawArt.qna || []
      };

      // Add to our articles
      const updatedArticles = [newArt, ...articles];
      updateArticlesInStateAndStorage(updatedArticles);
      
      // Clear inputs
      setIaPrompt("");
      setIaKeywords("");
      
      // Advance immediately to end step
      setGenerationStepIndex(steps.length - 1);
      setTimeout(() => {
        setIsGeneratingIa(false);
        // Automatically display the newly generated article
        setActiveArticle(newArt);
        setIsCmsOpen(false);
      }, 1500);

    } catch (err: any) {
      clearInterval(stepInterval);
      alert(`Error de IA: ${err.message}. Se creará un artículo de respaldo optimizado.`);
      
      // Create a rich simulated backup fallback so the app continues to operate and excel in UI
      const backupTitle = iaPrompt ? `Análisis profundo: Las implicaciones del debate sobre ${iaPrompt}` : "El nuevo equilibrio de fuerzas políticas y el impacto en la gobernabilidad nacional";
      const fallbackKeywords = iaKeywords ? iaKeywords.split(",").map(k => k.trim()) : ["gobernabilidad", "debate nacional", "reforma", "congreso"];
      
      const backupArt: Article = {
        id: `art-gen-fallback-${Date.now()}`,
        title: backupTitle,
        category: iaSection,
        summary: "El panorama político entra en una fase decisiva de negociaciones estratégicas y reconfiguración de alianzas partidistas en el congreso.",
        content: `<h2>El escenario de negociación política actual</h2><p>El escenario parlamentario experimenta tensiones significativas que forzarán un replanteamiento de la agenda institucional de cara al segundo semestre de este periodo. Los debates y los <strong>consensos de bancada</strong> se perfilan complejos pero indispensables.</p><h3>Análisis estratégico y prioridades legislativas</h3><ul><li><strong>Cohesión de bloques legislativos:</strong> Las directivas se encuentran definiendo los límites de las concesiones permitidas ante el oficialismo.</li><li><strong>Efecto en el debate público:</strong> Los ciudadanos demandan mayor transparencia y un desglose riguroso de los presupuestos asignados para el desarrollo.</li></ul><p>Es claro que las decisiones que se adopten en las próximas comisiones técnicas determinarán la viabilidad de los cambios estructurales propuestos.</p>`,
        author: "Trend-Bot (Optimizado en Contingencia)",
        date: "Hoy, 13 de Julio, 2026",
        readTime: "4 min lectura",
        image: `https://picsum.photos/seed/court/800/450`,
        keywords: fallbackKeywords,
        qna: [
          {
            question: "¿Qué papel juegan las minorías en esta coyuntura legislativa?",
            answer: "Las minorías parlamentarias se convierten en el bloque clave de bisagra para destrabar o congelar las iniciativas de reforma."
          }
        ]
      };
      
      const updatedArticles = [backupArt, ...articles];
      updateArticlesInStateAndStorage(updatedArticles);
      setIsGeneratingIa(false);
      setActiveArticle(backupArt);
      setIsCmsOpen(false);
    }
  };

  // Manual Article submission
  const handleManualArticleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!manualArticle.title || !manualArticle.content) {
      alert("Por favor rellene el título y el contenido.");
      return;
    }

    const keywordList = manualArticle.keywords
      ? manualArticle.keywords.split(",").map(k => k.trim())
      : ["manual", "encuadre", manualArticle.category.toLowerCase()];

    const newArt: Article = {
      id: `art-man-${Date.now()}`,
      title: manualArticle.title,
      category: manualArticle.category,
      summary: manualArticle.summary || manualArticle.content.substring(0, 150).replace(/<[^>]*>/g, '') + "...",
      content: manualArticle.content.replace(/\n/g, "<br/>"),
      author: manualArticle.author,
      date: "Hoy, 13 de Julio, 2026",
      readTime: `${Math.max(2, Math.round(manualArticle.content.split(" ").length / 180))} min lectura`,
      image: `https://picsum.photos/seed/${manualArticle.suggestedImage || "city"}/800/450`,
      keywords: keywordList,
      qna: [
        {
          question: `¿Qué implicaciones tiene esta publicación de ${manualArticle.category}?`,
          answer: "Establece un precedente crítico en el análisis y el seguimiento del desarrollo institucional nacional."
        }
      ]
    };

    updateArticlesInStateAndStorage([newArt, ...articles]);
    setManualArticle({
      title: "",
      category: "Pulso Legislativo",
      summary: "",
      content: "",
      author: "Redacción Encuadre",
      keywords: "",
      suggestedImage: "politics"
    });
    setIsManualCreating(false);
    alert("¡Artículo guardado y publicado exitosamente!");
  };

  // Toggle Ad Banner Active State
  const handleToggleBanner = (id: string) => {
    const updated = banners.map(b => (b.id === id ? { ...b, isActive: !b.isActive } : b));
    updateBannersInStateAndStorage(updated);
  };

  // Add custom banner
  const handleAddBanner = (e: React.FormEvent) => {
    e.preventDefault();
    if (!newBanner.title || !newBanner.imageUrl) {
      alert("Por favor ingrese el título y la URL de imagen del Banner.");
      return;
    }

    const banner: AdBanner = {
      id: `ban-${Date.now()}`,
      title: newBanner.title,
      imageUrl: newBanner.imageUrl,
      targetUrl: newBanner.targetUrl,
      isActive: newBanner.isActive,
      placement: newBanner.placement.length > 0 ? newBanner.placement : ["Todo"]
    };

    updateBannersInStateAndStorage([...banners, banner]);
    setNewBanner({
      title: "",
      imageUrl: "",
      targetUrl: "#",
      placement: [],
      isActive: true
    });
    alert("Pauta publicitaria inyectada con éxito.");
  };

  // Update Article Local SEO Data
  const handleSaveLocalSeo = (e: React.FormEvent) => {
    e.preventDefault();
    const updated = articles.map(art => {
      if (art.id === selectedSeoArticleId) {
        return {
          ...art,
          title: localSeoData.title,
          summary: localSeoData.summary,
          keywords: localSeoData.keywords.split(",").map(k => k.trim())
        };
      }
      return art;
    });
    updateArticlesInStateAndStorage(updated);
    alert("SEO Local del artículo actualizado y re-indexado.");
  };

  // Citizen Anonymous Tip submission
  const handleDenunciaSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!denunciaForm.subject || !denunciaForm.description) {
      alert("Por favor rellene el asunto y la descripción detallada.");
      return;
    }

    setDenunciaSubmitting(true);
    setTimeout(() => {
      const code = `ENC-2026-${Math.floor(100000 + Math.random() * 900000)}`;
      setDenunciaCode(code);
      setDenunciaSubmitting(false);
      // Reset form
      setDenunciaForm({
        subject: "",
        institution: "",
        description: "",
        isAnonymous: true,
        contactInfo: ""
      });
    }, 1500);
  };

  // --- DERIVED SELECTORS FOR UI ---
  // Articles filtered by active category selection on homepage
  const filteredArticles = useMemo(() => {
    if (selectedCategory === "Todo") {
      return articles.filter(a => !a.isOpinion);
    }
    return articles.filter(a => a.category === selectedCategory && !a.isOpinion);
  }, [articles, selectedCategory]);

  // Separate Opinion columns for layout grid
  const opinionArticles = useMemo(() => {
    return articles.filter(a => a.isOpinion);
  }, [articles]);

  // Find Featured article (main large left card)
  const featuredArticle = useMemo(() => {
    const feat = filteredArticles.find(a => a.isFeatured);
    if (feat) return feat;
    // Fallback to first non-opinion article in filtered
    return filteredArticles.find(a => !a.isOpinion) || null;
  }, [filteredArticles]);

  // Find secondary articles (excluding the main featured one)
  const secondaryArticles = useMemo(() => {
    if (!featuredArticle) return filteredArticles;
    return filteredArticles.filter(a => a.id !== featuredArticle.id).slice(0, 3);
  }, [filteredArticles, featuredArticle]);

  // Find rest of regular articles (remaining)
  const remainingArticles = useMemo(() => {
    if (!featuredArticle) return [];
    const secIds = secondaryArticles.map(s => s.id);
    return filteredArticles.filter(a => a.id !== featuredArticle.id && !secIds.includes(a.id));
  }, [filteredArticles, featuredArticle, secondaryArticles]);

  // Retrieve banners matching an active article or general placement
  const getBannersForArticle = (articleId: string, category: string) => {
    return banners.filter(b => 
      b.isActive && 
      (b.placement.includes("Todo") || 
       b.placement.includes(category) || 
       b.placement.includes(articleId))
    );
  };

  // General leaderboard banner (Top horizontal pauta)
  const generalLeaderboardBanner = useMemo(() => {
    return banners.find(b => b.isActive && b.placement.includes("Todo")) || null;
  }, [banners]);

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col selection:bg-violet-200">
      
      {/* --- UPPER TICKER / UTILITY RAIL --- */}
      <div className="bg-violet-950 text-violet-100 text-xs py-2 px-4 md:px-8 flex flex-col md:flex-row justify-between items-center gap-2 border-b border-violet-900 font-mono tracking-wide z-10">
        <div className="flex items-center gap-3">
          <Calendar className="w-3.5 h-3.5 text-orange-400" />
          <span>Lunes, 13 de Julio de 2026</span>
          <span className="text-violet-400 hidden md:inline">|</span>
          <span className="text-orange-300 hidden md:inline font-semibold">TENDENCIA: Reforma Electoral • Compensación Verde • Transición Energética</span>
        </div>
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2">
            <Facebook className="w-3.5 h-3.5 hover:text-orange-400 cursor-pointer transition-colors" />
            <Twitter className="w-3.5 h-3.5 hover:text-orange-400 cursor-pointer transition-colors" />
            <Instagram className="w-3.5 h-3.5 hover:text-orange-400 cursor-pointer transition-colors" />
          </div>
          <span className="text-violet-400">|</span>
          <button 
            onClick={() => {
              setDenunciaCode(null);
              setIsDenunciaOpen(true);
            }}
            id="denuncia_header_btn"
            className="flex items-center gap-1.5 bg-gradient-to-r from-orange-500 to-orange-600 text-white font-sans font-medium px-3 py-1 rounded shadow-sm hover:from-orange-600 hover:to-orange-700 transition-all text-xs"
          >
            <ShieldAlert className="w-3.5 h-3.5 animate-pulse" />
            Denuncia Ciudadana
          </button>
        </div>
      </div>

      {/* --- SITE HEADER --- */}
      <header className="bg-white border-b border-gray-200 py-6 px-4 md:px-8 sticky top-0 z-20 shadow-sm backdrop-blur-md bg-white/95">
        <div className="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-center gap-4">
          
          {/* Logo & Slogan */}
          <div className="flex flex-col items-center md:items-start cursor-pointer" onClick={() => setActiveArticle(null)}>
            <div className="flex items-baseline gap-1.5">
              <span className="text-4xl font-extrabold tracking-tighter text-violet-950 font-serif">ENCUADRE</span>
              <span className="w-2.5 h-2.5 rounded-full bg-orange-500"></span>
            </div>
            <span className="text-xs text-slate-500 font-mono tracking-widest mt-1 uppercase">Periodismo Político de Alta Precisión</span>
          </div>

          {/* Clean Menu and Search bar */}
          <div className="flex flex-col sm:flex-row items-center gap-4 w-full md:w-auto">
            <nav className="flex flex-wrap justify-center gap-1 bg-slate-100 p-1 rounded-lg">
              {["Todo", "Pulso Legislativo", "Nacional", "Internacional", "Memoria Digital"].map((cat) => (
                <button
                  key={cat}
                  onClick={() => {
                    setSelectedCategory(cat);
                    setActiveArticle(null);
                  }}
                  id={`nav-cat-${cat.replace(/\s+/g, '-').toLowerCase()}`}
                  className={`px-3 py-1.5 text-xs font-semibold rounded-md transition-all ${
                    selectedCategory === cat && !activeArticle
                      ? "bg-violet-900 text-white shadow-sm"
                      : "text-slate-600 hover:text-slate-900 hover:bg-slate-200"
                  }`}
                >
                  {cat}
                </button>
              ))}
            </nav>
            <div className="relative w-full sm:w-48 hidden lg:block">
              <input 
                type="text" 
                placeholder="Buscar temas..." 
                className="w-full bg-slate-100 border border-slate-200 rounded-lg text-xs py-1.5 pl-8 pr-3 outline-none focus:border-violet-500 focus:bg-white transition-all text-slate-800"
              />
              <Search className="w-3.5 h-3.5 text-slate-400 absolute left-2.5 top-2.5" />
            </div>
          </div>

        </div>
      </header>

      {/* --- AD BANNER: HEADER LEADERBOARD --- */}
      {generalLeaderboardBanner && !activeArticle && (
        <div className="bg-white border-b border-gray-100 py-3 px-4 flex justify-center">
          <div className="max-w-7xl w-full">
            <div className="relative bg-slate-100 border border-slate-200/60 rounded-lg overflow-hidden h-16 md:h-24 flex items-center justify-between group shadow-inner">
              <div className="absolute top-1 left-2 bg-slate-200/80 text-[9px] uppercase px-1 rounded text-slate-500 font-mono font-bold">Publicidad</div>
              <img 
                src={generalLeaderboardBanner.imageUrl} 
                alt={generalLeaderboardBanner.title} 
                className="w-full h-full object-cover group-hover:scale-[1.01] transition-transform duration-700"
                referrerPolicy="no-referrer"
              />
              <div className="absolute inset-0 bg-gradient-to-r from-violet-950/80 via-transparent to-black/30 flex items-center justify-between px-6 md:px-12">
                <div className="text-white max-w-lg">
                  <span className="text-[10px] uppercase text-orange-400 tracking-wider font-semibold">Anuncio Destacado</span>
                  <h4 className="text-xs md:text-sm font-bold tracking-tight line-clamp-1">{generalLeaderboardBanner.title}</h4>
                </div>
                <a 
                  href={generalLeaderboardBanner.targetUrl}
                  className="bg-orange-500 text-white font-semibold text-xs py-1.5 px-3 rounded hover:bg-orange-600 transition-colors flex items-center gap-1 shrink-0"
                >
                  Saber más <ArrowUpRight className="w-3.5 h-3.5" />
                </a>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* --- MAIN CORE GRID CONTAINER --- */}
      <main className="flex-grow max-w-7xl w-full mx-auto p-4 md:p-8">
        
        <AnimatePresence mode="wait">
          
          {/* 1. PORTAL READING VIEW */}
          {activeArticle ? (
            <motion.article 
              initial={{ opacity: 0, y: 15 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -15 }}
              className="grid grid-cols-1 lg:grid-cols-12 gap-8"
              id="reading-article-view"
            >
              {/* Main Column */}
              <div className="lg:col-span-8 bg-white border border-gray-200 rounded-2xl p-6 md:p-10 shadow-sm">
                
                {/* Back Link */}
                <button 
                  onClick={() => setActiveArticle(null)}
                  className="inline-flex items-center gap-2 text-xs font-semibold text-violet-900 hover:text-violet-700 mb-6 group"
                >
                  <span className="group-hover:-translate-x-1 transition-transform">←</span> Volver a la portada
                </button>

                {/* Metadata & Categories */}
                <div className="flex flex-wrap items-center gap-3 mb-4">
                  <span className="bg-violet-900 text-white font-mono uppercase tracking-widest text-[10px] font-bold px-2.5 py-1 rounded">
                    {activeArticle.category}
                  </span>
                  <div className="flex items-center gap-1.5 text-xs text-slate-500 font-medium">
                    <Calendar className="w-3.5 h-3.5" />
                    <span>{activeArticle.date}</span>
                  </div>
                  <span className="text-slate-300">•</span>
                  <div className="flex items-center gap-1.5 text-xs text-slate-500 font-medium">
                    <Clock className="w-3.5 h-3.5" />
                    <span>{activeArticle.readTime}</span>
                  </div>
                </div>

                {/* Title & Summary */}
                <h1 className="text-2xl md:text-4xl font-extrabold tracking-tight text-slate-900 mb-4 leading-tight font-serif">
                  {activeArticle.title}
                </h1>
                
                <p className="text-lg text-slate-600 font-medium border-l-4 border-orange-500 pl-4 mb-8 italic">
                  {activeArticle.summary}
                </p>

                {/* Main Visual Image */}
                <div className="relative aspect-video rounded-xl overflow-hidden mb-8 shadow-md">
                  <img 
                    src={activeArticle.image} 
                    alt={activeArticle.title}
                    className="w-full h-full object-cover"
                    referrerPolicy="no-referrer"
                  />
                  <div className="absolute bottom-2 right-2 bg-black/70 text-slate-200 font-mono text-[9px] px-2 py-0.5 rounded">
                    Ilustración: Archivo Encuadre Político
                  </div>
                </div>

                {/* Rich HTML Content Body */}
                <div 
                  className="prose max-w-none text-slate-800 leading-relaxed space-y-6 text-sm md:text-base 
                  prose-headings:font-serif prose-headings:text-slate-900 prose-headings:font-bold
                  prose-h2:text-xl md:prose-h2:text-2xl prose-h2:border-b prose-h2:border-gray-100 prose-h2:pb-2 prose-h2:mt-8
                  prose-h3:text-lg prose-h3:mt-6
                  prose-strong:text-violet-950 prose-strong:font-bold
                  prose-ul:list-disc prose-ul:pl-6 prose-ul:space-y-2"
                  dangerouslySetInnerHTML={{ __html: activeArticle.content }}
                />

                {/* Keywords SEO tag display */}
                <div className="mt-10 pt-6 border-t border-gray-100 flex flex-wrap items-center gap-2">
                  <Globe className="w-3.5 h-3.5 text-slate-400 mr-2" />
                  <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider font-mono">Indexado SEO:</span>
                  {activeArticle.keywords.map((kw, i) => (
                    <span key={i} className="bg-slate-100 text-slate-700 font-mono text-xs px-2.5 py-1 rounded border border-slate-200/60">
                      #{kw}
                    </span>
                  ))}
                </div>

                {/* Q&A Section (FAQ SEO optimization requirement) */}
                {activeArticle.qna && activeArticle.qna.length > 0 && (
                  <div className="mt-12 bg-violet-50/70 border border-violet-100 rounded-xl p-6">
                    <div className="flex items-center gap-2 mb-4">
                      <Sparkles className="w-4 h-4 text-violet-700" />
                      <h3 className="text-sm font-bold tracking-wider text-violet-900 uppercase font-mono">Preguntas Frecuentes (Indexado de IA Búsqueda)</h3>
                    </div>
                    <div className="space-y-4">
                      {activeArticle.qna.map((item, idx) => (
                        <div key={idx} className="border-b border-violet-100/60 last:border-0 pb-3 last:pb-0">
                          <h4 className="text-sm font-extrabold text-violet-950 flex items-start gap-2">
                            <span className="bg-violet-200 text-violet-800 text-[10px] py-0.5 px-1.5 rounded shrink-0 mt-0.5">Q</span>
                            {item.question}
                          </h4>
                          <p className="text-xs md:text-sm text-slate-700 mt-1.5 pl-6 font-medium">
                            {item.answer}
                          </p>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Author footer credit info */}
                <div className="mt-10 pt-6 border-t border-gray-200 flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-full bg-violet-900 text-white flex items-center justify-center font-extrabold text-sm font-serif">
                      {activeArticle.author.substring(0, 2).toUpperCase()}
                    </div>
                    <div>
                      <span className="block text-sm font-extrabold text-slate-900">{activeArticle.author}</span>
                      <span className="text-xs text-slate-500">Mesa de Análisis Político de Encuadre</span>
                    </div>
                  </div>
                  <button 
                    onClick={() => alert("Enlace copiado al portapapeles para distribución institucional.")}
                    className="flex items-center gap-1 text-xs text-slate-500 hover:text-violet-900 font-bold border border-slate-200 px-3 py-1.5 rounded-lg hover:bg-slate-50 transition-all"
                  >
                    <Share2 className="w-3.5 h-3.5" /> Compartir
                  </button>
                </div>

              </div>

              {/* Sidebar Column */}
              <div className="lg:col-span-4 space-y-6">
                
                {/* Segmented injected ad banners for this article */}
                {getBannersForArticle(activeArticle.id, activeArticle.category).map(banner => (
                  <div key={banner.id} className="bg-white border border-gray-200 rounded-xl p-4 shadow-sm relative group overflow-hidden">
                    <span className="absolute top-2 left-2 bg-slate-200/80 text-[8px] uppercase tracking-wider px-1 py-0.5 rounded text-slate-500 font-mono font-bold z-10">Pauta Segmentada</span>
                    <div className="relative aspect-[4/3] rounded-lg overflow-hidden mb-3">
                      <img 
                        src={banner.imageUrl} 
                        alt={banner.title} 
                        className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                        referrerPolicy="no-referrer"
                      />
                    </div>
                    <h4 className="text-xs font-bold text-slate-800 line-clamp-2 mb-2">{banner.title}</h4>
                    <a 
                      href={banner.targetUrl}
                      className="w-full text-center block bg-violet-900 hover:bg-violet-950 text-white font-semibold text-xs py-2 rounded-lg transition-colors"
                    >
                      Ver Oportunidad
                    </a>
                  </div>
                ))}

                {/* Popular articles recommendation */}
                <div className="bg-slate-900 text-white rounded-xl p-6 border border-slate-800">
                  <h3 className="text-xs uppercase text-orange-400 tracking-widest font-bold font-mono mb-4 border-b border-slate-800 pb-2">Otras noticias de interés</h3>
                  <div className="space-y-4">
                    {articles
                      .filter(a => a.id !== activeArticle.id && !a.isOpinion)
                      .slice(0, 4)
                      .map(art => (
                        <div 
                          key={art.id} 
                          onClick={() => setActiveArticle(art)}
                          className="group cursor-pointer border-b border-slate-800/80 last:border-0 pb-3 last:pb-0"
                        >
                          <span className="text-[9px] uppercase tracking-wider font-mono text-violet-400 font-semibold">{art.category}</span>
                          <h4 className="text-xs font-bold group-hover:text-orange-300 transition-colors line-clamp-2 mt-0.5 leading-snug">
                            {art.title}
                          </h4>
                        </div>
                      ))}
                  </div>
                </div>

                {/* Editorial integrity pledge */}
                <div className="bg-white border border-gray-200 rounded-xl p-6 text-center">
                  <ShieldAlert className="w-8 h-8 text-orange-500 mx-auto mb-3" />
                  <h4 className="text-sm font-bold text-slate-900">Compromiso Editorial</h4>
                  <p className="text-xs text-slate-500 mt-2 leading-relaxed">
                    Nuestras coberturas están resguardadas bajo estrictas pautas de independencia editorial. Las opiniones de terceros no reflejan la línea de este portal.
                  </p>
                </div>

              </div>
            </motion.article>
          ) : (
            
            // 2. MAIN NEWS PORTAL DIRECTORY / PORTADA
            <motion.div 
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="space-y-12"
            >
              
              {/* --- PORTADA: SECCION HERO ASIMETRICA --- */}
              {featuredArticle && (
                <section className="space-y-4">
                  
                  {/* Section Title */}
                  <div className="flex items-center justify-between border-b-2 border-violet-950 pb-2">
                    <div className="flex items-center gap-2">
                      <span className="w-3 h-3 bg-violet-900 rounded-sm"></span>
                      <h2 className="text-lg md:text-xl font-bold tracking-tight text-slate-900 uppercase font-mono">
                        Noticia de Portada • {selectedCategory}
                      </h2>
                    </div>
                    <span className="text-xs font-mono text-slate-500 hidden sm:inline">Última actualización: Hace un instante</span>
                  </div>

                  {/* Asymmetrical Layout */}
                  <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
                    
                    {/* LEFT MAIN HERO ARTICLE CARD (60%) */}
                    <div 
                      onClick={() => setActiveArticle(featuredArticle)}
                      className="lg:col-span-7 bg-white border border-gray-200 rounded-2xl overflow-hidden cursor-pointer group hover:shadow-lg transition-all flex flex-col justify-between"
                      id="hero-featured-article"
                    >
                      <div className="relative aspect-video overflow-hidden bg-slate-950">
                        <img 
                          src={featuredArticle.image} 
                          alt={featuredArticle.title} 
                          className="w-full h-full object-cover group-hover:scale-[1.03] transition-transform duration-700"
                          referrerPolicy="no-referrer"
                        />
                        <div className="absolute top-3 left-3 bg-violet-950 text-white font-mono text-[9px] uppercase tracking-widest font-bold px-2 py-1 rounded">
                          {featuredArticle.category}
                        </div>
                      </div>
                      <div className="p-6 flex-grow flex flex-col justify-between">
                        <div>
                          <div className="flex items-center gap-3 text-xs text-slate-400 font-medium mb-2.5">
                            <span className="flex items-center gap-1">
                              <User className="w-3.5 h-3.5" /> {featuredArticle.author.split(" ")[0]} {featuredArticle.author.split(" ")[1]}
                            </span>
                            <span>•</span>
                            <span>{featuredArticle.date}</span>
                          </div>
                          <h3 className="text-xl md:text-2xl font-extrabold tracking-tight text-slate-900 group-hover:text-violet-900 transition-colors font-serif leading-tight">
                            {featuredArticle.title}
                          </h3>
                          <p className="text-slate-600 text-xs md:text-sm mt-3 line-clamp-3">
                            {featuredArticle.summary}
                          </p>
                        </div>
                        <div className="mt-5 pt-4 border-t border-gray-100 flex items-center justify-between">
                          <span className="text-xs font-bold text-violet-900 group-hover:text-orange-500 transition-colors flex items-center gap-1">
                            Análisis completo <ChevronRight className="w-3.5 h-3.5" />
                          </span>
                          <span className="text-xs text-slate-400 font-mono font-medium">{featuredArticle.readTime}</span>
                        </div>
                      </div>
                    </div>

                    {/* RIGHT 3 SECONDARY ARTICLES STACK (40%) */}
                    <div className="lg:col-span-5 flex flex-col justify-between gap-4">
                      {secondaryArticles.length > 0 ? (
                        secondaryArticles.map((art) => (
                          <div 
                            key={art.id}
                            onClick={() => setActiveArticle(art)}
                            className="bg-white border border-gray-200 hover:border-slate-300 rounded-xl p-4 cursor-pointer group hover:shadow-md transition-all flex gap-4 h-full"
                          >
                            <div className="w-24 h-20 md:w-28 md:h-24 shrink-0 rounded-lg overflow-hidden bg-slate-100">
                              <img 
                                src={art.image} 
                                alt={art.title} 
                                className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                                referrerPolicy="no-referrer"
                              />
                            </div>
                            <div className="flex flex-col justify-between flex-grow">
                              <div>
                                <span className="text-[9px] uppercase tracking-widest font-mono text-orange-600 font-bold block">{art.category}</span>
                                <h4 className="text-xs md:text-sm font-extrabold text-slate-900 tracking-tight leading-snug mt-1 group-hover:text-violet-900 transition-colors line-clamp-2">
                                  {art.title}
                                </h4>
                              </div>
                              <span className="text-[10px] text-slate-400 mt-2 flex items-center gap-1.5 font-medium">
                                <Clock className="w-3 h-3" /> {art.readTime}
                              </span>
                            </div>
                          </div>
                        ))
                      ) : (
                        <div className="bg-white border border-dashed border-gray-300 rounded-xl p-8 text-center flex flex-col justify-center items-center h-full">
                          <AlertCircle className="w-8 h-8 text-slate-300 mb-2" />
                          <p className="text-slate-400 text-xs">No hay noticias secundarias en esta sección.</p>
                        </div>
                      )}
                    </div>

                  </div>
                </section>
              )}

              {/* --- AD BANNER: MIDDLE IN-LINE SPONSOR --- */}
              {banners.filter(b => b.isActive && b.placement.includes("Todo")).slice(1, 2).map((banner) => (
                <div key={banner.id} className="bg-slate-200/50 rounded-xl p-4 flex flex-col md:flex-row justify-between items-center gap-4 border border-slate-300/60 max-w-5xl mx-auto w-full">
                  <div className="flex items-center gap-4">
                    <Megaphone className="w-8 h-8 text-orange-500 shrink-0" />
                    <div>
                      <span className="text-[9px] font-mono text-slate-500 uppercase tracking-wider block">Pauta Especial</span>
                      <h4 className="text-xs md:text-sm font-bold text-slate-800 leading-tight">{banner.title}</h4>
                    </div>
                  </div>
                  <a 
                    href={banner.targetUrl}
                    className="bg-violet-900 text-white font-semibold text-xs py-2 px-4 rounded hover:bg-violet-950 transition-all shrink-0 text-center w-full md:w-auto"
                  >
                    Registrar Asistencia
                  </a>
                </div>
              ))}

              {/* --- GRID SECTIONS: OPINION & REMAINING ARTICLES --- */}
              <section className="grid grid-cols-1 lg:grid-cols-12 gap-8">
                
                {/* LEFT: REMAINING ARTICLES (8 COLS) */}
                <div className="lg:col-span-8 space-y-6">
                  
                  <div className="border-b border-slate-300 pb-2">
                    <h3 className="text-xs font-bold font-mono tracking-widest text-slate-600 uppercase flex items-center gap-2">
                      <FileText className="w-3.5 h-3.5 text-violet-900" /> Archivo de Crónicas Políticas
                    </h3>
                  </div>

                  {remainingArticles.length > 0 ? (
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                      {remainingArticles.map((art) => (
                        <div 
                          key={art.id}
                          onClick={() => setActiveArticle(art)}
                          className="bg-white border border-gray-200 rounded-xl overflow-hidden cursor-pointer group hover:shadow-md transition-all flex flex-col justify-between"
                        >
                          <div className="relative aspect-video overflow-hidden">
                            <img 
                              src={art.image} 
                              alt={art.title} 
                              className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
                              referrerPolicy="no-referrer"
                            />
                            <div className="absolute top-2 left-2 bg-slate-900/80 text-white font-mono text-[8px] uppercase tracking-widest px-2 py-0.5 rounded">
                              {art.category}
                            </div>
                          </div>
                          <div className="p-4 flex-grow flex flex-col justify-between">
                            <div>
                              <h4 className="text-xs md:text-sm font-extrabold tracking-tight text-slate-900 group-hover:text-violet-900 transition-colors line-clamp-2">
                                {art.title}
                              </h4>
                              <p className="text-slate-500 text-[11px] mt-2 line-clamp-2 leading-relaxed">
                                {art.summary}
                              </p>
                            </div>
                            <div className="mt-4 pt-3 border-t border-gray-100 flex items-center justify-between text-[10px] text-slate-400 font-medium">
                              <span>{art.date}</span>
                              <span className="font-mono text-violet-900 font-bold group-hover:text-orange-500 transition-colors flex items-center">
                                Leer <ChevronRight className="w-3 h-3" />
                              </span>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="bg-white border border-dashed border-gray-200 rounded-xl py-12 text-center text-slate-400 text-xs">
                      No hay artículos adicionales registrados para este filtro.
                    </div>
                  )}

                </div>

                {/* RIGHT: OPINION COLUMNISTS BENTO GRID (4 COLS) */}
                <div className="lg:col-span-4 space-y-6">
                  
                  <div className="border-b border-slate-300 pb-2">
                    <h3 className="text-xs font-bold font-mono tracking-widest text-slate-600 uppercase flex items-center gap-2">
                      <Sparkles className="w-3.5 h-3.5 text-orange-500" /> Tribuna & Opinión Independiente
                    </h3>
                  </div>

                  <div className="space-y-4">
                    {opinionArticles.map((art) => (
                      <div 
                        key={art.id}
                        onClick={() => setActiveArticle(art)}
                        className="bg-gradient-to-br from-violet-50/60 to-white border border-violet-100 rounded-xl p-5 cursor-pointer group hover:shadow-md transition-all relative flex flex-col justify-between"
                      >
                        <div className="absolute top-4 right-4 text-violet-200 text-4xl font-serif select-none">“</div>
                        <div>
                          <h4 className="text-xs md:text-sm font-extrabold tracking-tight text-slate-900 group-hover:text-violet-900 transition-colors leading-snug line-clamp-2 mb-3">
                            {art.title}
                          </h4>
                          <p className="text-slate-500 text-xs italic line-clamp-3 mb-4 pr-3 leading-relaxed">
                            {art.summary}
                          </p>
                        </div>
                        
                        {/* Author Profile Card */}
                        {art.opinionAuthor && (
                          <div className="pt-3 border-t border-violet-100/80 flex items-center gap-3">
                            <div className="w-9 h-9 rounded-full overflow-hidden border border-violet-200 shrink-0 bg-slate-100">
                              <img 
                                src={art.opinionAuthor.avatar} 
                                alt={art.opinionAuthor.name} 
                                className="w-full h-full object-cover"
                                referrerPolicy="no-referrer"
                              />
                            </div>
                            <div>
                              <span className="block text-xs font-extrabold text-slate-900 leading-tight">
                                {art.opinionAuthor.name}
                              </span>
                              <span className="text-[10px] text-slate-500 leading-tight block truncate max-w-[200px]">
                                {art.opinionAuthor.role}
                              </span>
                            </div>
                          </div>
                        )}
                      </div>
                    ))}
                  </div>

                </div>

              </section>

            </motion.div>
          )}

        </AnimatePresence>

      </main>

      {/* --- FLOATING REPORT ANONYMOUS TIP MODAL (DENUNCIA CIUDADANA) --- */}
      <AnimatePresence>
        {isDenunciaOpen && (
          <div className="fixed inset-0 bg-slate-950/70 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
            <motion.div 
              initial={{ scale: 0.95, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.95, opacity: 0 }}
              className="bg-white border border-slate-200 shadow-2xl rounded-2xl max-w-xl w-full max-h-[90vh] overflow-y-auto"
            >
              <div className="bg-gradient-to-r from-slate-900 to-slate-800 text-white p-5 flex justify-between items-center border-b border-slate-700">
                <div className="flex items-center gap-2">
                  <ShieldAlert className="w-5 h-5 text-orange-500 animate-pulse" />
                  <div>
                    <h3 className="text-sm font-bold uppercase tracking-wider font-mono">Buzón de Filtración Segura</h3>
                    <span className="text-[10px] text-slate-300">Cifrado de extremo a extremo, resguardo de fuente</span>
                  </div>
                </div>
                <button 
                  onClick={() => setIsDenunciaOpen(false)}
                  className="text-slate-400 hover:text-white transition-colors"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              <div className="p-6">
                
                {denunciaCode ? (
                  <div className="text-center py-6 space-y-4">
                    <div className="w-12 h-12 bg-emerald-100 rounded-full flex items-center justify-center mx-auto text-emerald-600">
                      <Check className="w-6 h-6" />
                    </div>
                    <h4 className="text-lg font-bold text-slate-900">Filtración Recibida Correctamente</h4>
                    <p className="text-xs text-slate-600 leading-relaxed max-w-md mx-auto">
                      Su reporte ha sido asignado a nuestro comité de investigación técnica. Hemos eliminado los metadatos de esta sesión para resguardar su anonimato. Guarde su código de seguimiento privado:
                    </p>
                    <div className="bg-slate-100 font-mono text-sm tracking-widest font-extrabold text-slate-800 py-3 rounded-lg border border-slate-200 max-w-xs mx-auto">
                      {denunciaCode}
                    </div>
                    <div className="pt-4">
                      <button 
                        onClick={() => setIsDenunciaOpen(false)}
                        className="bg-slate-900 hover:bg-slate-950 text-white font-bold text-xs py-2 px-6 rounded-lg transition-all"
                      >
                        Cerrar Buzón
                      </button>
                    </div>
                  </div>
                ) : (
                  <form onSubmit={handleDenunciaSubmit} className="space-y-4">
                    <div>
                      <label className="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-1.5">Asunto / Temática Principal *</label>
                      <input 
                        type="text"
                        required
                        placeholder="Ej. Irregularidades en licitación de obras viales"
                        value={denunciaForm.subject}
                        onChange={e => setDenunciaForm({ ...denunciaForm, subject: e.target.value })}
                        className="w-full border border-slate-200 rounded-lg py-2 px-3 text-xs outline-none focus:border-orange-500 text-slate-800"
                      />
                    </div>

                    <div>
                      <label className="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-1.5">Organismo o Institución Involucrada</label>
                      <input 
                        type="text"
                        placeholder="Ej. Ministerio de Obras Públicas, Secretaría Regional"
                        value={denunciaForm.institution}
                        onChange={e => setDenunciaForm({ ...denunciaForm, institution: e.target.value })}
                        className="w-full border border-slate-200 rounded-lg py-2 px-3 text-xs outline-none focus:border-orange-500 text-slate-800"
                      />
                    </div>

                    <div>
                      <label className="block text-xs font-bold text-slate-700 uppercase tracking-wider mb-1.5">Descripción Detallada de los Hechos *</label>
                      <textarea 
                        required
                        rows={4}
                        placeholder="Detalle fechas, personas involucradas, desvío de fondos o conductas ilícitas de las que tiene conocimiento..."
                        value={denunciaForm.description}
                        onChange={e => setDenunciaForm({ ...denunciaForm, description: e.target.value })}
                        className="w-full border border-slate-200 rounded-lg py-2 px-3 text-xs outline-none focus:border-orange-500 text-slate-800 resize-none"
                      />
                    </div>

                    <div className="bg-slate-50 p-3.5 rounded-lg border border-slate-200/80 space-y-3">
                      <div className="flex items-center justify-between">
                        <span className="text-xs font-bold text-slate-700">Mantener mi reporte 100% Anónimo</span>
                        <button
                          type="button"
                          onClick={() => setDenunciaForm({ ...denunciaForm, isAnonymous: !denunciaForm.isAnonymous })}
                          className="text-slate-600"
                        >
                          {denunciaForm.isAnonymous ? (
                            <div className="w-10 h-6 bg-orange-500 rounded-full flex items-center justify-end p-0.5 transition-colors cursor-pointer">
                              <div className="w-5 h-5 bg-white rounded-full shadow-sm"></div>
                            </div>
                          ) : (
                            <div className="w-10 h-6 bg-slate-200 rounded-full flex items-center p-0.5 transition-colors cursor-pointer">
                              <div className="w-5 h-5 bg-white rounded-full shadow-sm"></div>
                            </div>
                          )}
                        </button>
                      </div>

                      {!denunciaForm.isAnonymous && (
                        <div>
                          <label className="block text-[11px] font-bold text-slate-600 mb-1">Información de Contacto Seguro (Email / Teléfono Encriptado)</label>
                          <input 
                            type="text"
                            placeholder="Ej. protonmail, signal o alias institucional"
                            value={denunciaForm.contactInfo}
                            onChange={e => setDenunciaForm({ ...denunciaForm, contactInfo: e.target.value })}
                            className="w-full border border-slate-200 rounded-lg py-1.5 px-3 text-xs outline-none focus:border-orange-500 text-slate-800"
                          />
                        </div>
                      )}
                    </div>

                    <div className="flex justify-end gap-3 pt-2">
                      <button 
                        type="button"
                        onClick={() => setIsDenunciaOpen(false)}
                        className="border border-slate-200 text-slate-700 font-bold text-xs py-2 px-4 rounded-lg hover:bg-slate-50 transition-colors"
                      >
                        Cancelar
                      </button>
                      <button 
                        type="submit"
                        disabled={denunciaSubmitting}
                        className="bg-orange-500 hover:bg-orange-600 disabled:bg-slate-300 text-white font-bold text-xs py-2 px-6 rounded-lg transition-all flex items-center gap-1.5"
                      >
                        {denunciaSubmitting ? (
                          <>
                            <RefreshCw className="w-3.5 h-3.5 animate-spin" /> Procesando...
                          </>
                        ) : (
                          <>
                            <Send className="w-3.5 h-3.5" /> Enviar Cifrado
                          </>
                        )}
                      </button>
                    </div>

                  </form>
                )}

              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      {/* --- HIDDEN CMS DASHBOARD OVERLAY (FULL SCREEN) --- */}
      <AnimatePresence>
        {isCmsOpen && (
          <div className="fixed inset-0 bg-slate-950 z-50 flex flex-col">
            
            {/* CMS Top Header */}
            <div className="bg-slate-900 text-white border-b border-slate-800 p-4 md:px-8 flex justify-between items-center">
              <div className="flex items-center gap-3">
                <div className="w-8 h-8 rounded-lg bg-orange-500 flex items-center justify-center text-slate-900 font-extrabold font-mono text-sm">
                  CMS
                </div>
                <div>
                  <h2 className="text-sm font-bold tracking-wider font-mono">PANEL DE CONTROL INTERNO</h2>
                  <span className="text-[10px] text-slate-400">Encuadre Editorial V2.6 • Conectado a Gemini Flash (Servidor)</span>
                </div>
              </div>
              <button 
                onClick={() => setIsCmsOpen(false)}
                className="bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white p-2 rounded-lg transition-colors flex items-center gap-1 text-xs font-semibold"
              >
                <X className="w-4 h-4" /> Cerrar Panel
              </button>
            </div>

            {/* CMS Layout Inner Grid */}
            <div className="flex-grow flex flex-col md:flex-row overflow-hidden">
              
              {/* Sidebar Tabs Selector */}
              <div className="w-full md:w-64 bg-slate-900 text-slate-300 p-4 border-r border-slate-800 flex flex-row md:flex-col gap-1 overflow-x-auto shrink-0">
                <button
                  onClick={() => setActiveCmsTab("blog")}
                  className={`w-full text-left px-4 py-3 rounded-lg text-xs font-bold font-mono uppercase tracking-wider flex items-center gap-2.5 transition-all ${
                    activeCmsTab === "blog" 
                      ? "bg-violet-900 text-white shadow" 
                      : "hover:bg-slate-800/80 hover:text-white"
                  }`}
                >
                  <FileText className="w-4 h-4 shrink-0" />
                  Redacción & IA
                </button>
                <button
                  onClick={() => setActiveCmsTab("ads")}
                  className={`w-full text-left px-4 py-3 rounded-lg text-xs font-bold font-mono uppercase tracking-wider flex items-center gap-2.5 transition-all ${
                    activeCmsTab === "ads" 
                      ? "bg-violet-900 text-white shadow" 
                      : "hover:bg-slate-800/80 hover:text-white"
                  }`}
                >
                  <Megaphone className="w-4 h-4 shrink-0" />
                  Pauta Publicitaria
                </button>
                <button
                  onClick={() => setActiveCmsTab("seo")}
                  className={`w-full text-left px-4 py-3 rounded-lg text-xs font-bold font-mono uppercase tracking-wider flex items-center gap-2.5 transition-all ${
                    activeCmsTab === "seo" 
                      ? "bg-violet-900 text-white shadow" 
                      : "hover:bg-slate-800/80 hover:text-white"
                  }`}
                >
                  <Globe className="w-4 h-4 shrink-0" />
                  Optimización SEO
                </button>

                <div className="mt-auto pt-6 border-t border-slate-800 text-center hidden md:block">
                  <div className="bg-slate-950 p-3 rounded-lg border border-slate-800/80">
                    <ShieldAlert className="w-5 h-5 text-orange-400 mx-auto mb-1.5" />
                    <span className="block text-[10px] text-slate-400 leading-tight">Credenciales autorizadas por sesión activa</span>
                  </div>
                </div>
              </div>

              {/* Main Tab Content Canvas */}
              <div className="flex-grow bg-slate-950 text-slate-100 p-4 md:p-8 overflow-y-auto">
                
                {/* TAB 1: BLOG IA & ADMINISTRACION */}
                {activeCmsTab === "blog" && (
                  <div className="space-y-8 max-w-5xl">
                    
                    {/* IA ARTICLE GENERATOR PANEL (SEO Predictivo) */}
                    <div className="bg-slate-900 rounded-xl p-6 border border-slate-800 shadow-xl relative">
                      <div className="absolute top-4 right-4 bg-violet-900 text-white text-[9px] uppercase tracking-wider font-mono font-bold px-2 py-0.5 rounded-full flex items-center gap-1">
                        <Sparkles className="w-2.5 h-2.5" /> Automatizado
                      </div>
                      
                      <div className="flex items-center gap-2 mb-4">
                        <Sparkles className="w-5 h-5 text-orange-400" />
                        <h3 className="text-sm font-bold tracking-widest font-mono uppercase text-white">Trend-Bot: Generador Editorial de IA</h3>
                      </div>
                      
                      <p className="text-slate-400 text-xs mb-5 max-w-3xl leading-relaxed">
                        Inyecta una sugerencia de tema político. El motor generará un artículo periodístico estructurado formalmente en <strong>H2/H3</strong>, con un gancho persuasivo, distribución orgánica de palabras clave e indexado de <strong>Preguntas y Respuestas (FAQ)</strong> optimizado para búsquedas.
                      </p>

                      <div className="grid grid-cols-1 md:grid-cols-12 gap-4 items-end">
                        
                        <div className="md:col-span-5">
                          <label className="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Tema Principal del Artículo</label>
                          <input 
                            type="text" 
                            placeholder="Ej. reforma jubilatoria en el senado, cumbre de gobernadores..."
                            value={iaPrompt}
                            onChange={e => setIaPrompt(e.target.value)}
                            className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white placeholder-slate-600"
                          />
                        </div>

                        <div className="md:col-span-3">
                          <label className="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Sección Destino</label>
                          <select 
                            value={iaSection}
                            onChange={e => setIaSection(e.target.value)}
                            className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white"
                          >
                            <option value="Pulso Legislativo">Pulso Legislativo</option>
                            <option value="Nacional">Nacional</option>
                            <option value="Internacional">Internacional</option>
                            <option value="Memoria Digital">Memoria Digital</option>
                          </select>
                        </div>

                        <div className="md:col-span-2">
                          <label className="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Keywords Manuales</label>
                          <input 
                            type="text" 
                            placeholder="opcional, comas..."
                            value={iaKeywords}
                            onChange={e => setIaKeywords(e.target.value)}
                            className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white placeholder-slate-700"
                          />
                        </div>

                        <div className="md:col-span-2">
                          <button
                            onClick={handleGenerateIaArticle}
                            disabled={isGeneratingIa}
                            className="w-full bg-violet-800 hover:bg-violet-700 disabled:bg-slate-800 text-white font-extrabold text-xs py-2 px-4 rounded-lg transition-all flex items-center justify-center gap-1.5"
                          >
                            {isGeneratingIa ? (
                              <>
                                <RefreshCw className="w-3.5 h-3.5 animate-spin" /> Creando...
                              </>
                            ) : (
                              <>
                                <Sparkles className="w-3.5 h-3.5 text-orange-400" /> Generar IA
                              </>
                            )}
                          </button>
                        </div>

                      </div>

                      {/* Suggested quick presets */}
                      <div className="mt-3.5 flex flex-wrap items-center gap-2">
                        <span className="text-[10px] font-bold text-slate-500 font-mono">PREAJUSTES SUGERIDOS:</span>
                        {[
                          "Crisis de coalición parlamentaria y el presupuesto",
                          "Nueva ley de subsidio al litio y minería limpia",
                          "Tratado de libre comercio y aranceles agrarios",
                          "Impacto político de la inflación y tasas del Banco"
                        ].map((txt) => (
                          <button
                            key={txt}
                            onClick={() => setIaPrompt(txt)}
                            className="bg-slate-950 hover:bg-slate-800 text-[10px] text-slate-300 border border-slate-800 py-1 px-2 rounded-md transition-colors"
                          >
                            {txt}
                          </button>
                        ))}
                      </div>

                      {/* IA LOG LOADING SCREEN STEPPER */}
                      {isGeneratingIa && (
                        <div className="mt-6 bg-slate-950/90 rounded-lg p-5 border border-slate-800 flex flex-col md:flex-row items-center gap-6 justify-between transition-all">
                          <div className="flex items-center gap-4">
                            <div className="relative">
                              <div className="w-10 h-10 border-4 border-violet-900 border-t-orange-400 rounded-full animate-spin"></div>
                              <Sparkles className="w-4 h-4 text-orange-400 absolute top-3 left-3 animate-pulse" />
                            </div>
                            <div>
                              <span className="text-xs uppercase text-orange-400 font-bold font-mono block">Escribiendo con SEO Predictivo...</span>
                              <span className="text-xs text-slate-300 font-medium tracking-wide">
                                {generationSteps[generationStepIndex]}
                              </span>
                            </div>
                          </div>
                          
                          {/* Step counters */}
                          <div className="flex gap-1.5">
                            {generationSteps.map((_, i) => (
                              <div 
                                key={i} 
                                className={`w-3.5 h-1.5 rounded transition-all ${
                                  i <= generationStepIndex ? "bg-orange-400" : "bg-slate-800"
                                }`}
                              />
                            ))}
                          </div>
                        </div>
                      )}

                    </div>

                    {/* MANUAL CREATION TOGGLE BUTTON */}
                    <div className="flex justify-between items-center">
                      <h4 className="text-xs font-bold font-mono uppercase tracking-widest text-slate-400">Publicaciones Editoriales</h4>
                      <button
                        onClick={() => setIsManualCreating(!isManualCreating)}
                        className="bg-slate-800 hover:bg-slate-700 text-white font-bold text-xs py-1.5 px-4 rounded-lg border border-slate-700 transition-colors"
                      >
                        {isManualCreating ? "Ocultar Redactor Manual" : "Redactar Artículo Manual"}
                      </button>
                    </div>

                    {/* MANUAL ARTICLE CREATION FORM */}
                    {isManualCreating && (
                      <form onSubmit={handleManualArticleSubmit} className="bg-slate-900 p-6 border border-slate-800 rounded-xl space-y-4">
                        <div className="flex items-center gap-2 pb-2 border-b border-slate-800">
                          <Plus className="w-4 h-4 text-orange-500" />
                          <h4 className="text-xs font-bold font-mono tracking-wider uppercase">Redacción Manual Tradicional</h4>
                        </div>
                        
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div>
                            <label className="block text-[10px] font-bold text-slate-400 mb-1">Título del Artículo *</label>
                            <input 
                              type="text" 
                              required
                              placeholder="Ej. El Congreso posterga el debate de reformas impositivas..."
                              value={manualArticle.title}
                              onChange={e => setManualArticle({ ...manualArticle, title: e.target.value })}
                              className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white"
                            />
                          </div>
                          <div>
                            <label className="block text-[10px] font-bold text-slate-400 mb-1">Sección *</label>
                            <select 
                              value={manualArticle.category}
                              onChange={e => setManualArticle({ ...manualArticle, category: e.target.value })}
                              className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white"
                            >
                              <option value="Pulso Legislativo">Pulso Legislativo</option>
                              <option value="Nacional">Nacional</option>
                              <option value="Internacional">Internacional</option>
                              <option value="Memoria Digital">Memoria Digital</option>
                            </select>
                          </div>
                        </div>

                        <div>
                          <label className="block text-[10px] font-bold text-slate-400 mb-1">Resumen / Bajada de Portada (Ejecutivo)</label>
                          <input 
                            type="text" 
                            placeholder="Ingrese un breve párrafo explicativo para la portada del sitio..."
                            value={manualArticle.summary}
                            onChange={e => setManualArticle({ ...manualArticle, summary: e.target.value })}
                            className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white"
                          />
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                          <div>
                            <label className="block text-[10px] font-bold text-slate-400 mb-1">Autor</label>
                            <input 
                              type="text" 
                              value={manualArticle.author}
                              onChange={e => setManualArticle({ ...manualArticle, author: e.target.value })}
                              className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white"
                            />
                          </div>
                          <div>
                            <label className="block text-[10px] font-bold text-slate-400 mb-1">Término de Imagen (Seed)</label>
                            <input 
                              type="text" 
                              placeholder="Ej. election, court, city"
                              value={manualArticle.suggestedImage}
                              onChange={e => setManualArticle({ ...manualArticle, suggestedImage: e.target.value })}
                              className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white"
                            />
                          </div>
                          <div>
                            <label className="block text-[10px] font-bold text-slate-400 mb-1">Palabras Clave (Separadas por comas)</label>
                            <input 
                              type="text" 
                              placeholder="ej. congreso, senado, ley"
                              value={manualArticle.keywords}
                              onChange={e => setManualArticle({ ...manualArticle, keywords: e.target.value })}
                              className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white"
                            />
                          </div>
                        </div>

                        <div>
                          <label className="block text-[10px] font-bold text-slate-400 mb-1">Cuerpo del Artículo * (Puede usar marcado HTML de cabeceras, negritas o listas si lo desea)</label>
                          <textarea 
                            required
                            rows={6}
                            placeholder="Escriba el contenido de la noticia o columna..."
                            value={manualArticle.content}
                            onChange={e => setManualArticle({ ...manualArticle, content: e.target.value })}
                            className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white resize-none"
                          />
                        </div>

                        <div className="flex justify-end gap-3 pt-2">
                          <button 
                            type="button"
                            onClick={() => setIsManualCreating(false)}
                            className="bg-slate-800 hover:bg-slate-700 text-slate-300 font-bold text-xs py-2 px-4 rounded-lg"
                          >
                            Cerrar
                          </button>
                          <button 
                            type="submit"
                            className="bg-orange-500 hover:bg-orange-600 text-white font-bold text-xs py-2 px-6 rounded-lg"
                          >
                            Publicar Noticia
                          </button>
                        </div>
                      </form>
                    )}

                    {/* MANAGED ARTICLES DATA DIRECTORY TABLE */}
                    <div className="bg-slate-900 rounded-xl border border-slate-800 overflow-hidden">
                      <div className="p-4 border-b border-slate-800 flex justify-between items-center bg-slate-900/60">
                        <span className="text-xs font-bold font-mono uppercase tracking-wider text-white">Directorio de Artículos</span>
                        <span className="text-[10px] text-slate-400 font-mono">Artículos Activos: {articles.length}</span>
                      </div>
                      
                      <div className="overflow-x-auto">
                        <table className="w-full text-left border-collapse">
                          <thead>
                            <tr className="border-b border-slate-800 bg-slate-950 text-[10px] text-slate-400 uppercase font-mono">
                              <th className="p-3">Título</th>
                              <th className="p-3">Sección</th>
                              <th className="p-3">Autor</th>
                              <th className="p-3">Palabras Clave (SEO)</th>
                              <th className="p-3 text-right">Acciones</th>
                            </tr>
                          </thead>
                          <tbody className="divide-y divide-slate-800 text-xs">
                            {articles.map((art) => (
                              <tr key={art.id} className="hover:bg-slate-800/40">
                                <td className="p-3 font-semibold text-slate-200 max-w-sm truncate">{art.title}</td>
                                <td className="p-3">
                                  <span className="bg-slate-950 text-orange-400 text-[9px] px-2 py-0.5 rounded border border-slate-800">
                                    {art.category}
                                  </span>
                                </td>
                                <td className="p-3 text-slate-400 font-mono">{art.author.split(" ")[0]}</td>
                                <td className="p-3 text-slate-400 truncate max-w-xs">{art.keywords.join(", ")}</td>
                                <td className="p-3 text-right space-x-2">
                                  <button
                                    onClick={() => {
                                      setActiveArticle(art);
                                      setIsCmsOpen(false);
                                    }}
                                    className="text-violet-400 hover:text-white font-bold"
                                  >
                                    Ver
                                  </button>
                                  <button
                                    onClick={() => handleDeleteArticle(art.id)}
                                    className="text-red-400 hover:text-red-300"
                                  >
                                    Eliminar
                                  </button>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </div>

                  </div>
                )}

                {/* TAB 2: AD BANNER CONTROL & SEGMENTATION */}
                {activeCmsTab === "ads" && (
                  <div className="space-y-8 max-w-5xl">
                    
                    {/* NEW BANNER FORM */}
                    <div className="bg-slate-900 border border-slate-800 rounded-xl p-6 shadow-xl">
                      <div className="flex items-center gap-2 mb-4 pb-2 border-b border-slate-800">
                        <Plus className="w-4.5 h-4.5 text-orange-400" />
                        <h3 className="text-sm font-bold tracking-wider font-mono uppercase">Inyectar Nuevo Banner Publicitario</h3>
                      </div>

                      <form onSubmit={handleAddBanner} className="space-y-4">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div>
                            <label className="block text-[10px] font-bold text-slate-400 uppercase mb-1">Título de Campaña / Anuncio *</label>
                            <input 
                              type="text" 
                              required
                              placeholder="Ej. Campaña Presidencial 2026 - Conoce Propuestas"
                              value={newBanner.title}
                              onChange={e => setNewBanner({ ...newBanner, title: e.target.value })}
                              className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white placeholder-slate-700"
                            />
                          </div>
                          <div>
                            <label className="block text-[10px] font-bold text-slate-400 uppercase mb-1">Imagen URL (Formato Banner) *</label>
                            <input 
                              type="text" 
                              required
                              placeholder="https://picsum.photos/seed/ad/1100/180"
                              value={newBanner.imageUrl}
                              onChange={e => setNewBanner({ ...newBanner, imageUrl: e.target.value })}
                              className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white placeholder-slate-700"
                            />
                          </div>
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          <div>
                            <label className="block text-[10px] font-bold text-slate-400 uppercase mb-1">Enlace de Destino (URL)</label>
                            <input 
                              type="text" 
                              placeholder="http://ejemplo.com/campaña"
                              value={newBanner.targetUrl}
                              onChange={e => setNewBanner({ ...newBanner, targetUrl: e.target.value })}
                              className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white placeholder-slate-700"
                            />
                          </div>
                          
                          {/* Segmentation selector */}
                          <div>
                            <label className="block text-[10px] font-bold text-slate-400 uppercase mb-1">Seleccionar Ubicaciones Segmentadas</label>
                            <div className="bg-slate-950 border border-slate-800 rounded-lg p-2 max-h-28 overflow-y-auto space-y-1">
                              {["Todo", "Pulso Legislativo", "Nacional", "Internacional", "Memoria Digital"].map((lbl) => (
                                <div key={lbl} className="flex items-center gap-2">
                                  <input 
                                    type="checkbox"
                                    id={`chk-b-${lbl}`}
                                    checked={newBanner.placement.includes(lbl)}
                                    onChange={(e) => {
                                      const updatedPl = e.target.checked
                                        ? [...newBanner.placement, lbl]
                                        : newBanner.placement.filter(p => p !== lbl);
                                      setNewBanner({ ...newBanner, placement: updatedPl });
                                    }}
                                    className="accent-violet-600 cursor-pointer"
                                  />
                                  <label htmlFor={`chk-b-${lbl}`} className="text-[10px] text-slate-300 font-mono cursor-pointer select-none">{lbl}</label>
                                </div>
                              ))}
                              {articles.filter(a => !a.isOpinion).map((art) => (
                                <div key={art.id} className="flex items-center gap-2">
                                  <input 
                                    type="checkbox"
                                    id={`chk-b-${art.id}`}
                                    checked={newBanner.placement.includes(art.id)}
                                    onChange={(e) => {
                                      const updatedPl = e.target.checked
                                        ? [...newBanner.placement, art.id]
                                        : newBanner.placement.filter(p => p !== art.id);
                                      setNewBanner({ ...newBanner, placement: updatedPl });
                                    }}
                                    className="accent-violet-600 cursor-pointer"
                                  />
                                  <label htmlFor={`chk-b-${art.id}`} className="text-[10px] text-slate-400 font-mono cursor-pointer select-none truncate max-w-[200px]">Art: {art.title}</label>
                                </div>
                              ))}
                            </div>
                          </div>
                        </div>

                        <div className="flex justify-end gap-3 pt-2">
                          <button 
                            type="submit"
                            className="bg-orange-500 hover:bg-orange-600 text-white font-bold text-xs py-2 px-6 rounded-lg transition-all"
                          >
                            Inyectar Pauta Publicitaria
                          </button>
                        </div>
                      </form>
                    </div>

                    {/* ACTIVE ADS TABLE */}
                    <div className="bg-slate-900 border border-slate-800 rounded-xl overflow-hidden">
                      <div className="p-4 border-b border-slate-800 bg-slate-900/60 flex justify-between items-center">
                        <span className="text-xs font-bold font-mono uppercase tracking-wider text-white">Listado de Pautas Activas</span>
                        <span className="text-[10px] text-slate-400 font-mono">Banners Totales: {banners.length}</span>
                      </div>

                      <div className="overflow-x-auto">
                        <table className="w-full text-left border-collapse">
                          <thead>
                            <tr className="border-b border-slate-800 bg-slate-950 text-[10px] text-slate-400 uppercase font-mono">
                              <th className="p-3">Campaña / Anuncio</th>
                              <th className="p-3">Destino URL</th>
                              <th className="p-3">Segmentación / Ubicaciones</th>
                              <th className="p-3">Previsualización</th>
                              <th className="p-3 text-center">Estado (Toggle)</th>
                              <th className="p-3 text-right">Acción</th>
                            </tr>
                          </thead>
                          <tbody className="divide-y divide-slate-800 text-xs">
                            {banners.map((ban) => (
                              <tr key={ban.id} className="hover:bg-slate-800/40">
                                <td className="p-3 font-semibold text-slate-200">{ban.title}</td>
                                <td className="p-3 text-slate-400 font-mono max-w-[150px] truncate">{ban.targetUrl}</td>
                                <td className="p-3 text-slate-300">
                                  <div className="flex flex-wrap gap-1">
                                    {ban.placement.map((pl, i) => (
                                      <span key={i} className="bg-slate-950 border border-slate-800 text-orange-400 text-[8px] px-1.5 py-0.5 rounded font-mono">
                                        {pl.startsWith("art-") ? "Artículo" : pl}
                                      </span>
                                    ))}
                                  </div>
                                </td>
                                <td className="p-3">
                                  <div className="w-24 h-10 border border-slate-700 rounded overflow-hidden">
                                    <img src={ban.imageUrl} alt="preview" className="w-full h-full object-cover" referrerPolicy="no-referrer" />
                                  </div>
                                </td>
                                <td className="p-3 text-center">
                                  <button
                                    onClick={() => handleToggleBanner(ban.id)}
                                    className="focus:outline-none"
                                  >
                                    {ban.isActive ? (
                                      <span className="bg-emerald-950/80 text-emerald-400 border border-emerald-800 font-mono text-[9px] uppercase font-bold py-1 px-3 rounded-md cursor-pointer block text-center">
                                        Activo
                                      </span>
                                    ) : (
                                      <span className="bg-slate-950 text-slate-500 border border-slate-800 font-mono text-[9px] uppercase font-bold py-1 px-3 rounded-md cursor-pointer block text-center">
                                        Inactivo
                                      </span>
                                    )}
                                  </button>
                                </td>
                                <td className="p-3 text-right">
                                  <button
                                    onClick={() => {
                                      const updated = banners.filter(b => b.id !== ban.id);
                                      updateBannersInStateAndStorage(updated);
                                    }}
                                    className="text-red-400 hover:text-red-300 font-bold"
                                  >
                                    Remover
                                  </button>
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </div>

                  </div>
                )}

                {/* TAB 3: GLOBAL & LOCAL SEO META MODIFICATION */}
                {activeCmsTab === "seo" && (
                  <div className="space-y-8 max-w-5xl">
                    
                    {/* SYSTEM GLOBAL SEO FORM */}
                    <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
                      
                      {/* Left: Settings Panel */}
                      <div className="lg:col-span-6 space-y-6">
                        
                        {/* Global Settings */}
                        <div className="bg-slate-900 border border-slate-800 rounded-xl p-5 shadow-xl space-y-4">
                          <div className="flex items-center gap-2 pb-2 border-b border-slate-800">
                            <Globe className="w-4.5 h-4.5 text-violet-400" />
                            <h3 className="text-sm font-bold tracking-wider font-mono uppercase">Metadatos SEO Globales</h3>
                          </div>

                          <div className="space-y-3">
                            <div>
                              <label className="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Meta-Título Principal</label>
                              <input 
                                type="text"
                                value={globalSEO.title}
                                onChange={e => updateGlobalSEOStateAndStorage({ ...globalSEO, title: e.target.value })}
                                className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white"
                              />
                            </div>
                            <div>
                              <label className="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Meta-Descripción General</label>
                              <textarea
                                rows={3}
                                value={globalSEO.description}
                                onChange={e => updateGlobalSEOStateAndStorage({ ...globalSEO, description: e.target.value })}
                                className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white resize-none"
                              />
                            </div>
                            <div>
                              <label className="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Palabras Clave SEO (Keywords)</label>
                              <input 
                                type="text"
                                value={globalSEO.keywords}
                                onChange={e => updateGlobalSEOStateAndStorage({ ...globalSEO, keywords: e.target.value })}
                                className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white"
                              />
                            </div>
                          </div>
                        </div>

                        {/* Local Settings */}
                        <div className="bg-slate-900 border border-slate-800 rounded-xl p-5 shadow-xl space-y-4">
                          <div className="flex items-center gap-2 pb-2 border-b border-slate-800">
                            <FileText className="w-4.5 h-4.5 text-orange-400" />
                            <h3 className="text-sm font-bold tracking-wider font-mono uppercase">Optimización por Artículo (SEO Local)</h3>
                          </div>

                          <div className="space-y-3">
                            <div>
                              <label className="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1 font-mono">Seleccione Artículo para Editar</label>
                              <select
                                value={selectedSeoArticleId}
                                onChange={e => setSelectedSeoArticleId(e.target.value)}
                                className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white"
                              >
                                {articles.map(a => (
                                  <option key={a.id} value={a.id}>{a.title}</option>
                                ))}
                              </select>
                            </div>

                            <form onSubmit={handleSaveLocalSeo} className="space-y-3">
                              <div>
                                <label className="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Título de Búsqueda Personalizado</label>
                                <input 
                                  type="text"
                                  value={localSeoData.title}
                                  onChange={e => setLocalSeoData({ ...localSeoData, title: e.target.value })}
                                  className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white"
                                />
                              </div>
                              <div>
                                <label className="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Descripción de Snippet (Google)</label>
                                <textarea 
                                  rows={2}
                                  value={localSeoData.summary}
                                  onChange={e => setLocalSeoData({ ...localSeoData, summary: e.target.value })}
                                  className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white resize-none"
                                />
                              </div>
                              <div>
                                <label className="block text-[10px] font-bold text-slate-400 uppercase tracking-wider mb-1">Palabras Clave Locales</label>
                                <input 
                                  type="text"
                                  value={localSeoData.keywords}
                                  onChange={e => setLocalSeoData({ ...localSeoData, keywords: e.target.value })}
                                  className="w-full bg-slate-950 border border-slate-800 rounded-lg py-2 px-3 text-xs outline-none focus:border-violet-600 text-white"
                                />
                              </div>
                              
                              <div className="pt-2">
                                <button 
                                  type="submit"
                                  className="bg-violet-800 hover:bg-violet-700 text-white font-bold text-xs py-2 px-4 rounded-lg w-full transition-all"
                                >
                                  Re-indexar Artículo Local
                                </button>
                              </div>
                            </form>
                          </div>
                        </div>

                      </div>

                      {/* Right: Search Engines Previews Engine */}
                      <div className="lg:col-span-6 space-y-6">
                        
                        {/* Google Search Mockup Snippet */}
                        <div className="bg-white border border-slate-200 rounded-xl p-5 shadow-xl text-slate-900">
                          <span className="text-[10px] font-mono uppercase tracking-wider font-bold text-slate-500 block mb-3 border-b pb-2">Vista Previa: Buscador de Google (SERP)</span>
                          
                          <div className="font-sans">
                            <span className="text-xs text-slate-600 block mb-1">https://www.encuadre.com</span>
                            <h4 className="text-lg text-blue-800 hover:underline font-medium cursor-pointer tracking-tight leading-snug line-clamp-2">
                              {localSeoData.title || globalSEO.title}
                            </h4>
                            <p className="text-xs text-slate-600 mt-1 line-clamp-2 leading-relaxed">
                              {localSeoData.summary || globalSEO.description}
                            </p>
                          </div>

                          <div className="mt-4 pt-3 border-t border-slate-100 flex items-center justify-between">
                            <span className="text-[10px] text-slate-400 font-mono">Indexado en tiempo real: Forzado</span>
                            <span className="bg-slate-100 text-slate-700 text-[9px] px-2 py-0.5 rounded font-mono font-bold uppercase tracking-wider">LCP: 0.8s</span>
                          </div>
                        </div>

                        {/* AI OVERVIEW / GEMINI SEARCH INSIGHT PREVIEW */}
                        <div className="bg-gradient-to-tr from-violet-950/90 to-violet-900 border border-violet-800 rounded-xl p-5 shadow-xl text-white">
                          <div className="flex items-center gap-1.5 mb-3 border-b border-violet-800 pb-2">
                            <Sparkles className="w-4 h-4 text-orange-400" />
                            <span className="text-[10px] font-mono uppercase tracking-wider font-bold text-violet-200">Búsqueda Inteligente (Gemini AI Overview)</span>
                          </div>

                          <div className="space-y-3 font-sans">
                            <span className="text-[10px] bg-violet-800 text-orange-300 font-mono font-bold py-0.5 px-2 rounded-full inline-block">Análisis Predictivo de IA</span>
                            
                            <h4 className="text-sm font-extrabold text-white tracking-tight leading-snug">
                              ¿Qué dice el portal Encuadre sobre {localSeoData.title ? `"${localSeoData.title.substring(0, 45)}..."` : "la agenda de gobierno"}?
                            </h4>
                            
                            <p className="text-xs text-violet-100 leading-relaxed font-medium">
                              Basado en la indexación de Encuadre, se prevé una cobertura prioritaria en torno a: <strong>{localSeoData.keywords || globalSEO.keywords}</strong>. El análisis detalla que {localSeoData.summary ? localSeoData.summary : globalSEO.description}
                            </p>

                            <div className="bg-violet-950/60 p-3 rounded-lg border border-violet-800/80 space-y-1">
                              <span className="text-[9px] font-mono text-violet-300 uppercase block">Fuentes del Resumen</span>
                              <div className="flex items-center gap-2 text-[10px]">
                                <span className="text-orange-400 font-bold font-serif">ENC</span>
                                <span className="text-slate-300 underline font-medium truncate max-w-[200px]">{localSeoData.title || articles[0]?.title}</span>
                              </div>
                            </div>
                          </div>

                          <div className="mt-4 pt-3 border-t border-violet-800 flex items-center justify-between text-[10px] text-violet-300 font-mono">
                            <span>Sincronizado vía AI Studio</span>
                            <span className="flex items-center gap-1"><CheckSquare className="w-3.5 h-3.5 text-orange-400" /> Optimizado</span>
                          </div>
                        </div>

                      </div>

                    </div>

                  </div>
                )}

              </div>

            </div>

          </div>
        )}
      </AnimatePresence>

      {/* --- FOOTER & CAMOUFLAGED ADMIN ENTRY --- */}
      <footer className="bg-slate-900 text-slate-400 text-xs py-10 px-4 md:px-8 border-t border-slate-800">
        <div className="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-center gap-6">
          
          <div className="flex flex-col items-center md:items-start">
            <div className="flex items-baseline gap-1 cursor-pointer" onClick={() => setActiveArticle(null)}>
              <span className="text-xl font-bold tracking-tighter text-white font-serif">ENCUADRE</span>
              <span className="w-1.5 h-1.5 rounded-full bg-orange-500"></span>
            </div>
            <span className="text-[10px] text-slate-500 font-mono tracking-widest uppercase mt-1">Periodismo Político de Alta Precisión</span>
          </div>

          <div className="flex flex-wrap justify-center gap-6 text-slate-500 font-medium">
            <a href="#" className="hover:text-slate-300 transition-colors">Términos de Servicio</a>
            <a href="#" className="hover:text-slate-300 transition-colors">Aviso de Privacidad</a>
            <a href="#" className="hover:text-slate-300 transition-colors">Contacto Institucional</a>
          </div>

          <div className="flex items-center gap-4 text-slate-500">
            <span>© 2026 Encuadre Político.</span>
            
            {/* Camouflaged sutil CMS access button requested in prompts */}
            <button 
              onClick={() => {
                setActiveCmsTab("blog");
                setIsCmsOpen(true);
              }}
              id="camouflaged_cms_btn"
              title="Mesa de Control Interno"
              className="text-slate-800 hover:text-slate-600 focus:outline-none transition-colors duration-300 cursor-default"
            >
              <Settings className="w-3 h-3" />
            </button>
          </div>

        </div>
      </footer>

    </div>
  );
}
