// CNG Technology Use Guide - Tab-based navigation + data-driven content
// app.jsx — Visual design from CNG-SiteMap-Mockup.jsx, all content from Google Sheets

const { useState, useEffect, useRef } = React;
const { Globe, Shield, BookOpen, Monitor, Clock, Home, Laptop, MessageCircle, ChevronRight, Menu, X, Lock, Eye, Users, ArrowRight, Zap, Heart, Brain, Send, Bot, Star, Settings, Cpu, Wifi, HardDrive, MonitorSmartphone, ExternalLink, CheckCircle2, Sparkles, ThumbsUp, ThumbsDown, School, Layers, RefreshCw, ChevronDown, Smartphone } = LucideReact;

// ============ DEVICE DETECTION ============
function detectDeviceType() {
  const ua = navigator.userAgent;
  if (/tablet|ipad|playbook|silk/i.test(ua) || (/android/i.test(ua) && !/mobile/i.test(ua))) return 'tablet';
  if (/mobile|iphone|ipod|android.*mobile|webos|blackberry|opera mini|iemobile/i.test(ua)) return 'mobile';
  return 'desktop';
}

function detectBrowser() {
  const ua = navigator.userAgent;
  if (ua.includes('Edg/')) { const v = ua.match(/Edg\/([\d.]+)/); return 'Edge ' + (v ? v[1].split('.')[0] : ''); }
  if (ua.includes('OPR/') || ua.includes('Opera/')) { const v = ua.match(/OPR\/([\d.]+)/); return 'Opera ' + (v ? v[1].split('.')[0] : ''); }
  if (ua.includes('Chrome/') && !ua.includes('Edg/')) { const v = ua.match(/Chrome\/([\d.]+)/); return 'Chrome ' + (v ? v[1].split('.')[0] : ''); }
  if (ua.includes('Safari/') && !ua.includes('Chrome/')) { const v = ua.match(/Version\/([\d.]+)/); return 'Safari ' + (v ? v[1].split('.')[0] : ''); }
  if (ua.includes('Firefox/')) { const v = ua.match(/Firefox\/([\d.]+)/); return 'Firefox ' + (v ? v[1].split('.')[0] : ''); }
  return 'Other';
}

const DEVICE_TYPE = detectDeviceType();
const BROWSER_NAME = detectBrowser();

// ============ CONFIGURATION ============
const CONFIG = {
  API_URL: 'https://techguide-api-bot.green-king-4a92.workers.dev',
  SHEETS: {
    config: 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRIL-UCSOCH2swVsucn6ADV-4kqeA9xJLUeDt8ZN-R7K7lWXIZnDynGwAkdMRbYQRgwPBKUnLpDFXyy/pub?gid=43748082&single=true&output=csv',
    overview: 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRIL-UCSOCH2swVsucn6ADV-4kqeA9xJLUeDt8ZN-R7K7lWXIZnDynGwAkdMRbYQRgwPBKUnLpDFXyy/pub?gid=10125262&single=true&output=csv',
    byod: 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRIL-UCSOCH2swVsucn6ADV-4kqeA9xJLUeDt8ZN-R7K7lWXIZnDynGwAkdMRbYQRgwPBKUnLpDFXyy/pub?gid=2000694559&single=true&output=csv',
    apps: 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRIL-UCSOCH2swVsucn6ADV-4kqeA9xJLUeDt8ZN-R7K7lWXIZnDynGwAkdMRbYQRgwPBKUnLpDFXyy/pub?gid=1431586618&single=true&output=csv',
    filtering: 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRIL-UCSOCH2swVsucn6ADV-4kqeA9xJLUeDt8ZN-R7K7lWXIZnDynGwAkdMRbYQRgwPBKUnLpDFXyy/pub?gid=516137570&single=true&output=csv',
    grades: 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRIL-UCSOCH2swVsucn6ADV-4kqeA9xJLUeDt8ZN-R7K7lWXIZnDynGwAkdMRbYQRgwPBKUnLpDFXyy/pub?gid=403844015&single=true&output=csv',
    parental: 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRIL-UCSOCH2swVsucn6ADV-4kqeA9xJLUeDt8ZN-R7K7lWXIZnDynGwAkdMRbYQRgwPBKUnLpDFXyy/pub?gid=1618309637&single=true&output=csv',
    faq: 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRIL-UCSOCH2swVsucn6ADV-4kqeA9xJLUeDt8ZN-R7K7lWXIZnDynGwAkdMRbYQRgwPBKUnLpDFXyy/pub?gid=1630426286&single=true&output=csv',
    resources: 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRIL-UCSOCH2swVsucn6ADV-4kqeA9xJLUeDt8ZN-R7K7lWXIZnDynGwAkdMRbYQRgwPBKUnLpDFXyy/pub?gid=617891267&single=true&output=csv',
    ai: 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRIL-UCSOCH2swVsucn6ADV-4kqeA9xJLUeDt8ZN-R7K7lWXIZnDynGwAkdMRbYQRgwPBKUnLpDFXyy/pub?gid=69910011&single=true&output=csv',
    classwize: 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRIL-UCSOCH2swVsucn6ADV-4kqeA9xJLUeDt8ZN-R7K7lWXIZnDynGwAkdMRbYQRgwPBKUnLpDFXyy/pub?gid=1600917523&single=true&output=csv',
    qustodio: 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRIL-UCSOCH2swVsucn6ADV-4kqeA9xJLUeDt8ZN-R7K7lWXIZnDynGwAkdMRbYQRgwPBKUnLpDFXyy/pub?gid=1984087685&single=true&output=csv',
    parenthub: 'https://docs.google.com/spreadsheets/d/e/2PACX-1vRIL-UCSOCH2swVsucn6ADV-4kqeA9xJLUeDt8ZN-R7K7lWXIZnDynGwAkdMRbYQRgwPBKUnLpDFXyy/pub?gid=910805439&single=true&output=csv'
  }
};

const DATA_CATEGORIES = [
  { id: 'overview', name: 'Policies & Philosophy', nameEs: 'Políticas y Filosofía', icon: '📋', sheet: 'overview' },
  { id: 'byod', name: 'BYOD Devices', nameEs: 'Dispositivos BYOD', icon: '💻', sheet: 'byod', isTable: true },
  { id: 'apps', name: 'App Restrictions', nameEs: 'Restricciones de Apps', icon: '📱', sheet: 'apps', isTable: true },
  { id: 'ai', name: 'AI Tools', nameEs: 'Herramientas IA', icon: '🤖', sheet: 'ai', isTable: true },
  { id: 'filtering', name: 'Web Filtering', nameEs: 'Filtrado Web', icon: '🛡️', sheet: 'filtering', isTable: true },
  { id: 'grades', name: 'Grade Guidelines', nameEs: 'Guías por Grado', icon: '🎓', sheet: 'grades', isTable: true },
  { id: 'parental', name: 'Parental Controls', nameEs: 'Controles Parentales', icon: '👨‍👩‍👧', sheet: 'parental', isTable: true },
  { id: 'faq', name: 'FAQ', nameEs: 'Preguntas Frecuentes', icon: '❓', sheet: 'faq', isFaq: true },
  { id: 'resources', name: 'Resources', nameEs: 'Recursos', icon: '🔗', sheet: 'resources' }
];

async function loadSheet(url) {
  const res = await fetch(url);
  const csv = await res.text();
  return new Promise(r => Papa.parse(csv, { header: true, skipEmptyLines: true, complete: res => r(res.data) }));
}
function get(obj, ...keys) { for (const k of keys) if (obj[k]) return obj[k]; return ''; }

// UI-only labels (navigation chrome, no content)
const ui = {
  en: {
    nav: ["School","Citizenship","Safety","Screen Time","Home","BYOD","Data"],
    navIds: ["philosophy","citizenship","controls","screentime","home","byod","data"],
    langToggle:"ES", askAI:"Ask AI", explore:"Explore", viewData:"View Detailed Data",
    heroBadge:"2025–2026 School Year", heroPre:"Colegio Nueva Granada",
    heroT1:"Digital", heroT2:"Wellbeing",
    heroCta1:"Explore Guide", heroCta2:"Ask AI Assistant",
    chatGreeting:"Hi! I'm CNG's Tech Guide assistant. Ask me anything about our technology policies, BYOD requirements, digital citizenship, or parental controls. How can I help?",
    chatPlaceholder:"Type your question...", chatOnline:"Online · Ready to help",
    chatTitle:"Need answers?", chatSub:"Our AI assistant knows everything about CNG's technology policies.",
    chatCta:"Start a Conversation", loading:"Loading Technology Guide...",
    connErr:"Connection error. Please try again.", noProc:"I could not process that.",
    privacyNotice:"Questions are logged anonymously to improve this guide.",
    tabs: { school: "At School", home: "At Home", bridge: "360° Protection" },
    navGroups: [
      { label: "Definitions", items: [
        { label: "Our Philosophy", id: "philosophy", tab: "school" },
        { label: "Citizenship", id: "citizenship", tab: "school" },
      ]},
      { label: "Access & Controls", items: [
        { label: "App Restrictions", id: "controls", tab: "school" },
        { label: "Parental Controls", id: "home", tab: "home" },
        { label: "Screen Time", id: "screentime", tab: "home" }
      ]},
      { label: "BYOD", items: [
        { label: "Device Specs", id: "byod", tab: "bridge" },
        { label: "360° Protection", id: "integration", tab: "bridge" }
      ]},
      { label: "Resources", items: [
        { label: "Resources", id: "resources", tab: null, modal: "resources" }
      ]},
      { label: "Online Safety Hub", external: "https://cng.onlinesafetyhub.uk/" }
    ],
    integrationLabel: "Seamless Protection",
    integrationTitle: "Qustodio + Linewize",
    integrationSubtitle: "How seamless 360° protection works — everywhere, all the time",
    integrationIntro: "CNG uses Linewize for school network filtering and recommends Qustodio for home. Together, they create continuous protection that adapts automatically as students move between school, home, and on the go.",
    integrationTrafficTitle: "Traffic Flow",
    integrationBlockTitle: "Block Pages",
    integrationBlockDesc: "When content is blocked, students see clear messages explaining why:",
    integrationSchoolBlock: "School block: \"This site is restricted by your school's policy.\"",
    integrationParentBlock: "Parent block: \"This site is restricted by your family's settings.\"",
    integrationFaqTitle: "Frequently Asked Questions",
    bentoCards: [
      { icon:"book", label:"Philosophy", desc:"Why we use technology", tag:"School" },
      { icon:"globe", label:"Digital Citizenship", desc:"Building digital leaders", tag:"Core" },
      { icon:"shield", label:"Access & Controls", desc:"Network-level protections", tag:"Safety" },
      { icon:"clock", label:"Screen Time", desc:"Age-based recommendations", tag:"Health" },
      { icon:"home", label:"Parental Controls", desc:"Tools for families", tag:"Home" },
      { icon:"laptop", label:"BYOD Program", desc:"Device specifications", tag:"MS/HS" },
      { icon:"layers", label:"360° Protection", desc:"Qustodio + Linewize", tag:"Bridge" },
      { icon:"bot", label:"AI Assistant", desc:"Get instant answers", tag:"New" }
    ],
  },
  es: {
    nav: ["Colegio","Ciudadanía","Seguridad","Pantalla","Hogar","BYOD","Datos"],
    navIds: ["philosophy","citizenship","controls","screentime","home","byod","data"],
    langToggle:"EN", askAI:"IA", explore:"Explorar", viewData:"Ver Datos Detallados",
    heroBadge:"Año Escolar 2025–2026", heroPre:"Colegio Nueva Granada",
    heroT1:"Bienestar", heroT2:"Digital",
    heroCta1:"Explorar Guía", heroCta2:"Preguntar al Asistente",
    chatGreeting:"¡Hola! Soy el asistente de la Guía Tecnológica de CNG. Pregúntame sobre políticas de tecnología, requisitos BYOD, ciudadanía digital o controles parentales. ¿En qué te puedo ayudar?",
    chatPlaceholder:"Escribe tu pregunta...", chatOnline:"En línea · Listo para ayudar",
    chatTitle:"¿Necesitas respuestas?", chatSub:"Nuestro asistente de IA conoce todo sobre las políticas tecnológicas de CNG.",
    chatCta:"Iniciar Conversación", loading:"Cargando Guía Tecnológica...",
    connErr:"Error de conexión. Intenta de nuevo.", noProc:"No pude procesar eso.",
    privacyNotice:"Las preguntas se registran de forma anónima para mejorar esta guía.",
    tabs: { school: "En el Colegio", home: "En Casa", bridge: "Protección 360°" },
    navGroups: [
      { label: "Definiciones", items: [
        { label: "Nuestra Filosofía", id: "philosophy", tab: "school" },
        { label: "Ciudadanía", id: "citizenship", tab: "school" },
      ]},
      { label: "Acceso y Controles", items: [
        { label: "Restricciones de Apps", id: "controls", tab: "school" },
        { label: "Controles Parentales", id: "home", tab: "home" },
        { label: "Tiempo en Pantalla", id: "screentime", tab: "home" }
      ]},
      { label: "BYOD", items: [
        { label: "Especificaciones", id: "byod", tab: "bridge" },
        { label: "Protección 360°", id: "integration", tab: "bridge" }
      ]},
      { label: "Recursos", items: [
        { label: "Recursos", id: "resources", tab: null, modal: "resources" }
      ]},
      { label: "Online Safety Hub", external: "https://cng.onlinesafetyhub.uk/" }
    ],
    integrationLabel: "Protección Continua",
    integrationTitle: "Qustodio + Linewize",
    integrationSubtitle: "Cómo funciona la protección 360° — en todas partes, todo el tiempo",
    integrationIntro: "CNG usa Linewize para el filtrado de la red escolar y recomienda Qustodio para el hogar. Juntos, crean una protección continua que se adapta automáticamente.",
    integrationTrafficTitle: "Flujo de Tráfico",
    integrationBlockTitle: "Páginas de Bloqueo",
    integrationBlockDesc: "Cuando se bloquea contenido, los estudiantes ven mensajes claros:",
    integrationSchoolBlock: "Bloqueo escolar: \"Este sitio está restringido por la política de tu colegio.\"",
    integrationParentBlock: "Bloqueo parental: \"Este sitio está restringido por la configuración de tu familia.\"",
    integrationFaqTitle: "Preguntas Frecuentes",
    bentoCards: [
      { icon:"book", label:"Filosofía", desc:"Por qué usamos tecnología", tag:"Colegio" },
      { icon:"globe", label:"Ciudadanía Digital", desc:"Formando líderes digitales", tag:"Central" },
      { icon:"shield", label:"Acceso y Controles", desc:"Protecciones de red", tag:"Seguridad" },
      { icon:"clock", label:"Tiempo en Pantalla", desc:"Recomendaciones por edad", tag:"Salud" },
      { icon:"home", label:"Controles Parentales", desc:"Herramientas para familias", tag:"Hogar" },
      { icon:"laptop", label:"Programa BYOD", desc:"Especificaciones de dispositivos", tag:"MS/HS" },
      { icon:"layers", label:"Protección 360°", desc:"Qustodio + Linewize", tag:"Puente" },
      { icon:"bot", label:"Asistente IA", desc:"Respuestas instantáneas", tag:"Nuevo" }
    ],
  }
};

// ============ Utilities ============
function Counter({ target, suffix = "" }) {
  const [v, setV] = useState(0); const ref = useRef(null); const done = useRef(false);
  useEffect(() => { const obs = new IntersectionObserver(([e]) => { if (e.isIntersecting && !done.current) { done.current = true; let s = 0; const step = Math.max(1, Math.ceil(target / 60)); const id = setInterval(() => { s += step; if (s >= target) { setV(target); clearInterval(id); } else setV(s); }, 20); obs.disconnect(); } }, { threshold: 0.3 }); ref.current && obs.observe(ref.current); return () => obs.disconnect(); }, [target]);
  return <span ref={ref}>{v.toLocaleString()}{suffix}</span>;
}

function Reveal({ children, delay = 0, style = {} }) {
  const ref = useRef(null); const [vis, setVis] = useState(false);
  useEffect(() => { const obs = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setVis(true); obs.disconnect(); } }, { threshold: 0.1 }); ref.current && obs.observe(ref.current); return () => obs.disconnect(); }, []);
  return <div ref={ref} style={{ ...style, opacity: vis ? 1 : 0, transform: vis ? "translateY(0)" : "translateY(40px)", transition: `opacity 0.7s cubic-bezier(0.16,1,0.3,1) ${delay}s, transform 0.7s cubic-bezier(0.16,1,0.3,1) ${delay}s` }}>{children}</div>;
}

function groupBy(arr, key) { const g = {}; (arr||[]).forEach(r => { const k = r[key] || 'Other'; if (!g[k]) g[k] = []; g[k].push(r); }); return g; }

// ============ Chat message renderer with clickable references ============
// Parses [Label](#modal:sheet), [Label](#section:id), [Label](url) into clickable links
function ChatMessage({ text, onOpenModal, onScrollTo }) {
  if (!text) return null;
  // Single regex handles all link types: modal, section, and external URLs
  // Allows optional space between ] and (
  const regex = /\[([^\]]+)\]\s*\(#(modal|section):([^)]+)\)|\[([^\]]+)\]\s*\((https?:\/\/[^)]+)\)/g;
  const parts = [];
  let last = 0;
  let match;
  while ((match = regex.exec(text)) !== null) {
    if (match.index > last) parts.push({ type: 'text', value: text.slice(last, match.index) });
    if (match[1]) {
      parts.push({ type: match[2], label: match[1], id: match[3] });
    } else if (match[4]) {
      parts.push({ type: 'url', label: match[4], url: match[5] });
    }
    last = match.index + match[0].length;
  }
  if (last < text.length) parts.push({ type: 'text', value: text.slice(last) });

  return <>{parts.map((p, i) => renderPart(p, i, onOpenModal, onScrollTo))}</>;
}

function renderPart(p, i, onOpenModal, onScrollTo) {
  const linkStyle = { color: "#0F4C81", fontWeight: 600, cursor: "pointer", textDecoration: "underline", textDecorationColor: "rgba(15,76,129,0.3)", textUnderlineOffset: "2px" };
  if (p.type === 'modal') {
    return <span key={i} style={linkStyle} onClick={() => onOpenModal(p.id)}>{p.label}</span>;
  }
  if (p.type === 'section') {
    return <span key={i} style={linkStyle} onClick={() => onScrollTo(p.id)}>{p.label}</span>;
  }
  if (p.type === 'url') {
    return <a key={i} href={p.url} target="_blank" rel="noopener noreferrer" style={{ ...linkStyle, textDecoration: "underline" }}>{p.label}</a>;
  }
  // Plain text — preserve newlines
  return <span key={i}>{p.value}</span>;
}

// ============ Enriched table cell notes ============
const NOTE_INFO = {
  "Restricted Mode enabled on all CNG accounts": {
    en: {
      title: "YouTube Restricted Mode",
      body: "YouTube Restricted Mode is a built-in feature that helps filter out potentially mature or inappropriate content. When enabled on CNG school accounts, it hides videos that have been flagged by users or that YouTube's algorithms identify as containing inappropriate content. Teachers can still approve specific videos for educational purposes.",
      link: "https://support.google.com/youtube/answer/7354993?hl=en#zippy=%2Cwhat-does-restricted-mode-do",
      linkLabel: "More info on YouTube Restricted Mode"
    },
    es: {
      title: "Modo Restringido de YouTube",
      body: "El Modo Restringido de YouTube es una función integrada que ayuda a filtrar contenido potencialmente inapropiado. Cuando está habilitado en las cuentas escolares de CNG, oculta videos que han sido marcados por usuarios o que los algoritmos de YouTube identifican como contenido inapropiado. Los profesores pueden aprobar videos específicos para fines educativos.",
      link: "https://support.google.com/youtube/answer/7354993?hl=es#zippy=%2Cwhat-does-restricted-mode-do",
      linkLabel: "Más información sobre el Modo Restringido"
    }
  }
};

function NoteCell({ value, lang }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const info = NOTE_INFO[value];
  if (!info) return <>{value}</>;
  const t = info[lang] || info.en;

  // Calculate fixed position from the trigger element
  const [pos, setPos] = useState({ top:0, left:0 });
  const handleOpen = () => {
    if (ref.current) {
      const rect = ref.current.getBoundingClientRect();
      setPos({ top: rect.bottom + 8, left: Math.min(rect.left, window.innerWidth - 360) });
    }
    setOpen(!open);
  };

  return (
    <span>
      <span ref={ref} onClick={handleOpen} style={{ cursor:"pointer",color:"#0F4C81",fontWeight:600,borderBottom:"1.5px dashed #0F4C81",paddingBottom:1 }}>
        {value} <Globe size={12} style={{ verticalAlign:"middle",marginLeft:4,color:"#0F4C81" }}/>
      </span>
      {open && ReactDOM.createPortal(
        <div style={{ position:"fixed",inset:0,zIndex:2000 }} onClick={() => setOpen(false)}>
          <div style={{ position:"fixed",top:pos.top,left:pos.left,width:350,background:"white",borderRadius:16,boxShadow:"0 16px 48px rgba(0,0,0,0.22), 0 0 0 1px rgba(0,0,0,0.05)",zIndex:2001,overflow:"hidden",animation:"fadeUp 0.25s ease" }} onClick={e => e.stopPropagation()}>
            <div style={{ background:"linear-gradient(135deg,#0F4C81,#1A6FB5)",padding:"16px 20px",display:"flex",alignItems:"center",justifyContent:"space-between" }}>
              <span style={{ fontSize:14,fontWeight:800,color:"white",fontFamily:"'Sora',sans-serif" }}>{t.title}</span>
              <button onClick={() => setOpen(false)} style={{ background:"rgba(255,255,255,0.15)",border:"none",borderRadius:8,width:28,height:28,cursor:"pointer",color:"white",display:"flex",alignItems:"center",justifyContent:"center" }}><X size={14}/></button>
            </div>
            <div style={{ padding:"16px 20px" }}>
              <p style={{ fontSize:13,color:"#475569",lineHeight:1.7,marginBottom:14 }}>{t.body}</p>
              <a href={t.link} target="_blank" rel="noopener noreferrer" style={{ display:"inline-flex",alignItems:"center",gap:6,fontSize:12.5,fontWeight:700,color:"#0F4C81",textDecoration:"none",padding:"8px 14px",borderRadius:10,background:"#EFF6FF",border:"1px solid #DBEAFE",transition:"all 0.2s" }}
                onMouseEnter={e => { e.currentTarget.style.background="#DBEAFE"; }}
                onMouseLeave={e => { e.currentTarget.style.background="#EFF6FF"; }}>
                <ExternalLink size={13}/> {t.linkLabel}
              </a>
            </div>
          </div>
        </div>,
        document.body
      )}
    </span>
  );
}

// ============ Qustodio + Linewize diagram data ============
function getDiagramScenarios(isEn) {
  return [
    {
      id: "school",
      title: isEn ? "At School (CNG Network)" : "En el Colegio (Red CNG)",
      subtitle: isEn ? "Student connects to CNG's secure WiFi" : "El estudiante se conecta al WiFi seguro de CNG",
      icon: <School size={22}/>,
      bg: "#EFF6FF", border: "#3B82F6", color: "#1E40AF",
      linewize: { active: true, label: isEn ? "ACTIVE" : "ACTIVO", desc: isEn ? "School filtering rules apply: content filter, YouTube restricted, app control, device monitoring." : "Aplican reglas del colegio: filtro de contenido, YouTube restringido, control de apps, monitoreo." },
      qustodio: { active: false, label: isEn ? "PAUSED" : "EN PAUSA", desc: isEn ? "Automatically deactivates to avoid conflicts. No interference with learning tools." : "Se desactiva automáticamente para evitar conflictos. Sin interferencia con herramientas." },
      note: isEn ? "Cloud Safe Network detects the school network and signals Qustodio to pause." : "Cloud Safe Network detecta la red del colegio y señala a Qustodio que se pause."
    },
    {
      id: "home",
      title: isEn ? "At Home (Home WiFi)" : "En Casa (WiFi del Hogar)",
      subtitle: isEn ? "Student connects to home network" : "El estudiante se conecta a la red del hogar",
      icon: <Home size={22}/>,
      bg: "#ECFDF5", border: "#10B981", color: "#065F46",
      linewize: { active: false, label: isEn ? "PAUSED" : "EN PAUSA", desc: isEn ? "School network filter is paused at home. Base safety policies no longer apply directly." : "El filtro de red escolar está en pausa en casa. Las políticas base ya no aplican directamente." },
      qustodio: { active: true, label: isEn ? "ACTIVE" : "ACTIVO", desc: isEn ? "Parent rules activate: custom filtering, screen time limits, daily routines, activity reports." : "Las reglas parentales se activan: filtrado personalizado, límites de tiempo, rutinas, informes." },
      note: isEn ? "At home, Linewize pauses and Qustodio takes over with parent-configured rules." : "En casa, Linewize se pausa y Qustodio toma el control con las reglas configuradas por los padres."
    },
    {
      id: "mobile",
      title: isEn ? "On the Go (Mobile Data)" : "Fuera de Casa (Datos Móviles)",
      subtitle: isEn ? "Student uses mobile data away from both networks" : "El estudiante usa datos móviles fuera de ambas redes",
      icon: <Smartphone size={22}/>,
      bg: "#FFF7ED", border: "#F59E0B", color: "#92400E",
      linewize: { active: false, label: isEn ? "PAUSED" : "EN PAUSA", desc: isEn ? "School network filter is paused outside campus WiFi." : "El filtro de red escolar está en pausa fuera del WiFi del campus." },
      qustodio: { active: true, label: isEn ? "ACTIVE" : "ACTIVO", desc: isEn ? "All parent rules apply: filtering, screen time, location tracking, app blocking." : "Todas las reglas parentales aplican: filtrado, tiempo, ubicación, bloqueo de apps." },
      note: isEn ? "Qustodio provides full standalone protection when no school network is detected." : "Qustodio proporciona protección completa cuando no se detecta la red del colegio."
    }
  ];
}

function getFaqItems(isEn) {
  return [
    {
      q: isEn ? "Do I need to configure anything for the automatic switching?" : "¿Debo configurar algo para el cambio automático?",
      a: isEn ? "No. Once Qustodio and Linewize are both installed, the Cloud Safe Network feature handles switching automatically. When the device connects to CNG's network, Qustodio pauses. When it disconnects, Qustodio resumes." : "No. Una vez que Qustodio y Linewize están instalados, la función Cloud Safe Network maneja el cambio automáticamente. Cuando el dispositivo se conecta a la red de CNG, Qustodio se pausa. Cuando se desconecta, Qustodio se reanuda."
    },
    {
      q: isEn ? "Can my parental rules override school safety policies?" : "¿Pueden mis reglas parentales sobreescribir las políticas del colegio?",
      a: isEn ? "No. The school's base safety policies always remain active. Your parental rules add extra restrictions on top — they never override or relax school blocks. For example, if school blocks gambling, your settings cannot unblock it." : "No. Las políticas de seguridad base del colegio siempre permanecen activas. Tus reglas parentales agregan restricciones adicionales encima — nunca sobreescriben ni relajan los bloqueos escolares. Por ejemplo, si el colegio bloquea apuestas, tus configuraciones no pueden desbloquearlo."
    },
    {
      q: isEn ? "What happens if Qustodio doesn't pause at school?" : "¿Qué pasa si Qustodio no se pausa en el colegio?",
      a: isEn ? "This is rare but can happen if the device has connectivity issues. Contact CNG's Technology Department for troubleshooting. In most cases, a device restart resolves the issue." : "Esto es raro pero puede pasar si el dispositivo tiene problemas de conectividad. Contacta al Departamento de Tecnología de CNG para solucionar. En la mayoría de casos, reiniciar el dispositivo resuelve el problema."
    },
    {
      q: isEn ? "Does this work on all device types?" : "¿Funciona en todos los tipos de dispositivos?",
      a: isEn ? "Yes. The Qustodio + Linewize integration works on Chromebooks, Windows laptops, and MacBooks — all three BYOD options supported by CNG." : "Sí. La integración Qustodio + Linewize funciona en Chromebooks, laptops Windows y MacBooks — las tres opciones BYOD soportadas por CNG."
    }
  ];
}

// ============ MAIN APP ============
function App() {
  const [lang, setLang] = useState("en");
  const [mobileMenu, setMobileMenu] = useState(false);
  const [chatOpen, setChatOpen] = useState(false);
  const [chatMsgs, setChatMsgs] = useState([]);
  const [chatIn, setChatIn] = useState("");
  const [scrollY, setScrollY] = useState(0);
  const [selDevice, setSelDevice] = useState(null);
  const [hoveredBento, setHoveredBento] = useState(null);
  const [typing, setTyping] = useState(false);
  const chatRef = useRef(null);
  const sessionId = useRef(crypto.randomUUID());
  const [activeSection, setActiveSection] = useState('hero');
  const [sheetData, setSheetData] = useState({});
  const [dataLoading, setDataLoading] = useState(true);
  const [activeCategory, setActiveCategory] = useState(null);
  const [expandedItems, setExpandedItems] = useState({});
  const [activeTab, setActiveTab] = useState("school");
  const [openNavGroup, setOpenNavGroup] = useState(null);
  const [diagramStep, setDiagramStep] = useState(0);
  const [expandedFaq, setExpandedFaq] = useState(null);

  const t = ui[lang];

  useEffect(() => { const h = () => setScrollY(window.scrollY); window.addEventListener("scroll", h, { passive: true }); return () => window.removeEventListener("scroll", h); }, []);
  useEffect(() => { async function load() { try { const r = await Promise.all(Object.entries(CONFIG.SHEETS).map(async ([k, u]) => [k, await loadSheet(u)])); setSheetData(Object.fromEntries(r)); } catch(e) { console.error(e); } setDataLoading(false); } load(); }, []);
  useEffect(() => {
    const sectionIds = ['philosophy','citizenship','controls','screentime','home','byod','data'];
    const obs = new IntersectionObserver((entries) => {
      for (const e of entries) { if (e.isIntersecting) { setActiveSection(e.target.id); break; } }
    }, { threshold: 0.3, rootMargin: '-80px 0px -40% 0px' });
    sectionIds.forEach(id => { const el = document.getElementById(id); if (el) obs.observe(el); });
    return () => obs.disconnect();
  }, [dataLoading]);
  useEffect(() => { if (chatOpen && chatMsgs.length === 0) setChatMsgs([{ role: "bot", text: t.chatGreeting }]); }, [chatOpen]);
  useEffect(() => { if (chatRef.current) chatRef.current.scrollTop = chatRef.current.scrollHeight; }, [chatMsgs, typing]);

  const go = (id) => { document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" }); setMobileMenu(false); };
  const toggleItem = (i) => setExpandedItems(p => ({ ...p, [i]: !p[i] }));

  // Open a data modal by sheet id (used by chat links and deep links)
  const openModal = (sheetId) => {
    const cat = DATA_CATEGORIES.find(c => c.id === sheetId || c.sheet === sheetId);
    if (cat) { setActiveCategory(cat); setExpandedItems({}); window.history.replaceState(null, '', '#data:' + cat.id); }
  };
  const closeModal = () => { setActiveCategory(null); window.history.replaceState(null, '', window.location.pathname); };

  // Deep link: open modal from URL hash like #data:filtering
  useEffect(() => {
    if (dataLoading) return;
    const hash = window.location.hash;
    if (hash.startsWith('#data:')) {
      const id = hash.slice(6);
      const cat = DATA_CATEGORIES.find(c => c.id === id);
      if (cat) { setActiveCategory(cat); setExpandedItems({}); }
    }
  }, [dataLoading]);

  // Log a question to the worker and return the row number
  const logQuestion = async (question) => {
    try {
      const res = await fetch(CONFIG.API_URL + '/api/log', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ question, session_id: sessionId.current, language: lang, active_section: activeSection, device_type: DEVICE_TYPE, browser: BROWSER_NAME })
      });
      if (res.ok) { const data = await res.json(); return data.row; }
    } catch (e) { console.error('Log error:', e); }
    return null;
  };

  // Update a log row with AI response or feedback
  const patchLog = async (row, updates) => {
    if (!row) return;
    try {
      await fetch(CONFIG.API_URL + '/api/log/' + row, {
        method: 'PATCH', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ session_id: sessionId.current, ...updates })
      });
    } catch (e) { console.error('Patch log error:', e); }
  };

  // Handle feedback click
  const sendFeedback = (msgIndex, feedback) => {
    setChatMsgs(p => {
      const m = [...p];
      if (m[msgIndex]) { m[msgIndex] = { ...m[msgIndex], feedbackGiven: feedback }; }
      return m;
    });
    const msg = chatMsgs[msgIndex];
    if (msg?.logRow) patchLog(msg.logRow, { feedback, feedback_ts: new Date().toISOString() });
  };

  // Streaming chat with logging
  const sendMessage = async () => {
    if (!chatIn.trim() || typing) return;
    const msg = chatIn.trim(); setChatIn(""); setChatMsgs(p => [...p, { role: "user", text: msg }]); setTyping(true);
    const startTime = Date.now();
    let logRow = null;
    try {
      // Log the question (fire alongside AI request)
      const logPromise = logQuestion(msg);
      const history = [...chatMsgs].filter(m => !m.streaming).slice(-8).map(m => ({ role: m.role === 'bot' ? 'assistant' : 'user', content: m.text }));
      setChatMsgs(p => [...p, { role: 'bot', text: '', streaming: true }]);
      const res = await fetch(CONFIG.API_URL + '/chat/stream', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: msg, history, useServerData: true }) });
      if (!res.ok) throw new Error('fail');
      logRow = await logPromise;
      const ct = res.headers.get('content-type');
      if (ct && ct.includes('application/json')) {
        const j = await res.json();
        const responseTime = Date.now() - startTime;
        setChatMsgs(p => { const m=[...p]; m[m.length-1]={ role:'bot', text: j.reply||t.noProc, logRow }; return m; });
        patchLog(logRow, { ai_response: j.reply || '', response_time_ms: responseTime });
        setTyping(false); return;
      }
      const reader = res.body.getReader(); const dec = new TextDecoder(); let full='', buf='';
      while (true) { const { done, value } = await reader.read(); if (done) break; buf += dec.decode(value, { stream: true }); const lines = buf.split('\n'); buf = lines.pop()||'';
        for (const line of lines) { if (line.startsWith('data: ')) { const d=line.slice(6); if (d==='[DONE]') break; try { const p=JSON.parse(d); if(p.content){ full+=p.content; setChatMsgs(prev => { const m=[...prev]; if(m[m.length-1]?.streaming) m[m.length-1]={ role:'bot', text:full, streaming:true }; return m; }); } } catch(e){} } } }
      const responseTime = Date.now() - startTime;
      setChatMsgs(p => { const m=[...p]; if(m[m.length-1]?.streaming) m[m.length-1]={ role:'bot', text: full||t.noProc, logRow }; return m; });
      patchLog(logRow, { ai_response: full || '', response_time_ms: responseTime });
    } catch(e) {
      try {
        if (!logRow) logRow = await logQuestion(msg).catch(() => null);
        const history=[...chatMsgs].filter(m=>!m.streaming).slice(-8).map(m=>({role:m.role==='bot'?'assistant':'user',content:m.text})); const res=await fetch(CONFIG.API_URL+'/chat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({message:msg,history,useServerData:true})}); const j=await res.json();
        const responseTime = Date.now() - startTime;
        setChatMsgs(p=>{const m=[...p]; const li=m.length-1; if(m[li]?.streaming||m[li]?.text==='') m[li]={role:'bot',text:j.reply||t.connErr, logRow}; else m.push({role:'bot',text:j.reply||t.connErr, logRow}); return m;});
        patchLog(logRow, { ai_response: j.reply || '', response_time_ms: responseTime });
      }
      catch(e2){ setChatMsgs(p=>{const m=[...p]; const li=m.length-1; if(m[li]?.streaming||m[li]?.text==='') m[li]={role:'bot',text:t.connErr}; else m.push({role:'bot',text:t.connErr}); return m;}); }
    }
    setTyping(false);
  };

  // ═══ Derived data from sheets ═══
  const overview = sheetData.overview || [];
  const grp = groupBy(overview, 'Category');
  const byodRows = sheetData.byod || [];
  const parentalRows = sheetData.parental || [];
  const resourcesRows = sheetData.resources || [];
  const faqRows = sheetData.faq || [];
  const activeData = activeCategory ? (sheetData[activeCategory.sheet] || []) : [];

  // BYOD: extract device types from column headers
  const byodDeviceKeys = byodRows.length > 0 ? Object.keys(byodRows[0]).filter(k => k !== 'Category' && k !== 'Feature') : [];
  const deviceColors = ["#10B981", "#3B82F6", "#8B5CF6", "#F59E0B"];
  if (!selDevice && byodDeviceKeys.length > 0) setTimeout(() => setSelDevice(byodDeviceKeys[0]), 0);

  // Parental: extract tool names from column headers
  const parentalToolKeys = parentalRows.length > 0 ? Object.keys(parentalRows[0]).filter(k => k !== 'Feature') : [];
  const parentalColors = ["linear-gradient(90deg, #8B5CF6, #A78BFA)", "linear-gradient(90deg, #3B82F6, #60A5FA)", "linear-gradient(90deg, #6B7280, #9CA3AF)"];

  const bentoIcons = { book: <BookOpen size={22}/>, globe: <Globe size={22}/>, shield: <Shield size={22}/>, clock: <Clock size={22}/>, home: <Home size={22}/>, laptop: <Laptop size={22}/>, bot: <Bot size={22}/>, layers: <Layers size={22}/> };
  const bentoColors = ["#3B82F6", "#10B981", "#EF4444", "#F59E0B", "#EC4899", "#2C3E50", "#16A085", "#C9A227"];
  const pillarIcons = [<Shield size={26}/>, <Heart size={26}/>, <Brain size={26}/>, <Eye size={26}/>, <Lock size={26}/>, <Users size={26}/>];
  const pillarColors = ["#10B981", "#F59E0B", "#8B5CF6", "#3B82F6", "#EF4444", "#EC4899"];
  const ctrlIcons = [<Lock size={24}/>, <Monitor size={24}/>, <Settings size={24}/>, <Laptop size={24}/>, <Shield size={24}/>, <Eye size={24}/>];
  const ctrlColors = ["#EF4444", "#3B82F6", "#F59E0B", "#10B981", "#8B5CF6", "#EC4899"];
  const ctrlBgs = ["#FEF2F2", "#EFF6FF", "#FFFBEB", "#ECFDF5", "#F5F3FF", "#FCE7F3"];
  const ageColors = ["#EF4444", "#F59E0B", "#3B82F6", "#8B5CF6", "#10B981"];
  const ageBgs = ["#FEF2F2", "#FFFBEB", "#EFF6FF", "#F5F3FF", "#ECFDF5"];

  const tabColors = { school: "#0F4C81", home: "#10B981", bridge: "#C9A227" };
  const tabIcons = { school: <School size={16}/>, home: <Home size={16}/>, bridge: <Layers size={16}/> };
  const scenarios = getDiagramScenarios(lang==="en");
  const faqIntItems = getFaqItems(lang==="en");

  const sectionMap = [
    { tab: "school", id: "philosophy" },
    { tab: "school", id: "citizenship" },
    { tab: "school", id: "controls" },
    { tab: "home", id: "screentime" },
    { tab: "home", id: "home" },
    { tab: "bridge", id: "byod" },
    { tab: "bridge", id: "integration" },
    null // AI Assistant
  ];

  if (dataLoading) return <div className="loading"><img src="./escudo.png" alt="CNG" className="loading-logo" /><div className="loading-text">{t.loading}</div></div>;

  return (
    <div>
      {/* ══════════ HEADER — Tab-based navigation ══════════ */}
      <header className="glass" style={{ position:"sticky",top:0,zIndex:100, borderBottom: scrollY>20?"1px solid rgba(226,232,240,0.8)":"1px solid transparent", transition:"all 0.4s" }}>
        {/* Row 1: Logo + Tab pills + Language toggle + Ask AI + Mobile toggle */}
        <div style={{ maxWidth:1280,margin:"0 auto",padding:"0 32px",display:"flex",alignItems:"center",justifyContent:"space-between",height:60 }}>
          <div style={{ display:"flex",alignItems:"center",gap:14,cursor:"pointer" }} onClick={() => window.scrollTo({top:0,behavior:"smooth"})}>
            <img src="./escudo.png" alt="CNG" style={{ width:40,height:40,borderRadius:12,boxShadow:"0 4px 12px rgba(15,76,129,0.3)" }} />
            <div><div style={{ fontSize:15,fontWeight:800,color:"#0F172A",letterSpacing:"-0.03em",fontFamily:"'Sora',sans-serif" }}>CNG Digital Wellbeing</div><div style={{ fontSize:9,fontWeight:600,color:"#C9A227",letterSpacing:"0.12em",textTransform:"uppercase" }}>Colegio Nueva Granada</div></div>
          </div>

          {/* Tab pills */}
          <div className="tab-bar desktop-nav" style={{ display:"flex",gap:4,background:"#F1F5F9",borderRadius:12,padding:3 }}>
            {["school","home","bridge"].map(tab => (
              <button key={tab} onClick={() => { setActiveTab(tab); go(`section-${tab}`); }} style={{
                padding:"8px 18px",borderRadius:10,fontSize:12.5,fontWeight:700,
                border:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:6,
                background: activeTab===tab?"white":"transparent",
                color: activeTab===tab?tabColors[tab]:"#64748B",
                boxShadow: activeTab===tab?"0 2px 8px rgba(0,0,0,0.08)":"none",
                transition:"all 0.3s",fontFamily:"'DM Sans',sans-serif"
              }}>
                {tabIcons[tab]} {t.tabs[tab]}
              </button>
            ))}
          </div>

          <div style={{ display:"flex",alignItems:"center",gap:10 }}>
            <button onClick={() => setLang(lang==="en"?"es":"en")} style={{ padding:"7px 16px",borderRadius:10,fontSize:12,fontWeight:800,background:"transparent",border:"2px solid #E2E8F0",cursor:"pointer",color:"#475569",fontFamily:"'Space Mono',monospace",letterSpacing:"0.05em" }}>{t.langToggle}</button>
            <button onClick={() => setChatOpen(!chatOpen)} style={{ padding:"8px 18px",borderRadius:10,fontSize:12.5,fontWeight:700,background:"linear-gradient(135deg,#0F4C81,#1A6FB5)",border:"none",cursor:"pointer",color:"white",display:"flex",alignItems:"center",gap:6,boxShadow:"0 2px 8px rgba(15,76,129,0.25)" }}><Sparkles size={14}/> {t.askAI}</button>
            <button className="mob-toggle" onClick={() => setMobileMenu(!mobileMenu)} style={{ display:"none",width:40,height:40,borderRadius:12,border:"1px solid #E2E8F0",background:"white",cursor:"pointer",alignItems:"center",justifyContent:"center" }}>{mobileMenu?<X size={20}/>:<Menu size={20}/>}</button>
          </div>
        </div>

        {/* Row 2: Grouped navigation dropdowns (desktop only) */}
        <div className="sub-nav-row desktop-nav" style={{ borderTop:"1px solid #F1F5F9",background:"rgba(255,255,255,0.6)" }}>
          <div style={{ maxWidth:1280,margin:"0 auto",padding:"0 32px",display:"flex",alignItems:"center",height:38,gap:0 }}>
            {(t.navGroups||[]).map((group,gi) => (
              group.external ? (
                <div key={gi} style={{ position:"relative" }}>
                  <button onClick={() => window.open(group.external, '_blank')} style={{
                    padding:"5px 16px",borderRadius:7,fontSize:12.5,fontWeight:700,
                    border:"none",cursor:"pointer",
                    background:"transparent",color:"#64748B",
                    transition:"all 0.2s",fontFamily:"'DM Sans',sans-serif",
                    display:"flex",alignItems:"center",gap:4
                  }}
                    onMouseEnter={e => { e.currentTarget.style.background="#F1F5F9"; e.currentTarget.style.color="#0F172A"; }}
                    onMouseLeave={e => { e.currentTarget.style.background="transparent"; e.currentTarget.style.color="#64748B"; }}>
                    {group.label}
                    <ExternalLink size={11} style={{ opacity:0.6 }} />
                  </button>
                </div>
              ) : (
              <div key={gi} style={{ position:"relative" }}
                onMouseEnter={() => setOpenNavGroup(gi)}
                onMouseLeave={() => setOpenNavGroup(null)}>
                <button style={{
                  padding:"5px 16px",borderRadius:7,fontSize:12.5,fontWeight:700,
                  border:"none",cursor:"pointer",
                  background: openNavGroup===gi?"#F1F5F9":"transparent",
                  color: openNavGroup===gi?"#0F172A":"#64748B",
                  transition:"all 0.2s",fontFamily:"'DM Sans',sans-serif",
                  display:"flex",alignItems:"center",gap:4
                }}>
                  {group.label}
                  <ChevronDown size={12} style={{ opacity:0.5,transition:"transform 0.2s",transform:openNavGroup===gi?"rotate(180deg)":"none" }} />
                </button>
                {openNavGroup===gi && (
                  <div style={{
                    position:"absolute",top:"100%",left:0,paddingTop:4,
                    zIndex:200
                  }}>
                  <div style={{
                    background:"white",borderRadius:12,padding:"6px",
                    boxShadow:"0 12px 32px rgba(0,0,0,0.12), 0 0 0 1px rgba(0,0,0,0.04)",
                    minWidth:180
                  }}>
                    {group.items.map((item,ii) => (
                      <button key={ii} onClick={() => {
                        if (item.external) { window.open(item.external, '_blank'); setOpenNavGroup(null); return; }
                        if (item.modal) { openModal(item.modal); setOpenNavGroup(null); return; }
                        if (item.tab) { setActiveTab(item.tab); setTimeout(() => go(item.id), 120); }
                        else { go(item.id); }
                        setOpenNavGroup(null);
                      }} style={{
                        display:"block",width:"100%",padding:"9px 14px",borderRadius:8,
                        fontSize:12.5,fontWeight:500,color:"#334155",textAlign:"left",
                        border:"none",cursor:"pointer",background:"transparent",
                        transition:"all 0.15s",fontFamily:"'DM Sans',sans-serif",whiteSpace:"nowrap"
                      }}
                        onMouseEnter={e => { e.currentTarget.style.background="#F8FAFC"; e.currentTarget.style.color="#0F4C81"; }}
                        onMouseLeave={e => { e.currentTarget.style.background="transparent"; e.currentTarget.style.color="#334155"; }}>
                        {item.label} {item.external && <ExternalLink size={11} style={{ marginLeft:4,verticalAlign:"middle",color:"#94A3B8" }}/>}
                      </button>
                    ))}
                  </div>
                  </div>
                )}
              </div>
              )
            ))}
          </div>
        </div>

        {/* Mobile menu */}
        {mobileMenu && <div style={{ padding:"8px 32px 20px",background:"white",borderTop:"1px solid #E2E8F0" }}>
          {/* Tab buttons */}
          <div style={{ display:"flex",gap:6,marginBottom:16,padding:"8px 0" }}>
            {["school","home","bridge"].map(tab => (
              <button key={tab} onClick={() => { setActiveTab(tab); go(`section-${tab}`); setMobileMenu(false); }} style={{
                flex:1,padding:"10px 0",borderRadius:10,fontSize:12,fontWeight:700,
                border:`2px solid ${activeTab===tab?tabColors[tab]:"#E2E8F0"}`,
                background:activeTab===tab?`${tabColors[tab]}10`:"white",
                color:activeTab===tab?tabColors[tab]:"#64748B",
                cursor:"pointer",textAlign:"center"
              }}>
                {t.tabs[tab]}
              </button>
            ))}
          </div>
          {/* Nav group items */}
          {(t.navGroups||[]).map((group,gi) => (
            group.external ? (
              <div key={gi} style={{ padding:"12px 0",fontSize:15,fontWeight:700,color:"#0F172A",cursor:"pointer",borderBottom:"1px solid #F1F5F9",display:"flex",alignItems:"center",gap:8 }}
                onClick={() => { window.open(group.external, '_blank'); setMobileMenu(false); }}>
                {group.label} <ExternalLink size={13} style={{ color:"#94A3B8" }}/>
              </div>
            ) : (
            <div key={gi}>
              <div style={{ padding:"8px 0",fontSize:11,fontWeight:800,color:"#94A3B8",textTransform:"uppercase",letterSpacing:"0.08em" }}>{group.label}</div>
              {group.items.map((item,ii) => (
                <div key={ii} style={{ padding:"12px 0",fontSize:15,fontWeight:600,color:"#334155",cursor:"pointer",borderBottom:"1px solid #F1F5F9",display:"flex",alignItems:"center",gap:8 }}
                  onClick={() => {
                    if (item.external) { window.open(item.external, '_blank'); setMobileMenu(false); return; }
                    if (item.modal) { openModal(item.modal); setMobileMenu(false); return; }
                    if (item.tab) { setActiveTab(item.tab); setTimeout(() => go(item.id), 120); }
                    else { go(item.id); }
                    setMobileMenu(false);
                  }}>
                  {item.label} {item.external && <ExternalLink size={13} style={{ color:"#94A3B8" }}/>}
                </div>
              ))}
            </div>
            )
          ))}
          <a href="https://drive.google.com/file/d/1T66VnnmPsJXImbLrFWx7T87zWI0fAG3F/view?usp=sharing" target="_blank" rel="noopener noreferrer" style={{ display:"flex",alignItems:"center",gap:8,padding:"12px 0",fontSize:15,fontWeight:600,color:"#334155",textDecoration:"none",borderBottom:"1px solid #F1F5F9" }}>{lang==="en"?"Partnerships — Apple":"Convenios — Apple"} <ExternalLink size={13} style={{ color:"#94A3B8" }}/></a>
        </div>}
      </header>

      {/* ══════════ HERO (exact mockup design) ══════════ */}
      <section style={{ position:"relative",overflow:"hidden",minHeight:580,background:"linear-gradient(155deg,#050E1F 0%,#0A2240 25%,#0F4C81 55%,#1A6FB5 80%,#2A8FD5 100%)" }}>
        {/* Noise grain overlay */}
        <div style={{ position:"absolute",inset:0,opacity:0.03,backgroundImage:"url(\"data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\")",backgroundSize:"128px",pointerEvents:"none" }} />
        {/* Animated blobs */}
        <div style={{ position:"absolute",top:"-10%",right:"-5%",width:500,height:500,background:"radial-gradient(circle,rgba(201,162,39,0.18) 0%,transparent 65%)",animation:"morphBlob 15s ease-in-out infinite",pointerEvents:"none" }} />
        <div style={{ position:"absolute",bottom:"-15%",left:"10%",width:400,height:400,background:"radial-gradient(circle,rgba(26,111,181,0.25) 0%,transparent 65%)",animation:"morphBlob 12s ease-in-out infinite 3s",pointerEvents:"none" }} />
        {/* Grid lines */}
        <svg style={{ position:"absolute",inset:0,width:"100%",height:"100%",opacity:0.04,pointerEvents:"none" }}><defs><pattern id="grid" width="80" height="80" patternUnits="userSpaceOnUse"><path d="M 80 0 L 0 0 0 80" fill="none" stroke="white" strokeWidth="0.5"/></pattern></defs><rect width="100%" height="100%" fill="url(#grid)"/></svg>
        {/* Floating geometric accents */}
        <div style={{ position:"absolute",top:"15%",right:"12%",width:120,height:120,border:"1.5px solid rgba(201,162,39,0.25)",borderRadius:28,transform:"rotate(30deg)",animation:"float 10s ease-in-out infinite",pointerEvents:"none" }} />
        <div style={{ position:"absolute",bottom:"20%",right:"8%",width:60,height:60,border:"1.5px solid rgba(255,255,255,0.1)",borderRadius:"50%",animation:"float 8s ease-in-out infinite 2s",pointerEvents:"none" }} />
        <div style={{ position:"absolute",top:"60%",left:"5%",width:40,height:40,background:"rgba(201,162,39,0.15)",borderRadius:10,transform:"rotate(45deg)",animation:"float 7s ease-in-out infinite 1s",pointerEvents:"none" }} />

        <div className="hero-flex" style={{ maxWidth:1280,margin:"0 auto",padding:"80px 32px 72px",display:"flex",alignItems:"center",gap:80,position:"relative",zIndex:1 }}>
          <div style={{ flex:1 }}>
            <Reveal><div style={{ display:"inline-flex",alignItems:"center",gap:8,padding:"8px 18px",borderRadius:50,background:"rgba(201,162,39,0.15)",border:"1px solid rgba(201,162,39,0.3)",color:"#F5E6C4",fontSize:12,fontWeight:700,marginBottom:28,letterSpacing:"0.06em",textTransform:"uppercase",fontFamily:"'Space Mono',monospace" }}><Zap size={13}/> {t.heroBadge}</div></Reveal>
            <Reveal delay={0.1}><p style={{ fontSize:13,fontWeight:600,color:"rgba(201,162,39,0.8)",letterSpacing:"0.15em",textTransform:"uppercase",marginBottom:12,fontFamily:"'Space Mono',monospace" }}>{t.heroPre}</p></Reveal>
            <Reveal delay={0.15}><h1 className="hero-h1" style={{ fontFamily:"'Sora',sans-serif",fontSize:60,fontWeight:800,lineHeight:1.05,color:"white",marginBottom:24,letterSpacing:"-0.04em" }}>{t.heroT1}<br/><span style={{ background:"linear-gradient(90deg,#C9A227,#F5D35E,#E8B832,#C9A227)",backgroundSize:"300% auto",WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",animation:"shimmer 4s linear infinite" }}>{t.heroT2}</span></h1></Reveal>
            <Reveal delay={0.2}><div style={{ fontSize:15.5,color:"rgba(255,255,255,0.72)",lineHeight:1.7,maxWidth:560,marginBottom:36 }}>
              {lang==="en" ? <>
                <p style={{ marginBottom:14 }}>Welcome to the <strong style={{ color:"#F5D35E",fontWeight:700 }}>CNG Digital Wellbeing Partnership</strong> — your hub for everything our community is doing to help families navigate the digital world together, at school and at home.</p>
                <p style={{ margin:0 }}>Screen time, content exposure, and online focus are challenges every family faces. Here you'll find the policies, guidance, and resources CNG provides so you don't have to figure it out alone.</p>
              </> : <>
                <p style={{ marginBottom:14 }}>Bienvenido a la <strong style={{ color:"#F5D35E",fontWeight:700 }}>Alianza de Bienestar Digital CNG</strong> — tu centro para todo lo que nuestra comunidad está haciendo para ayudar a las familias a navegar el mundo digital juntos, en el colegio y en casa.</p>
                <p style={{ margin:0 }}>El tiempo en pantalla, la exposición al contenido y la concentración en línea son desafíos que toda familia enfrenta. Aquí encontrarás las políticas, la orientación y los recursos que CNG ofrece para que no tengas que resolverlo solo.</p>
              </>}
            </div></Reveal>
            <Reveal delay={0.25}><div style={{ display:"flex",gap:14,flexWrap:"wrap" }}>
              <button onClick={() => { setActiveTab("school"); setTimeout(() => go("philosophy"), 120); }} style={{ padding:"15px 30px",borderRadius:14,fontSize:14.5,fontWeight:700,background:"#C9A227",color:"#0A2240",border:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:10,transition:"all 0.3s",boxShadow:"0 8px 32px rgba(201,162,39,0.4), inset 0 1px 0 rgba(255,255,255,0.3)",fontFamily:"'Sora',sans-serif",letterSpacing:"-0.01em" }}>{t.heroCta1} <ArrowRight size={17}/></button>
              <button onClick={() => setChatOpen(true)} style={{ padding:"15px 30px",borderRadius:14,fontSize:14.5,fontWeight:700,background:"rgba(255,255,255,0.08)",color:"white",border:"1px solid rgba(255,255,255,0.2)",cursor:"pointer",display:"flex",alignItems:"center",gap:10,backdropFilter:"blur(12px)",transition:"all 0.3s",fontFamily:"'Sora',sans-serif",letterSpacing:"-0.01em" }}><Sparkles size={17}/> {t.heroCta2}</button>
            </div></Reveal>
          </div>

          {/* Hero visual — Security Dashboard mockup */}
          <div className="hero-visual" style={{ flex:"0 0 auto" }}>
            <Reveal delay={0.3}><div style={{ position:"relative" }}>
              {/* Glow behind */}
              <div style={{ position:"absolute",inset:-30,borderRadius:50,background:"radial-gradient(circle,rgba(201,162,39,0.2) 0%,transparent 70%)",animation:"glowPulse 4s ease-in-out infinite",pointerEvents:"none" }} />

              {/* Main card — security dashboard */}
              <div style={{ width:400,borderRadius:28,position:"relative",overflow:"hidden",background:"linear-gradient(160deg,rgba(15,30,60,0.95),rgba(15,76,129,0.85))",border:"1px solid rgba(255,255,255,0.12)",boxShadow:"0 32px 64px rgba(0,0,0,0.35), 0 0 0 1px rgba(255,255,255,0.08)",backdropFilter:"blur(20px)" }}>
                {/* Gold top accent */}
                <div style={{ height:3,background:"linear-gradient(90deg,transparent,#C9A227,#F5D35E,#C9A227,transparent)" }} />
                {/* Corner brackets */}
                <div style={{ position:"absolute",top:14,left:14,width:24,height:24,borderTop:"2px solid rgba(201,162,39,0.4)",borderLeft:"2px solid rgba(201,162,39,0.4)",borderRadius:"5px 0 0 0" }} />
                <div style={{ position:"absolute",top:14,right:14,width:24,height:24,borderTop:"2px solid rgba(201,162,39,0.4)",borderRight:"2px solid rgba(201,162,39,0.4)",borderRadius:"0 5px 0 0" }} />

                {/* Dashboard header */}
                <div style={{ padding:"24px 28px 16px",borderBottom:"1px solid rgba(255,255,255,0.08)" }}>
                  <div style={{ display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:6 }}>
                    <div style={{ display:"flex",alignItems:"center",gap:8 }}>
                      <div style={{ width:8,height:8,borderRadius:"50%",background:"#10B981",boxShadow:"0 0 8px rgba(16,185,129,0.6)",animation:"pulse 2s infinite" }} />
                      <span style={{ fontSize:11,fontWeight:700,color:"#10B981",textTransform:"uppercase",letterSpacing:"0.1em",fontFamily:"'Space Mono',monospace" }}>{lang==="en"?"All Systems Active":"Sistemas Activos"}</span>
                    </div>
                    <span style={{ fontSize:10,color:"rgba(255,255,255,0.35)",fontFamily:"'Space Mono',monospace" }}>v3.0</span>
                  </div>
                  <div style={{ fontSize:20,fontWeight:800,color:"white",fontFamily:"'Sora',sans-serif",letterSpacing:"-0.03em" }}>{lang==="en"?"CNG Security Hub":"Hub de Seguridad CNG"}</div>
                </div>

                {/* 3 mini stat cards */}
                <div style={{ padding:"16px 28px",display:"flex",gap:10 }}>
                  {[
                    { icon:<Lock size={16}/>, label:lang==="en"?"Filtering":"Filtrado", color:"#EF4444", stat:String((sheetData.filtering||[]).length)+"+" },
                    { icon:<Eye size={16}/>, label:lang==="en"?"Monitoring":"Monitoreo", color:"#3B82F6", stat:lang==="en"?"Centralized":"Centralizado" },
                    { icon:<Shield size={16}/>, label:lang==="en"?"Extra-layer":"Capa extra", color:"#10B981", stat:lang==="en"?"Protection":"Protección" }
                  ].map((item,i) => (
                    <div key={i} style={{ flex:1,padding:"14px 12px",borderRadius:14,background:"rgba(255,255,255,0.06)",border:"1px solid rgba(255,255,255,0.08)",textAlign:"center" }}>
                      <div style={{ color:item.color,marginBottom:6,display:"flex",justifyContent:"center" }}>{item.icon}</div>
                      <div style={{ fontSize:18,fontWeight:800,color:"white",fontFamily:"'Space Mono',monospace",lineHeight:1 }}>{item.stat}</div>
                      <div style={{ fontSize:9,color:"rgba(255,255,255,0.45)",marginTop:4,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em" }}>{item.label}</div>
                    </div>
                  ))}
                </div>

                {/* Protection layers — status rows */}
                <div style={{ padding:"12px 28px 8px" }}>
                  <div style={{ fontSize:10,color:"rgba(255,255,255,0.35)",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.1em",marginBottom:12,fontFamily:"'Space Mono',monospace" }}>{lang==="en"?"Protection Layers":"Capas de Protección"}</div>
                  {[
                    { label:lang==="en"?"Content Filter":"Filtro Contenido", stat:String((sheetData.filtering||[]).length)+" "+(lang==="en"?"categories":"categorías"), color:"#EF4444", icon:<Lock size={12}/> },
                    { label:lang==="en"?"App Control":"Control Apps", stat:lang==="en"?"Apps management":"Gestión de Apps", color:"#F59E0B", icon:<Settings size={12}/> },
                    { label:lang==="en"?"Device Mgmt":"Gestión Disp.", stat:"devices", color:"#10B981", icon:<Laptop size={12}/> },
                    { label:"YouTube", stat:lang==="en"?"Restricted Mode":"Modo Restringido", color:"#3B82F6", icon:<Eye size={12}/> }
                  ].map((row,i) => (
                    <div key={i} style={{ display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 12px",marginBottom:6,borderRadius:10,background:i%2===0?"rgba(255,255,255,0.04)":"transparent" }}>
                      <div style={{ display:"flex",alignItems:"center",gap:8 }}>
                        <div style={{ color:row.color,display:"flex" }}>{row.icon}</div>
                        <span style={{ fontSize:11.5,color:"rgba(255,255,255,0.65)",fontWeight:500 }}>{row.label}</span>
                      </div>
                      {row.stat === "devices" ? (
                        <div style={{ display:"flex",alignItems:"center",gap:6,padding:"3px 10px",borderRadius:6,background:`${row.color}15`,border:`1px solid ${row.color}25` }}>
                          {/* Apple logo */}
                          <svg width="14" height="14" viewBox="0 0 384 512" fill="rgba(255,255,255,0.7)"><path d="M318.7 268.7c-.2-36.7 16.4-64.4 50-84.8-18.8-26.9-47.2-41.7-84.7-44.6-35.5-2.8-74.3 20.7-88.5 20.7-15 0-49.4-19.7-76.4-19.7C63.3 141.2 4 184.8 4 273.5c0 26.2 4.8 53.3 14.4 81.2 12.8 36.7 59 126.7 107.2 125.2 25.2-.6 43-17.9 75.8-17.9 31.8 0 48.3 17.9 76.4 17.9 48.6-.7 90.4-82.5 102.6-119.3-65.2-30.7-61.7-90-61.7-91.9zm-56.6-164.2c27.3-32.4 24.8-61.9 24-72.5-24.1 1.4-52 16.4-67.9 34.9-17.5 19.8-27.8 44.3-25.6 71.9 26.1 2 49.9-11.4 69.5-34.3z"/></svg>
                          {/* Windows logo */}
                          <svg width="14" height="14" viewBox="0 0 448 512" fill="rgba(255,255,255,0.7)"><path d="M0 93.7l183.6-25.3v177.4H0V93.7zm0 324.6l183.6 25.3V268.4H0v149.9zm203.8 28L448 480V268.4H203.8v177.9zm0-380.6v180.1H448V32L203.8 65.7z"/></svg>
                          {/* Chrome logo */}
                          <svg width="14" height="14" viewBox="0 0 512 512" fill="rgba(255,255,255,0.7)"><path d="M0 256C0 209.4 17 166.6 45.2 132.6L194.1 370c-36.5-18.7-61.8-52.5-68.2-92.5L0 256zm256-256c70.7 0 134.7 28.7 181 75L346.1 165c-22.8-22.8-54.3-36.9-89.1-36.9-49.5 0-92 28.5-112.6 70L37.1 75C83.4 28.7 185.3 0 256 0zm181 437L346.1 347c22.8-22.8 36.9-54.3 36.9-89.1 0-49.5-28.5-92-70-112.6L437 37.1C483.3 83.4 512 185.3 512 256c0 70.7-28.7 134.7-75 181zM256 512c-70.7 0-134.7-28.7-181-75l90.9-90.9c22.8 22.8 54.3 36.9 89.1 36.9 49.5 0 92-28.5 112.6-70l107.3 122.9C428.6 483.3 326.7 512 256 512zm0-160a96 96 0 1 0 0-192 96 96 0 1 0 0 192z"/></svg>
                        </div>
                      ) : (
                        <span style={{ fontSize:11,fontWeight:700,color:row.color,fontFamily:"'Space Mono',monospace",padding:"3px 10px",borderRadius:6,background:`${row.color}15`,border:`1px solid ${row.color}25` }}>{row.stat}</span>
                      )}
                    </div>
                  ))}
                </div>

                {/* Bottom row */}
                <div style={{ padding:"12px 28px 22px",borderTop:"1px solid rgba(255,255,255,0.06)",display:"flex",alignItems:"center",justifyContent:"space-between" }}>
                  <div style={{ display:"flex",alignItems:"center",gap:6 }}>
                    <Wifi size={13} style={{ color:"#10B981" }} />
                    <span style={{ fontSize:10,color:"rgba(255,255,255,0.4)",fontFamily:"'Space Mono',monospace" }}>{lang==="en"?"Network encrypted":"Red encriptada"}</span>
                  </div>
                  <div style={{ display:"flex",gap:4 }}>
                    {[...Array(5)].map((_,i) => <div key={i} style={{ width:4,height:i<4?8+i*4:20,borderRadius:2,background:i<4?"#10B981":"rgba(255,255,255,0.15)" }} />)}
                  </div>
                </div>
              </div>
            </div></Reveal>
          </div>
        </div>

        {/* Bottom wave */}
        <svg viewBox="0 0 1440 60" style={{ position:"absolute",bottom:-1,width:"100%",display:"block" }} preserveAspectRatio="none"><path d="M0,40 C360,0 720,60 1080,20 C1260,5 1380,30 1440,25 L1440,60 L0,60 Z" fill="#FAFBFD"/></svg>
      </section>

      {/* ══════════ BENTO GRID (mockup design) ══════════ */}
      <section id="quicklinks" style={{ maxWidth:1280,margin:"0 auto",padding:"72px 32px" }}>
        <Reveal><div style={{ textAlign:"center",marginBottom:48 }}>
          <h2 style={{ fontFamily:"'Sora',sans-serif",fontSize:36,fontWeight:800,color:"#0F172A",letterSpacing:"-0.04em",marginBottom:10 }}>{lang==="en"?"Everything You Need":"Todo lo que Necesitas"}</h2>
          <p style={{ fontSize:16,color:"#64748B" }}>{lang==="en"?"Navigate our technology ecosystem with ease":"Navega nuestro ecosistema tecnológico con facilidad"}</p>
        </div></Reveal>
        <div className="bento-grid" style={{ display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:16 }}>
          {t.bentoCards.map((card,i) => (
            <Reveal key={i} delay={i*0.06}><div className="bento-card" onMouseEnter={() => setHoveredBento(i)} onMouseLeave={() => setHoveredBento(null)}
              onClick={() => {
                if (i === 7) { setChatOpen(true); return; }
                if (sectionMap[i]) { setActiveTab(sectionMap[i].tab); setTimeout(() => go(sectionMap[i].id), 120); }
              }}
              style={{ background: hoveredBento===i?`linear-gradient(135deg,${bentoColors[i]}08,${bentoColors[i]}15)`:"white" }}>
              <div style={{ position:"relative",zIndex:1 }}>
                <div style={{ display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16 }}>
                  <div style={{ width:48,height:48,borderRadius:14,background:`${bentoColors[i]}12`,color:bentoColors[i],display:"flex",alignItems:"center",justifyContent:"center",transition:"all 0.3s",transform:hoveredBento===i?"scale(1.1) rotate(-5deg)":"scale(1)" }}>{bentoIcons[card.icon]}</div>
                  <span style={{ padding:"4px 10px",borderRadius:6,fontSize:10,fontWeight:800,background:`${bentoColors[i]}12`,color:bentoColors[i],letterSpacing:"0.06em",textTransform:"uppercase",fontFamily:"'Space Mono',monospace" }}>{card.tag}</span>
                </div>
                <div style={{ fontSize:15,fontWeight:700,color:"#0F172A",marginBottom:4 }}>{card.label}</div>
                <div style={{ fontSize:13,color:"#94A3B8" }}>{card.desc}</div>
                <div style={{ marginTop:14,display:"flex",alignItems:"center",gap:4,fontSize:12,fontWeight:700,color:bentoColors[i],opacity:hoveredBento===i?1:0,transition:"opacity 0.3s" }}>{t.explore} <ChevronRight size={14}/></div>
              </div>
            </div></Reveal>
          ))}
        </div>
      </section>

      {/* ══════════ TAB: AT SCHOOL ══════════ */}
      <div id="section-school" style={{ display: activeTab === "school" ? "block" : "none" }}>
        {/* Section Banner */}
        <div style={{ background:"linear-gradient(135deg,rgba(15,76,129,0.03),rgba(15,76,129,0.015))", borderTop:"3px solid #0F4C81", padding:"28px 0" }}>
          <div style={{ maxWidth:1280,margin:"0 auto",padding:"0 32px",display:"flex",alignItems:"center",gap:12 }}>
            <div style={{ width:40,height:40,borderRadius:12,background:"#0F4C81",color:"white",display:"flex",alignItems:"center",justifyContent:"center" }}><School size={20}/></div>
            <h2 style={{ fontFamily:"'Sora',sans-serif",fontSize:22,fontWeight:800,color:"#0F4C81",letterSpacing:"-0.03em" }}>{t.tabs.school}</h2>
          </div>
        </div>

        {/* PHILOSOPHY (mockup design, sheet data) */}
        <section id="philosophy" style={{ maxWidth:1280,margin:"0 auto",padding:"32px 32px 72px" }}>
          <Reveal><div style={{ borderRadius:28,overflow:"hidden",border:"1px solid #E2E8F0",background:"white" }}>
            <div style={{ height:4,background:"linear-gradient(90deg,#0F4C81,#C9A227,#1A6FB5)" }} />
            <div style={{ padding:"48px 56px" }}>
              <div style={{ display:"flex",alignItems:"center",gap:10,marginBottom:8 }}>
                <div style={{ width:28,height:28,borderRadius:8,background:"#0F4C81",color:"white",display:"flex",alignItems:"center",justifyContent:"center" }}><BookOpen size={14}/></div>
                <span style={{ fontSize:11,fontWeight:800,color:"#C9A227",textTransform:"uppercase",letterSpacing:"0.12em",fontFamily:"'Space Mono',monospace" }}>{lang==="en"?"School Context":"Contexto Escolar"}</span>
              </div>
              <h2 style={{ fontFamily:"'Sora',sans-serif",fontSize:32,fontWeight:800,color:"#0F172A",letterSpacing:"-0.04em",marginBottom:32 }}>{lang==="en"?"Our Philosophy":"Nuestra Filosofía"}</h2>
              <div className="philosophy-grid" style={{ display:"grid",gridTemplateColumns:"1.2fr 1fr",gap:40 }}>
                <div>{(grp['Philosophy']||[]).map((r,i) => <div key={i} style={{ marginBottom:16 }}><h4 style={{ fontSize:14,fontWeight:700,color:"#0F172A",marginBottom:4 }}>{r.Title}</h4><p style={{ fontSize:15,color:"#475569",lineHeight:1.8 }}>{r.Description}</p></div>)}</div>
                <div style={{ background:"#F8FAFC",borderRadius:20,padding:28,border:"1px solid #E2E8F0" }}>
                  <div style={{ display:"flex",alignItems:"center",gap:10,marginBottom:16 }}><Shield size={18} style={{ color:"#0F4C81" }}/><h3 style={{ fontSize:15,fontWeight:800,color:"#0F172A",fontFamily:"'Sora',sans-serif" }}>{lang==="en"?"Legal Framework":"Marco Legal"}</h3></div>
                  {(grp['Legal Framework']||[]).map((r,i) => <div key={i} style={{ marginBottom:12 }}><p style={{ fontSize:13.5,color:"#64748B",lineHeight:1.75 }}>{r.Description}</p>{r.Title && <span className="legal-pill" style={{ marginTop:6,display:"inline-block" }}>{r.Title}</span>}</div>)}
                </div>
              </div>
            </div>
          </div></Reveal>
        </section>

        {/* DIGITAL CITIZENSHIP (mockup pillar cards, sheet data) */}
        <section id="citizenship" style={{ background:"linear-gradient(180deg,#F0F7FF 0%,#FAFBFD 100%)",padding:"72px 0" }}>
          <div style={{ maxWidth:1280,margin:"0 auto",padding:"0 32px" }}>
            <Reveal><div style={{ textAlign:"center",marginBottom:48 }}>
              <span style={{ display:"inline-flex",alignItems:"center",gap:6,padding:"6px 14px",borderRadius:8,background:"#ECFDF5",color:"#10B981",fontSize:11,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.1em",fontFamily:"'Space Mono',monospace",marginBottom:14 }}><Globe size={13}/> {lang==="en"?"Core Program":"Programa Central"}</span>
              <h2 style={{ fontFamily:"'Sora',sans-serif",fontSize:36,fontWeight:800,color:"#0F172A",letterSpacing:"-0.04em",marginBottom:10 }}>{lang==="en"?"Digital Citizenship":"Ciudadanía Digital"}</h2>
            </div></Reveal>
            {(grp['Digital Citizenship']||[]).length > 0 && (
              <div className="pillar-grid" style={{ display:"grid",gridTemplateColumns:`repeat(${Math.min((grp['Digital Citizenship']||[]).length,4)},1fr)`,gap:20 }}>
                {(grp['Digital Citizenship']||[]).map((r,i) => { const c=pillarColors[i%pillarColors.length]; return (
                  <Reveal key={i} delay={0.1+i*0.08}><div className="pillar" style={{ minHeight:220 }}>
                    <div style={{ position:"absolute",top:0,right:0,width:100,height:100,background:`radial-gradient(circle at top right,${c}10,transparent 70%)`,pointerEvents:"none" }} />
                    <div style={{ position:"relative",zIndex:1 }}>
                      <div style={{ width:56,height:56,borderRadius:16,marginBottom:20,background:`${c}12`,color:c,display:"flex",alignItems:"center",justifyContent:"center" }}>{pillarIcons[i%pillarIcons.length]}</div>
                      <h3 style={{ fontSize:18,fontWeight:800,color:"#0F172A",marginBottom:8,fontFamily:"'Sora',sans-serif" }}>{r.Title}</h3>
                      <p style={{ fontSize:13.5,color:"#64748B",lineHeight:1.7 }}>{r.Description}</p>
                    </div>
                  </div></Reveal>
                ); })}
              </div>
            )}
          </div>
        </section>

        {/* ACCESS & CONTROLS (mockup control cards, sheet data) */}
        <section id="controls" style={{ maxWidth:1280,margin:"0 auto",padding:"72px 32px" }}>
          <Reveal><div style={{ textAlign:"center",marginBottom:48 }}>
            <span style={{ display:"inline-flex",alignItems:"center",gap:6,padding:"6px 14px",borderRadius:8,background:"#FEF2F2",color:"#EF4444",fontSize:11,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.1em",fontFamily:"'Space Mono',monospace",marginBottom:14 }}><Lock size={13}/> {lang==="en"?"Network Security":"Seguridad de Red"}</span>
            <h2 style={{ fontFamily:"'Sora',sans-serif",fontSize:36,fontWeight:800,color:"#0F172A",letterSpacing:"-0.04em",marginBottom:10 }}>{lang==="en"?"Access & Controls":"Acceso y Controles"}</h2>
          </div></Reveal>
          <div className="ctrl-grid" style={{ display:"grid",gridTemplateColumns:"1fr 1fr",gap:20 }}>
            {(grp['Access & Controls']||grp['Access and Controls']||[]).map((r,i) => (
              <Reveal key={i} delay={i*0.08}><div className="control-card"><div style={{ display:"flex",gap:18 }}>
                <div style={{ width:56,height:56,borderRadius:16,flexShrink:0,background:ctrlBgs[i%6],color:ctrlColors[i%6],display:"flex",alignItems:"center",justifyContent:"center" }}>{ctrlIcons[i%6]}</div>
                <div style={{ flex:1 }}>
                  <h3 style={{ fontSize:16,fontWeight:800,color:"#0F172A",fontFamily:"'Sora',sans-serif",marginBottom:8 }}>{r.Title}</h3>
                  <p style={{ fontSize:13.5,color:"#64748B",lineHeight:1.7 }}>{r.Description}</p>
                </div>
              </div></div></Reveal>
            ))}
          </div>
          <Reveal delay={0.4}><div style={{ textAlign:"center",marginTop:32,display:"flex",justifyContent:"center",gap:12,flexWrap:"wrap" }}>
            {[DATA_CATEGORIES[2],DATA_CATEGORIES[3],DATA_CATEGORIES[4],DATA_CATEGORIES[5]].map((cat,i) => (
              <button key={i} className="data-link-btn" onClick={() => openModal(cat.id)}>{cat.icon} {lang==="en"?cat.name:cat.nameEs} <ExternalLink size={13}/></button>
            ))}
          </div></Reveal>
        </section>
      </div>

      {/* ══════════ TAB: AT HOME ══════════ */}
      <div id="section-home" style={{ display: activeTab === "home" ? "block" : "none" }}>
        {/* Section Banner (green) */}
        <div style={{ background:"linear-gradient(135deg,rgba(16,185,129,0.03),rgba(16,185,129,0.015))", borderTop:"3px solid #10B981", padding:"28px 0" }}>
          <div style={{ maxWidth:1280,margin:"0 auto",padding:"0 32px",display:"flex",alignItems:"center",gap:12 }}>
            <div style={{ width:40,height:40,borderRadius:12,background:"#10B981",color:"white",display:"flex",alignItems:"center",justifyContent:"center" }}><Home size={20}/></div>
            <h2 style={{ fontFamily:"'Sora',sans-serif",fontSize:22,fontWeight:800,color:"#10B981",letterSpacing:"-0.03em" }}>{t.tabs.home}</h2>
          </div>
        </div>

        {/* SCREEN TIME (mockup age cards, sheet data) */}
        <section id="screentime" style={{ background:"linear-gradient(180deg,#FFFDF5 0%,#FAFBFD 100%)",padding:"72px 0" }}>
          <div style={{ maxWidth:1280,margin:"0 auto",padding:"0 32px" }}>
            <Reveal><div style={{ textAlign:"center",marginBottom:48 }}>
              <span style={{ display:"inline-flex",alignItems:"center",gap:6,padding:"6px 14px",borderRadius:8,background:"#FFFBEB",color:"#F59E0B",fontSize:11,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.1em",fontFamily:"'Space Mono',monospace",marginBottom:14 }}><Clock size={13}/> {lang==="en"?"Health & Wellness":"Salud y Bienestar"}</span>
              <h2 style={{ fontFamily:"'Sora',sans-serif",fontSize:36,fontWeight:800,color:"#0F172A",letterSpacing:"-0.04em",marginBottom:10 }}>{lang==="en"?"Screen Time":"Tiempo en Pantalla"}</h2>
            </div></Reveal>
            <div style={{ maxWidth:800,margin:"0 auto" }}>
              {(grp['Screen Time']||[]).map((r,i) => (
                <Reveal key={i} delay={0.1+i*0.08}><div className="age-card" style={{ background:ageBgs[i%5],marginBottom:12,borderRadius:20 }}>
                  <div style={{ width:64,height:64,borderRadius:18,flexShrink:0,background:"white",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",boxShadow:`0 4px 12px ${ageColors[i%5]}20`,border:`2px solid ${ageColors[i%5]}30` }}>
                    <Clock size={22} style={{ color:ageColors[i%5] }} />
                  </div>
                  <div style={{ flex:1 }}><h4 style={{ fontSize:15,fontWeight:800,color:"#0F172A",fontFamily:"'Sora',sans-serif",marginBottom:4 }}>{r.Title}</h4><p style={{ fontSize:14.5,color:"#334155",lineHeight:1.7 }}>{r.Description}</p></div>
                </div></Reveal>
              ))}
            </div>
          </div>
        </section>

        {/* PARENTAL CONTROLS (mockup tool cards, sheet data) */}
        <section id="home" style={{ maxWidth:1280,margin:"0 auto",padding:"72px 32px" }}>
          <Reveal><div style={{ textAlign:"center",marginBottom:48 }}>
            <span style={{ display:"inline-flex",alignItems:"center",gap:6,padding:"6px 14px",borderRadius:8,background:"#FCE7F3",color:"#EC4899",fontSize:11,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.1em",fontFamily:"'Space Mono',monospace",marginBottom:14 }}><Home size={13}/> {lang==="en"?"For Families":"Para Familias"}</span>
            <h2 style={{ fontFamily:"'Sora',sans-serif",fontSize:36,fontWeight:800,color:"#0F172A",letterSpacing:"-0.04em",marginBottom:10 }}>{lang==="en"?"Parental Controls":"Controles Parentales"}</h2>
          </div></Reveal>
          {/* Intro from overview */}
          {(grp['Parental Controls']||[]).length>0 && <Reveal delay={0.1}><p style={{ textAlign:"center",fontSize:15,color:"#475569",maxWidth:640,margin:"0 auto 36px",lineHeight:1.75 }}>{(grp['Parental Controls']||[])[0]?.Description}</p></Reveal>}
          {/* Tool cards from parental sheet — one card per tool column */}
          {parentalToolKeys.length > 0 && (
            <div className="parental-grid" style={{ display:"grid",gridTemplateColumns:`repeat(${Math.min(parentalToolKeys.length,3)},1fr)`,gap:20,marginBottom:40 }}>
              {parentalToolKeys.map((tool,i) => {
                const features = parentalRows.slice(0,5);
                const platforms = parentalRows.find(r => (r.Feature||'').toLowerCase().includes('platform'));
                return (
                  <Reveal key={i} delay={0.15+i*0.08}><div style={{ borderRadius:24,background:"white",border:"1px solid #E2E8F0",overflow:"hidden",transition:"all 0.35s" }}
                    onMouseEnter={e => { e.currentTarget.style.transform="translateY(-6px)"; e.currentTarget.style.boxShadow="0 24px 48px -12px rgba(0,0,0,0.12)"; }}
                    onMouseLeave={e => { e.currentTarget.style.transform=""; e.currentTarget.style.boxShadow=""; }}>
                    <div style={{ height:4,background:parentalColors[i%3] }} />
                    <div style={{ padding:28 }}>
                      <h3 style={{ fontSize:18,fontWeight:800,color:"#0F172A",marginBottom:10,fontFamily:"'Sora',sans-serif" }}>{tool}</h3>
                      {/* Show first few features for this tool */}
                      {features.map((row,j) => row[tool] ? (
                        <div key={j} style={{ display:"flex",gap:8,alignItems:"flex-start",marginBottom:8 }}>
                          <CheckCircle2 size={14} style={{ color:"#10B981",flexShrink:0,marginTop:3 }} />
                          <span style={{ fontSize:13,color:"#64748B",lineHeight:1.5 }}><strong style={{ color:"#334155" }}>{row.Feature}:</strong> {row[tool]}</span>
                        </div>
                      ) : null)}
                      {/* Platforms row */}
                      {platforms && platforms[tool] && (
                        <div style={{ display:"flex",gap:6,flexWrap:"wrap",marginTop:12 }}>
                          {platforms[tool].split(',').map((p,j) => <span key={j} style={{ padding:"4px 10px",borderRadius:6,fontSize:11,fontWeight:600,background:"#F1F5F9",color:"#475569" }}>{p.trim()}</span>)}
                        </div>
                      )}
                    </div>
                  </div></Reveal>
                );
              })}
            </div>
          )}
          <Reveal delay={0.3}><div style={{ textAlign:"center" }}>
            <button className="data-link-btn" onClick={() => openModal('parental')}>👨‍👩‍👧 {t.viewData} <ExternalLink size={13}/></button>
          </div></Reveal>
        </section>

        {/* SHARED RESPONSIBILITY (mockup banner) */}
        {(grp['Shared Responsibility']||[]).length > 0 && (
          <section style={{ position:"relative",overflow:"hidden",background:"linear-gradient(155deg,#050E1F 0%,#0A2240 30%,#0F4C81 70%,#1A6FB5 100%)",padding:"80px 0" }}>
            <div style={{ maxWidth:1280,margin:"0 auto",padding:"0 32px",position:"relative",zIndex:1 }}>
              <Reveal><div style={{ textAlign:"center" }}>
                <h2 style={{ fontFamily:"'Sora',sans-serif",fontSize:40,fontWeight:800,color:"white",letterSpacing:"-0.04em",marginBottom:16 }}>{(grp['Shared Responsibility']||[])[0]?.Title || (lang==="en"?"Shared Responsibility":"Responsabilidad Compartida")}</h2>
                <p style={{ fontSize:16,color:"rgba(255,255,255,0.65)",maxWidth:600,margin:"0 auto 48px",lineHeight:1.75 }}>{(grp['Shared Responsibility']||[])[0]?.Description}</p>
              </div></Reveal>
              <Reveal delay={0.2}><div className="shared-flow" style={{ display:"flex",alignItems:"center",justifyContent:"center",gap:24 }}>
                {[{ icon:<Shield size={32}/>,label:lang==="en"?"School":"Colegio",color:"#C9A227",bg:"rgba(201,162,39,0.15)" },{arrow:true},{icon:<Home size={32}/>,label:lang==="en"?"Family":"Familia",color:"#F5D35E",bg:"rgba(245,211,94,0.15)" },{arrow:true},{icon:<Users size={32}/>,label:lang==="en"?"Together":"Juntos",color:"#2DD4BF",bg:"rgba(45,212,191,0.15)" }].map((s,i) => s.arrow ? <div key={i} style={{ color:"rgba(255,255,255,0.2)",fontSize:28 }}>→</div> : (
                  <div key={i} style={{ display:"flex",flexDirection:"column",alignItems:"center",gap:14 }}>
                    <div style={{ width:80,height:80,borderRadius:24,background:s.bg,border:`1.5px solid ${s.color}40`,display:"flex",alignItems:"center",justifyContent:"center",color:s.color }}>{s.icon}</div>
                    <span style={{ fontSize:14,fontWeight:700,color:"white",fontFamily:"'Sora',sans-serif" }}>{s.label}</span>
                  </div>
                ))}
              </div></Reveal>
            </div>
          </section>
        )}
      </div>

      {/* ══════════ TAB: 360° PROTECTION ══════════ */}
      <div id="section-bridge" style={{ display: activeTab === "bridge" ? "block" : "none" }}>
        {/* Section Banner (gold) */}
        <div style={{ background:"linear-gradient(135deg,rgba(201,162,39,0.03),rgba(201,162,39,0.015))", borderTop:"3px solid #C9A227", padding:"28px 0" }}>
          <div style={{ maxWidth:1280,margin:"0 auto",padding:"0 32px",display:"flex",alignItems:"center",gap:12 }}>
            <div style={{ width:40,height:40,borderRadius:12,background:"#C9A227",color:"white",display:"flex",alignItems:"center",justifyContent:"center" }}><Layers size={20}/></div>
            <h2 style={{ fontFamily:"'Sora',sans-serif",fontSize:22,fontWeight:800,color:"#C9A227",letterSpacing:"-0.03em" }}>{t.tabs.bridge}</h2>
          </div>
        </div>

        {/* NEW: Integration section — Qustodio + Linewize */}
        <section id="integration" style={{ maxWidth:1280,margin:"0 auto",padding:"56px 32px" }}>
          <Reveal>
            <div style={{ textAlign:"center",marginBottom:40 }}>
              <span style={{ display:"inline-flex",alignItems:"center",gap:6,padding:"5px 13px",borderRadius:8,background:"#FFFBEB",color:"#C9A227",fontSize:10,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.1em",fontFamily:"'Space Mono',monospace",marginBottom:12 }}>
                <RefreshCw size={12}/> {t.integrationLabel}
              </span>
              <h2 style={{ fontFamily:"'Sora',sans-serif",fontSize:32,fontWeight:800,color:"#0F172A",letterSpacing:"-0.04em",marginBottom:8 }}>{t.integrationTitle}</h2>
              <p style={{ fontSize:15,color:"#64748B",maxWidth:600,margin:"0 auto",marginBottom:12 }}>{t.integrationSubtitle}</p>
              <div style={{ display:"inline-flex",alignItems:"center",gap:6,padding:"6px 14px",borderRadius:50,background:"#FFFBEB",border:"1px solid #FDE68A",fontSize:12,fontWeight:700,color:"#92400E" }}>
                <Zap size={12}/> {lang==="en"?"Initially applies to 6th graders — expanding progressively":"Aplica inicialmente para estudiantes de 6° — se expande progresivamente"}
              </div>
            </div>
          </Reveal>
          <Reveal delay={0.06}>
            <p style={{ textAlign:"center",fontSize:14,color:"#475569",maxWidth:640,margin:"0 auto 36px",lineHeight:1.75 }}>{t.integrationIntro}</p>
          </Reveal>

          {/* Scenario selector */}
          <Reveal delay={0.1}>
            <div style={{ display:"flex",justifyContent:"center",gap:10,marginBottom:28,flexWrap:"wrap" }}>
              {scenarios.map((sc,i) => (
                <button key={i} onClick={() => setDiagramStep(i)} style={{
                  padding:"10px 20px",borderRadius:12,fontSize:13,fontWeight:700,
                  border:`2px solid ${diagramStep===i?sc.border:"#E2E8F0"}`,
                  background:diagramStep===i?sc.bg:"white",
                  color:diagramStep===i?sc.color:"#64748B",
                  cursor:"pointer",display:"flex",alignItems:"center",gap:8,transition:"all 0.3s"
                }}>{sc.icon} {sc.title}</button>
              ))}
            </div>
          </Reveal>

          {/* Active scenario card */}
          <Reveal delay={0.14}>
            {(() => {
              const sc = scenarios[diagramStep];
              return (
                <div style={{ maxWidth:800,margin:"0 auto 36px",borderRadius:24,border:`2px solid ${sc.border}30`,background:sc.bg,padding:36,transition:"all 0.4s" }}>
                  <div style={{ display:"flex",alignItems:"center",gap:12,marginBottom:6 }}>
                    <div style={{ width:44,height:44,borderRadius:13,background:`${sc.border}20`,color:sc.color,display:"flex",alignItems:"center",justifyContent:"center" }}>{sc.icon}</div>
                    <div>
                      <h3 style={{ fontSize:18,fontWeight:800,color:sc.color,fontFamily:"'Sora',sans-serif" }}>{sc.title}</h3>
                      <p style={{ fontSize:12,color:`${sc.color}99` }}>{sc.subtitle}</p>
                    </div>
                  </div>
                  <div style={{ display:"grid",gridTemplateColumns:"1fr 1fr",gap:16,marginTop:24 }}>
                    {/* Linewize */}
                    <div style={{ padding:20,borderRadius:16,background:"white",border:`1px solid ${sc.linewize.active?"#3B82F6":"#E2E8F0"}` }}>
                      <div style={{ display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10 }}>
                        <span style={{ fontSize:14,fontWeight:800,color:"#0F172A",fontFamily:"'Sora',sans-serif" }}>Linewize</span>
                        <span style={{
                          padding:"3px 10px",borderRadius:6,fontSize:10,fontWeight:800,fontFamily:"'Space Mono',monospace",
                          background:sc.linewize.active?"#EFF6FF":"#F1F5F9",
                          color:sc.linewize.active?"#3B82F6":"#94A3B8"
                        }}>{sc.linewize.label}</span>
                      </div>
                      <p style={{ fontSize:12.5,color:"#64748B",lineHeight:1.65 }}>{sc.linewize.desc}</p>
                    </div>
                    {/* Qustodio */}
                    <div style={{ padding:20,borderRadius:16,background:"white",border:`1px solid ${sc.qustodio.active?"#10B981":"#E2E8F0"}` }}>
                      <div style={{ display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10 }}>
                        <span style={{ fontSize:14,fontWeight:800,color:"#0F172A",fontFamily:"'Sora',sans-serif" }}>Qustodio</span>
                        <span style={{
                          padding:"3px 10px",borderRadius:6,fontSize:10,fontWeight:800,fontFamily:"'Space Mono',monospace",
                          background:sc.qustodio.active?"#ECFDF5":"#FEF2F2",
                          color:sc.qustodio.active?"#10B981":"#EF4444"
                        }}>{sc.qustodio.label}</span>
                      </div>
                      <p style={{ fontSize:12.5,color:"#64748B",lineHeight:1.65 }}>{sc.qustodio.desc}</p>
                    </div>
                  </div>
                  <div style={{ marginTop:18,padding:"12px 16px",borderRadius:10,background:"rgba(255,255,255,0.7)",border:"1px dashed rgba(0,0,0,0.1)",fontSize:12,color:"#64748B",display:"flex",alignItems:"flex-start",gap:8,lineHeight:1.6 }}>
                    <Zap size={14} style={{ flexShrink:0,marginTop:2,color:"#C9A227" }}/> {sc.note}
                  </div>
                </div>
              );
            })()}
          </Reveal>

          {/* Traffic flow */}
          <Reveal delay={0.18}>
            <div style={{ maxWidth:800,margin:"0 auto 36px" }}>
              <h3 style={{ fontFamily:"'Sora',sans-serif",fontSize:18,fontWeight:800,color:"#0F172A",marginBottom:16,textAlign:"center" }}>{t.integrationTrafficTitle}</h3>
              <div style={{ display:"flex",alignItems:"center",justifyContent:"center",gap:10,flexWrap:"wrap" }}>
                {[
                  { icon:<Laptop size={18}/>,label:lang==="en"?"Device":"Dispositivo",color:"#3B82F6" },
                  { arrow:true },
                  { icon:<Wifi size={18}/>,label:lang==="en"?"Network Detection":"Detección de Red",color:"#F59E0B" },
                  { arrow:true },
                  { icon:<Shield size={18}/>,label:"Linewize",color:"#0F4C81" },
                  { arrow:true },
                  { icon:<Lock size={18}/>,label:"Qustodio",color:"#10B981" },
                  { arrow:true },
                  { icon:<Globe size={18}/>,label:lang==="en"?"Content":"Contenido",color:"#8B5CF6" }
                ].map((s,i) => s.arrow ? (
                  <ArrowRight key={i} size={16} style={{ color:"#CBD5E1" }}/>
                ) : (
                  <div key={i} style={{ display:"flex",flexDirection:"column",alignItems:"center",gap:6 }}>
                    <div style={{ width:44,height:44,borderRadius:12,background:`${s.color}12`,color:s.color,display:"flex",alignItems:"center",justifyContent:"center" }}>{s.icon}</div>
                    <span style={{ fontSize:10,fontWeight:700,color:"#64748B" }}>{s.label}</span>
                  </div>
                ))}
              </div>
            </div>
          </Reveal>

          {/* Block pages */}
          <Reveal delay={0.22}>
            <div style={{ maxWidth:800,margin:"0 auto 36px" }}>
              <h3 style={{ fontFamily:"'Sora',sans-serif",fontSize:18,fontWeight:800,color:"#0F172A",marginBottom:10,textAlign:"center" }}>{t.integrationBlockTitle}</h3>
              <p style={{ textAlign:"center",fontSize:13,color:"#64748B",marginBottom:18 }}>{t.integrationBlockDesc}</p>
              <div style={{ display:"grid",gridTemplateColumns:"1fr 1fr",gap:14,maxWidth:600,margin:"0 auto" }}>
                <div style={{ padding:16,borderRadius:14,background:"#EFF6FF",border:"1px solid #DBEAFE" }}>
                  <div style={{ display:"flex",alignItems:"center",gap:7,marginBottom:6 }}>
                    <Shield size={14} style={{ color:"#3B82F6" }}/>
                    <span style={{ fontSize:11,fontWeight:800,color:"#3B82F6",fontFamily:"'Space Mono',monospace" }}>SCHOOL</span>
                  </div>
                  <p style={{ fontSize:12,color:"#1E40AF",lineHeight:1.5 }}>{t.integrationSchoolBlock}</p>
                </div>
                <div style={{ padding:16,borderRadius:14,background:"#ECFDF5",border:"1px solid #D1FAE5" }}>
                  <div style={{ display:"flex",alignItems:"center",gap:7,marginBottom:6 }}>
                    <Lock size={14} style={{ color:"#10B981" }}/>
                    <span style={{ fontSize:11,fontWeight:800,color:"#10B981",fontFamily:"'Space Mono',monospace" }}>PARENT</span>
                  </div>
                  <p style={{ fontSize:12,color:"#065F46",lineHeight:1.5 }}>{t.integrationParentBlock}</p>
                </div>
              </div>
            </div>
          </Reveal>

          {/* FAQ accordion */}
          <Reveal delay={0.26}>
            <div style={{ maxWidth:700,margin:"0 auto" }}>
              <h3 style={{ fontFamily:"'Sora',sans-serif",fontSize:18,fontWeight:800,color:"#0F172A",marginBottom:16,textAlign:"center" }}>{t.integrationFaqTitle}</h3>
              {faqIntItems.map((faq,i) => (
                <div key={i} style={{ background:"white",borderRadius:22,border:"1px solid #E2E8F0",marginBottom:10,overflow:"hidden",transition:"all 0.35s cubic-bezier(0.16,1,0.3,1)" }}>
                  <button onClick={() => setExpandedFaq(expandedFaq===i?null:i)} style={{
                    width:"100%",padding:"16px 20px",background:expandedFaq===i?"#F8FAFC":"white",
                    border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"space-between",textAlign:"left"
                  }}>
                    <span style={{ fontSize:14,fontWeight:600,color:"#0F172A" }}>{faq.q}</span>
                    <ChevronDown size={18} style={{ color:"#C9A227",transition:"transform 0.3s",transform:expandedFaq===i?"rotate(180deg)":"none",flexShrink:0,marginLeft:12 }}/>
                  </button>
                  <div style={{ maxHeight:expandedFaq===i?300:0,overflow:"hidden",transition:"max-height 0.3s ease-out" }}>
                    <div style={{ padding:"0 20px 16px",fontSize:13,color:"#64748B",lineHeight:1.7 }}>{faq.a}</div>
                  </div>
                </div>
              ))}
            </div>
          </Reveal>
        </section>

        {/* BYOD (mockup device tabs, sheet data) */}
        <section id="byod" style={{ maxWidth:1280,margin:"0 auto",padding:"72px 32px" }}>
          <Reveal><div style={{ textAlign:"center",marginBottom:48 }}>
            <span style={{ display:"inline-flex",alignItems:"center",gap:6,padding:"6px 14px",borderRadius:8,background:"#EBF0F5",color:"#2C3E50",fontSize:11,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.1em",fontFamily:"'Space Mono',monospace",marginBottom:14 }}><Laptop size={13}/> {lang==="en"?"Middle & High School":"Escuela Media y Alta"}</span>
            <h2 style={{ fontFamily:"'Sora',sans-serif",fontSize:36,fontWeight:800,color:"#0F172A",letterSpacing:"-0.04em",marginBottom:10 }}>{lang==="en"?"BYOD Program":"Programa BYOD"}</h2>
          </div></Reveal>

          {/* Device selector tabs */}
          {byodDeviceKeys.length > 0 && (
            <>
              <Reveal delay={0.15}><div style={{ display:"flex",justifyContent:"center",gap:12,marginBottom:32 }}>
                {byodDeviceKeys.map((key,i) => {
                  const color = deviceColors[i%deviceColors.length];
                  return <button key={key} className={`device-btn ${selDevice===key?"active":""}`}
                    style={selDevice===key?{background:color,borderColor:color,boxShadow:`0 8px 24px ${color}30`}:{}}
                    onClick={() => setSelDevice(key)}>{key}</button>;
                })}
              </div></Reveal>

              <Reveal delay={0.2}><div style={{ maxWidth:640,margin:"0 auto" }}>
                <div style={{ borderRadius:24,background:"white",border:"1px solid #E2E8F0",overflow:"hidden" }}>
                  <div style={{ height:4,background:deviceColors[byodDeviceKeys.indexOf(selDevice)%deviceColors.length] }} />
                  <div style={{ padding:36 }}>
                    {byodRows.filter(r => r[selDevice]).map((row,i) => (
                      <div key={i} style={{ display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 0",borderBottom:i<byodRows.filter(r=>r[selDevice]).length-1?"1px solid #F1F5F9":"none" }}>
                        <div style={{ display:"flex",alignItems:"center",gap:10,color:"#475569" }}>
                          <span style={{ color:"#94A3B8" }}>{[<Cpu size={16}/>,<Zap size={16}/>,<HardDrive size={16}/>,<MonitorSmartphone size={16}/>,<Settings size={16}/>,<Wifi size={16}/>,<Shield size={16}/>][i%7]}</span>
                          <span style={{ fontSize:14,fontWeight:600 }}>{row.Feature || row.Category}</span>
                        </div>
                        <span style={{ fontSize:14,fontWeight:700,color:"#0F172A",fontFamily:"'Space Mono',monospace",textAlign:"right",maxWidth:"55%" }}>{row[selDevice]}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div></Reveal>
            </>
          )}

          <Reveal delay={0.3}><div style={{ textAlign:"center",marginTop:24,display:"flex",justifyContent:"center",gap:12,flexWrap:"wrap" }}>
            <button className="data-link-btn" onClick={() => openModal('byod')}>💻 {t.viewData} <ExternalLink size={13}/></button>
            <a href="https://drive.google.com/file/d/1T66VnnmPsJXImbLrFWx7T87zWI0fAG3F/view?usp=sharing" target="_blank" rel="noopener noreferrer" className="data-link-btn" style={{ textDecoration:"none" }}>🤝 {lang==="en"?"Partnerships":"Convenios"} <ExternalLink size={13}/></a>
          </div></Reveal>
        </section>
      </div>

      {/* ══════════ CHATBOT CTA (mockup design) — OUTSIDE TABS ══════════ */}
      <section style={{ maxWidth:1280,margin:"0 auto",padding:"72px 32px" }}>
        <Reveal><div style={{ position:"relative",overflow:"hidden",borderRadius:32,background:"linear-gradient(135deg,#0F4C81,#1A6FB5,#2A8FD5)",padding:"64px 48px",textAlign:"center" }}>
          <div style={{ position:"absolute",top:-80,right:-80,width:300,height:300,borderRadius:"50%",background:"rgba(201,162,39,0.12)",pointerEvents:"none" }} />
          <div style={{ position:"relative",zIndex:1 }}>
            <div style={{ width:72,height:72,borderRadius:22,margin:"0 auto 24px",background:"rgba(255,255,255,0.12)",border:"1px solid rgba(255,255,255,0.2)",display:"flex",alignItems:"center",justifyContent:"center",color:"white",animation:"float 4s ease-in-out infinite" }}><Sparkles size={36}/></div>
            <h2 style={{ fontFamily:"'Sora',sans-serif",fontSize:34,fontWeight:800,color:"white",letterSpacing:"-0.03em",marginBottom:12 }}>{t.chatTitle}</h2>
            <p style={{ fontSize:16,color:"rgba(255,255,255,0.7)",maxWidth:500,margin:"0 auto 32px",lineHeight:1.7 }}>{t.chatSub}</p>
            <button onClick={() => setChatOpen(true)} style={{ padding:"16px 36px",borderRadius:16,fontSize:15,fontWeight:800,background:"#C9A227",color:"#0A2240",border:"none",cursor:"pointer",display:"inline-flex",alignItems:"center",gap:10,boxShadow:"0 8px 32px rgba(201,162,39,0.4)",fontFamily:"'Sora',sans-serif" }}><MessageCircle size={18}/> {t.chatCta}</button>
          </div>
        </div></Reveal>
      </section>

      {/* ══════════ FOOTER (resources from sheet) — OUTSIDE TABS ══════════ */}
      <footer style={{ borderTop:"1px solid #E2E8F0",background:"white",padding:"48px 0" }}>
        <div style={{ maxWidth:1280,margin:"0 auto",padding:"0 32px" }}>
          <div style={{ display:"flex",justifyContent:"space-between",alignItems:"flex-start",flexWrap:"wrap",gap:32 }}>
            <div>
              <div style={{ display:"flex",alignItems:"center",gap:12,marginBottom:12 }}><img src="./escudo.png" alt="CNG" style={{ width:36,height:36,borderRadius:10 }}/><span style={{ fontSize:15,fontWeight:800,color:"#0F172A",fontFamily:"'Sora',sans-serif" }}>CNG Digital Wellbeing</span></div>
              <p style={{ fontSize:13,color:"#94A3B8" }}>© 2025 Colegio Nueva Granada</p>
            </div>
            <div style={{ display:"flex",gap:8,flexWrap:"wrap",maxWidth:600 }}>
              {resourcesRows.map((r,i) => { const name=get(r,'Resource','Title'); const link=get(r,'Link/Contact','Link'); if(!name) return null;
                return <a key={i} href={link&&link.startsWith('http')?link:'#'} target={link&&link.startsWith('http')?'_blank':undefined} rel="noopener noreferrer"
                  style={{ fontSize:11,color:"#64748B",textDecoration:"none",padding:"5px 10px",borderRadius:8,background:"#F8FAFC",fontWeight:500,transition:"all 0.2s" }}
                  onMouseEnter={e => { e.target.style.background="#EFF6FF"; e.target.style.color="#0F4C81"; }} onMouseLeave={e => { e.target.style.background="#F8FAFC"; e.target.style.color="#64748B"; }}>{name}</a>;
              })}
            </div>
          </div>
        </div>
      </footer>

      {/* ══════════ DATA MODAL ══════════ */}
      <div className={`modal-overlay ${activeCategory?'open':''}`} onClick={() => closeModal()}>
        <div className="modal" onClick={e => e.stopPropagation()}>
          {activeCategory && (<>
            <div className="modal-header">
              <div className="modal-title"><span>{activeCategory.icon}</span> {lang==="en"?activeCategory.name:activeCategory.nameEs}</div>
              <button className="modal-close" onClick={() => closeModal()}><X size={16}/></button>
            </div>
            <div className="modal-content">
              {activeData.length===0 ? <div style={{ textAlign:"center",padding:40,color:"#94A3B8" }}><div style={{ fontSize:40,marginBottom:12 }}>📊</div><p>{lang==="en"?"Loading...":"Cargando..."}</p></div>
              : activeCategory.isTable ? <div style={{ overflowX:"auto" }}><table className="data-table"><thead><tr>{Object.keys(activeData[0]).map(h => <th key={h}>{h}</th>)}</tr></thead><tbody>{activeData.map((row,i) => <tr key={i}>{Object.entries(row).map(([k,v]) => <td key={k}>{v==='Allow'?<span className="status-allow">✓ Allow</span>:v==='Block'?<span className="status-block">✕ Block</span>:NOTE_INFO[v]?<NoteCell value={v} lang={lang}/>:v}</td>)}</tr>)}</tbody></table></div>
              : activeCategory.isFaq ? activeData.map((row,i) => <div key={i} className={`accordion-item ${expandedItems[i]?'open':''}`}><div className="accordion-header" onClick={() => toggleItem(i)}><span className="accordion-title">{get(row,'Question')}</span><span className="accordion-icon">▾</span></div><div className="accordion-body"><div className="accordion-content">{get(row,'Answer')}</div></div></div>)
              : activeCategory.id === 'resources' ? activeData.map((row,i) => { const name=get(row,'Title','Resource'); const link=get(row,'Link/Contact','Link'); const desc=get(row,'Description'); return name ? <a key={i} href={link&&link.startsWith('http')?link:'#'} target={link&&link.startsWith('http')?'_blank':undefined} rel="noopener noreferrer" style={{ display:"flex",alignItems:"center",justifyContent:"space-between",padding:"16px 20px",borderRadius:16,border:"1px solid #E2E8F0",marginBottom:10,textDecoration:"none",transition:"all 0.25s",background:"white",cursor:"pointer" }} onMouseEnter={e=>{e.currentTarget.style.borderColor="#0F4C81";e.currentTarget.style.background="#F8FBFF";}} onMouseLeave={e=>{e.currentTarget.style.borderColor="#E2E8F0";e.currentTarget.style.background="white";}}><div><div style={{ fontWeight:600,color:"#0F172A",fontSize:15 }}>{name}</div>{desc && <div style={{ fontSize:13,color:"#64748B",marginTop:4 }}>{desc}</div>}</div>{link&&link.startsWith('http')&&<ExternalLink size={16} style={{ color:"#94A3B8",flexShrink:0,marginLeft:12 }}/>}</a> : null; })
              : activeData.map((row,i) => <div key={i} className={`accordion-item ${expandedItems[i]?'open':''}`}><div className="accordion-header" onClick={() => toggleItem(i)}><span className="accordion-title">{get(row,'Title','Resource')}</span><span className="accordion-icon">▾</span></div><div className="accordion-body"><div className="accordion-content">{get(row,'Description','Link/Contact')}</div></div></div>)}
            </div>
          </>)}
        </div>
      </div>

      {/* ══════════ CHAT FAB + WINDOW (mockup design) ══════════ */}
      {!chatOpen && <button className="chat-fab" onClick={() => setChatOpen(true)}><MessageCircle size={28}/><div style={{ position:"absolute",inset:-4,borderRadius:24,border:"2px solid rgba(15,76,129,0.3)",animation:"ripple 2s ease-out infinite",pointerEvents:"none" }} /></button>}
      {chatOpen && (
        <div className="chat-win">
          <div style={{ background:"linear-gradient(135deg,#0A2E5C,#0F4C81,#1A6FB5)",padding:"20px 24px",display:"flex",alignItems:"center",justifyContent:"space-between" }}>
            <div style={{ display:"flex",alignItems:"center",gap:12 }}>
              <div style={{ width:40,height:40,borderRadius:14,background:"rgba(255,255,255,0.12)",border:"1px solid rgba(255,255,255,0.15)",display:"flex",alignItems:"center",justifyContent:"center",color:"white" }}><Sparkles size={20}/></div>
              <div><div style={{ fontSize:14,fontWeight:800,color:"white",fontFamily:"'Sora',sans-serif" }}>CNG Tech Assistant</div><div style={{ fontSize:11,color:"rgba(255,255,255,0.55)",display:"flex",alignItems:"center",gap:6 }}><div style={{ width:6,height:6,borderRadius:"50%",background:"#2DD4BF" }}/>{t.chatOnline}</div></div>
            </div>
            <button onClick={() => setChatOpen(false)} style={{ background:"rgba(255,255,255,0.1)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:10,width:34,height:34,cursor:"pointer",color:"white",display:"flex",alignItems:"center",justifyContent:"center" }}><X size={16}/></button>
          </div>
          <div ref={chatRef} style={{ flex:1,padding:20,overflowY:"auto",maxHeight:360,display:"flex",flexDirection:"column",gap:14,background:"#FAFBFD" }}>
            {chatMsgs.map((msg,i) => (
              <div key={i} style={{ display:"flex",flexDirection:"column",alignItems:msg.role==="user"?"flex-end":"flex-start",animation:"fadeUp 0.3s ease" }}>
                <div style={{ display:"flex",justifyContent:msg.role==="user"?"flex-end":"flex-start" }}>
                  {msg.role==="bot" && <div style={{ width:28,height:28,borderRadius:8,background:"#EFF6FF",display:"flex",alignItems:"center",justifyContent:"center",marginRight:8,flexShrink:0,marginTop:4 }}><Sparkles size={14} style={{ color:"#0F4C81" }}/></div>}
                  <div className="msg-bubble" style={{ borderRadius:msg.role==="user"?"16px 16px 4px 16px":"16px 16px 16px 4px",background:msg.role==="user"?"linear-gradient(135deg,#0F4C81,#1A6FB5)":"white",color:msg.role==="user"?"white":"#334155",border:msg.role==="bot"?"1px solid #E2E8F0":"none",whiteSpace:"pre-wrap" }}>{msg.role==="bot" ? <ChatMessage text={msg.text} onOpenModal={openModal} onScrollTo={go} /> : msg.text}</div>
                </div>
                {msg.role==="bot" && !msg.streaming && msg.logRow && (
                  <div style={{ display:"flex",gap:4,marginLeft:36,marginTop:4 }}>
                    <button onClick={() => sendFeedback(i, 'helpful')} disabled={!!msg.feedbackGiven}
                      style={{ padding:"3px 8px",borderRadius:8,border:"1px solid "+(msg.feedbackGiven==='helpful'?"#0F4C81":"#E2E8F0"),background:msg.feedbackGiven==='helpful'?"#EFF6FF":"transparent",cursor:msg.feedbackGiven?"default":"pointer",opacity:msg.feedbackGiven&&msg.feedbackGiven!=='helpful'?0.3:1,display:"flex",alignItems:"center",gap:3,fontSize:11,color:msg.feedbackGiven==='helpful'?"#0F4C81":"#94A3B8",transition:"all 0.2s" }}>
                      <ThumbsUp size={12}/>
                    </button>
                    <button onClick={() => sendFeedback(i, 'not_helpful')} disabled={!!msg.feedbackGiven}
                      style={{ padding:"3px 8px",borderRadius:8,border:"1px solid "+(msg.feedbackGiven==='not_helpful'?"#EF4444":"#E2E8F0"),background:msg.feedbackGiven==='not_helpful'?"#FEF2F2":"transparent",cursor:msg.feedbackGiven?"default":"pointer",opacity:msg.feedbackGiven&&msg.feedbackGiven!=='not_helpful'?0.3:1,display:"flex",alignItems:"center",gap:3,fontSize:11,color:msg.feedbackGiven==='not_helpful'?"#EF4444":"#94A3B8",transition:"all 0.2s" }}>
                      <ThumbsDown size={12}/>
                    </button>
                  </div>
                )}
              </div>
            ))}
            {typing && <div className="typing"><span></span><span></span><span></span></div>}
          </div>
          <div style={{ fontSize:10,color:"#94A3B8",textAlign:"center",padding:"6px 20px 0",background:"white",borderTop:"1px solid #E2E8F0" }}>{t.privacyNotice}</div>
          <div style={{ padding:"12px 20px 16px",background:"white",display:"flex",gap:10 }}>
            <input value={chatIn} onChange={e => setChatIn(e.target.value)} onKeyDown={e => e.key==="Enter"&&sendMessage()} placeholder={t.chatPlaceholder} disabled={typing}
              style={{ flex:1,padding:"12px 16px",borderRadius:14,border:"1px solid #E2E8F0",fontSize:14,outline:"none",fontFamily:"inherit",background:"#F8FAFC" }}
              onFocus={e => e.target.style.borderColor="#0F4C81"} onBlur={e => e.target.style.borderColor="#E2E8F0"} />
            <button onClick={sendMessage} disabled={typing||!chatIn.trim()} style={{ width:46,height:46,borderRadius:14,background:"linear-gradient(135deg,#0F4C81,#1A6FB5)",color:"white",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",opacity:typing||!chatIn.trim()?0.5:1 }}><Send size={18}/></button>
          </div>
        </div>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
