import React, { useState, useEffect, useRef } from 'react';
import { createRoot } from 'react-dom/client';
import { 
  GoogleGenAI, 
  Modality, 
  LiveServerMessage,
} from '@google/genai';
import { 
  MessageSquare, 
  Image as ImageIcon, 
  Mic, 
  MicOff, 
  Send, 
  Sparkles, 
  Search, 
  History, 
  Layers,
  Zap, 
  Loader2,
  ExternalLink,
  ChevronRight,
  Home as HomeIcon,
  ArrowRight,
  Heart,
  Brain,
  Coffee,
  Stars,
  Quote,
  CheckCircle2,
  ShieldCheck,
  MousePointer2,
  Clock,
  Sparkle,
  FileText,
  User,
  MapPin,
  Stethoscope,
  Info,
  BookOpen,
  Phone,
  LayoutDashboard,
  Mail,
  Globe,
  Grid,
  BarChart3,
  Calendar,
  CreditCard,
  Settings,
  Shield,
  Activity,
  Users,
  AlertCircle,
  TrendingUp,
  FileSearch,
  Plus,
  MoreVertical,
  Bell,
  Truck,
  FileUp,
  Link as LinkIcon,
  Filter,
  Check,
  X,
  Clock3,
  BarChart,
  Trophy,
  Calculator,
  Target,
  LineChart,
  Eye,
  PieChart,
  Map as MapIcon,
  Briefcase,
  ZapOff,
  UserCheck,
  DollarSign,
  Download,
  Smartphone,
  SendHorizontal,
  Inbox,
  ShieldAlert,
  FileBadge,
  Stamp,
  ClipboardList,
  Headphones,
  Scale,
  Smile,
  Frown,
  Utensils,
  Ambulance,
  Menu,
  Moon,
  Sun,
  LogOut,
  ChevronDown,
  Library,
  GraduationCap,
  PlayCircle,
  Hash,
  Share2,
  Command,
  Instagram,
  Twitter,
  Linkedin,
  Navigation,
  Compass,
  ArrowLeft,
  StickyNote,
  Server,
  Cloud,
  FileCode
} from 'lucide-react';

// --- Utility Functions for Audio (Live API) ---
function encode(bytes: Uint8Array) {
  let binary = '';
  const len = bytes.byteLength;
  for (let i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return btoa(binary);
}

function decode(base64: string) {
  const binaryString = atob(base64);
  const len = binaryString.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes;
}

async function decodeAudioData(
  data: Uint8Array,
  ctx: AudioContext,
  sampleRate: number,
  numChannels: number,
): Promise<AudioBuffer> {
  const dataInt16 = new Int16Array(data.buffer);
  const frameCount = dataInt16.length / numChannels;
  const buffer = ctx.createBuffer(numChannels, frameCount, sampleRate);

  for (let channel = 0; channel < numChannels; channel++) {
    const channelData = buffer.getChannelData(channel);
    for (let i = 0; i < frameCount; i++) {
      channelData[i] = dataInt16[i * numChannels + channel] / 32768.0;
    }
  }
  return buffer;
}

const App: React.FC = () => {
  type Tabs = 'home' | 'chat' | 'image' | 'live' | 'admission' | 'methodology' | 'contact' | 'status' | 'solutions' | 'settings' | 'dashboard' | 'resources' | 'faculty' | 'fees-billing' | 'academic-records' | 'attendance' | 'schedule' | 'incident-management' | 'progress-tracking' | 'communications' | 'map' | 'lesson';
  const [activeTab, setActiveTab] = useState<Tabs>('home');
  const [messages, setMessages] = useState<{ role: 'user' | 'model'; text: string; sources?: any[] }[]>([]);
  const [chatInput, setChatInput] = useState('');
  const [isSearching, setIsSearching] = useState(false);
  const [isTyping, setIsTyping] = useState(false);

  const [imagePrompt, setImagePrompt] = useState('');
  const [generatedImage, setGeneratedImage] = useState<string | null>(null);
  const [isGeneratingImage, setIsGeneratingImage] = useState(false);

  const [isLiveActive, setIsLiveActive] = useState(false);
  const [isNotifOpen, setIsNotifOpen] = useState(false);
  
  // Dashboard states
  const [currentTime, setCurrentTime] = useState(new Date());
  
  // Resources states
  const [resourceSearch, setResourceSearch] = useState('');
  
  // Faculty states
  const [selectedFaculty, setSelectedFaculty] = useState<any | null>(null);
  
  // Lesson states
  const [studentNotes, setStudentNotes] = useState('');
  
  // Admission Form State
  const [admissionStep, setAdmissionStep] = useState(1);
  const [statusId, setStatusId] = useState('');
  const [isCheckingStatus, setIsCheckingStatus] = useState(false);
  const [statusResult, setStatusResult] = useState<null | 'pending' | 'accepted' | 'not_found'>(null);
  
  // Incident Form State
  const [incidentType, setIncidentType] = useState('Medico');
  const [incidentDesc, setIncidentDesc] = useState('');
  const [isReporting, setIsReporting] = useState(false);

  const audioContextInputRef = useRef<AudioContext | null>(null);
  const audioContextOutputRef = useRef<AudioContext | null>(null);
  const liveSessionRef = useRef<any>(null);
  const nextStartTimeRef = useRef(0);

  useEffect(() => {
    const timer = setInterval(() => setCurrentTime(new Date()), 1000);
    return () => clearInterval(timer);
  }, []);

  const handleSendMessage = async (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    if (!chatInput.trim() || isTyping) return;
    const userMsg = chatInput;
    setMessages(prev => [...prev, { role: 'user', text: userMsg }]);
    setChatInput('');
    setIsTyping(true);
    try {
      const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
      const config: any = {};
      if (isSearching) config.tools = [{ googleSearch: {} }];
      const response = await ai.models.generateContent({
        model: 'gemini-3-flash-preview',
        contents: userMsg,
        config: config
      });
      const text = response.text || "No response generado.";
      const sources = response.candidates?.[0]?.groundingMetadata?.groundingChunks || [];
      setMessages(prev => [...prev, { role: 'model', text, sources }]);
    } catch (err) {
      setMessages(prev => [...prev, { role: 'model', text: "Error de conexión con la IA." }]);
    } finally {
      setIsTyping(false);
    }
  };

  const handleGenerateImage = async () => {
    if (!imagePrompt.trim() || isGeneratingImage) return;
    setIsGeneratingImage(true);
    setGeneratedImage(null);
    try {
      const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
      const response = await ai.models.generateContent({
        model: 'gemini-2.5-flash-image',
        contents: { parts: [{ text: imagePrompt }] },
      });
      for (const part of response.candidates[0].content.parts) {
        if (part.inlineData) {
          setGeneratedImage(`data:image/png;base64,${part.inlineData.data}`);
          break;
        }
      }
    } catch (err) {
      alert("Error al generar imagen.");
    } finally {
      setIsGeneratingImage(false);
    }
  };

  const startLiveSession = async () => {
    try {
      const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
      audioContextInputRef.current = new AudioContext({ sampleRate: 16000 });
      audioContextOutputRef.current = new AudioContext({ sampleRate: 24000 });
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      const sessionPromise = ai.live.connect({
        model: 'gemini-2.5-flash-native-audio-preview-12-2025',
        callbacks: {
          onopen: () => {
            setIsLiveActive(true);
            const source = audioContextInputRef.current!.createMediaStreamSource(stream);
            const scriptProcessor = audioContextInputRef.current!.createScriptProcessor(4096, 1, 1);
            scriptProcessor.onaudioprocess = (e) => {
              const inputData = e.inputBuffer.getChannelData(0);
              const int16 = new Int16Array(inputData.length);
              for (let i = 0; i < inputData.length; i++) int16[i] = inputData[i] * 32768;
              const pcmBlob = { data: encode(new Uint8Array(int16.buffer)), mimeType: 'audio/pcm;rate=16000' };
              sessionPromise.then(s => s.sendRealtimeInput({ media: pcmBlob }));
            };
            source.connect(scriptProcessor);
            scriptProcessor.connect(audioContextInputRef.current!.destination);
          },
          onmessage: async (m: LiveServerMessage) => {
            const base64Audio = m.serverContent?.modelTurn?.parts[0]?.inlineData?.data;
            if (base64Audio && audioContextOutputRef.current) {
              const ctx = audioContextOutputRef.current;
              nextStartTimeRef.current = Math.max(nextStartTimeRef.current, ctx.currentTime);
              const audioBuffer = await decodeAudioData(decode(base64Audio), ctx, 24000, 1);
              const source = ctx.createBufferSource();
              source.buffer = audioBuffer;
              source.connect(ctx.destination);
              source.start(nextStartTimeRef.current);
              nextStartTimeRef.current += audioBuffer.duration;
            }
          },
          onclose: () => setIsLiveActive(false)
        },
        config: { responseModalities: [Modality.AUDIO], inputAudioTranscription: {}, outputAudioTranscription: {} }
      });
      liveSessionRef.current = await sessionPromise;
    } catch (err) { alert("Acceso al micrófono denegado."); }
  };

  const stopLiveSession = () => {
    if (liveSessionRef.current) liveSessionRef.current.close();
    setIsLiveActive(false);
  };

  const checkStatus = (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    if(!statusId.trim()) return;
    setIsCheckingStatus(true);
    setStatusResult(null);
    setTimeout(() => {
        setIsCheckingStatus(false);
        if(statusId === 'ADM-2025') setStatusResult('accepted');
        else if(statusId === 'ADM-PEND') setStatusResult('pending');
        else setStatusResult('not_found');
    }, 1500);
  };

  const isDarkPage = ['chat', 'image', 'live'].includes(activeTab);

  const BackToHub = () => (
    <button onClick={() => setActiveTab('solutions')} className="mb-8 flex items-center gap-2 text-[10px] font-black uppercase text-[#566262] hover:text-[#001429] transition-all group">
      <ArrowLeft className="w-4 h-4 group-hover:-translate-x-1 transition-transform" /> Volver al Hub de Soluciones
    </button>
  );

  const resourcesData = [
    { title: "Neurociencia I", cat: "Manual", icon: Brain },
    { title: "Lab de Robótica", cat: "Guía", icon: Zap },
    { title: "Sistemas Éticos", cat: "Ensayo", icon: ShieldCheck },
    { title: "Matemática IA", cat: "Práctica", icon: Calculator },
    { title: "Historia de la IA", cat: "Documento", icon: Library },
    { title: "Algoritmos Genéticos", cat: "Manual", icon: Zap },
  ];

  const facultyData = [
    { name: "Dr. Elara Vega", role: "Directora de IA", img: "https://i.pravatar.cc/150?u=elara", bio: "Experta en redes neuronales profundas con más de 15 años de investigación en Google Brain." },
    { name: "Mtro. Julian Paz", role: "Investigador Neuro", img: "https://i.pravatar.cc/150?u=julian", bio: "Especialista en interfaces cerebro-computador y neuroplasticidad aplicada al aprendizaje." },
    { name: "Dra. Sofia Sol", role: "Ética Aplicada", img: "https://i.pravatar.cc/150?u=sofia", bio: "Consultora internacional en ética algorítmica y gobernanza de sistemas autónomos." }
  ];

  const filteredResources = resourcesData.filter(r => 
    r.title.toLowerCase().includes(resourceSearch.toLowerCase()) || 
    r.cat.toLowerCase().includes(resourceSearch.toLowerCase())
  );

  return (
    <div className={`min-h-screen ${isDarkPage ? 'bg-[#001429]' : 'bg-[#FDFCF8]'} text-[#001429] font-sans transition-colors duration-700 overflow-x-hidden`}>
      
      {/* Desktop Sidebar Nav */}
      <nav className="fixed left-0 top-0 bottom-0 w-20 bg-[#001429] border-r border-white/5 hidden md:flex flex-col items-center py-8 gap-6 z-50 shadow-2xl">
        <div onClick={() => setActiveTab('home')} className="p-3 bg-[#566262] rounded-full shadow-lg cursor-pointer hover:rotate-12 transition-all">
          <Sparkles className="w-5 h-5 text-white" />
        </div>
        <div className="flex flex-col gap-4 mt-8 flex-1 overflow-y-auto scrollbar-hide">
          {[
            { id: 'home', icon: HomeIcon, label: 'Inicio' },
            { id: 'dashboard', icon: LayoutDashboard, label: 'Dash' },
            { id: 'solutions', icon: Grid, label: 'Soluciones' },
            { id: 'methodology', icon: BookOpen, label: 'Método' },
            { id: 'admission', icon: FileText, label: 'Admisión' },
            { id: 'resources', icon: Library, label: 'Recursos' },
            { id: 'faculty', icon: GraduationCap, label: 'Staff' },
            { id: 'map', icon: Compass, label: 'Campus' },
          ].map((tab) => (
            <button 
              key={tab.id}
              onClick={() => setActiveTab(tab.id as Tabs)}
              className={`p-4 rounded-full transition-all flex flex-col items-center gap-1 group ${activeTab === tab.id ? 'bg-white/10 text-[#566262]' : 'text-slate-400 hover:text-white hover:bg-white/5'}`}
            >
              <tab.icon className="w-5 h-5" />
              <span className="text-[9px] uppercase tracking-tighter font-bold opacity-0 group-hover:opacity-100 transition-opacity">{tab.label}</span>
            </button>
          ))}
          <div className="h-px w-8 bg-white/10 my-2 self-center" />
          {[
            { id: 'chat', icon: MessageSquare, label: 'Chat' },
            { id: 'image', icon: ImageIcon, label: 'Imagen' },
            { id: 'live', icon: Mic, label: 'Voz' },
          ].map((tab) => (
            <button 
              key={tab.id}
              onClick={() => setActiveTab(tab.id as Tabs)}
              className={`p-4 rounded-full transition-all flex flex-col items-center gap-1 group ${activeTab === tab.id ? 'bg-white/10 text-[#566262]' : 'text-slate-400 hover:text-white hover:bg-white/5'}`}
            >
              <tab.icon className="w-5 h-5" />
              <span className="text-[9px] uppercase tracking-tighter font-bold opacity-0 group-hover:opacity-100 transition-opacity">{tab.label}</span>
            </button>
          ))}
        </div>
        <button onClick={() => setActiveTab('settings')} className={`p-4 rounded-full transition-all ${activeTab === 'settings' ? 'bg-white/10 text-[#566262]' : 'text-slate-400 hover:text-white'}`}>
          <Settings className="w-5 h-5" />
        </button>
      </nav>

      {/* Mobile Bottom Nav */}
      <nav className="fixed bottom-0 left-0 right-0 bg-[#001429] border-t border-white/5 flex md:hidden justify-around items-center py-4 z-[100] px-4 shadow-[0_-10px_30px_rgba(0,0,0,0.3)]">
        {[
          { id: 'home', icon: HomeIcon },
          { id: 'dashboard', icon: LayoutDashboard },
          { id: 'chat', icon: MessageSquare },
          { id: 'solutions', icon: Grid },
          { id: 'settings', icon: Settings },
        ].map((tab) => (
          <button 
            key={tab.id} 
            onClick={() => setActiveTab(tab.id as Tabs)}
            className={`p-3 rounded-2xl transition-all ${activeTab === tab.id ? 'bg-[#566262] text-white shadow-lg scale-110' : 'text-slate-400'}`}
          >
            <tab.icon className="w-6 h-6" />
          </button>
        ))}
      </nav>

      {/* Main Content Area */}
      <main className={`md:ml-20 min-h-screen flex flex-col items-center ${activeTab === 'home' ? 'pt-0' : 'max-w-7xl mx-auto px-6 py-8 pb-32 md:pb-8'}`}>
        
        {/* Header */}
        {!isDarkPage && (
          <header className="w-full flex justify-between items-center py-6 px-4 md:px-12 sticky top-0 bg-[#FDFCF8]/95 backdrop-blur-xl z-40 border-b border-slate-100">
            <span onClick={() => setActiveTab('home')} className="text-xl md:text-2xl font-black tracking-tighter text-[#001429] flex items-center gap-3 cursor-pointer">
              <div className="w-4 h-4 rounded-full bg-[#001429]" />
              FORMA
            </span>
            <div className="hidden lg:flex items-center gap-10 text-[10px] font-black text-[#001429]/60 uppercase tracking-[0.3em]">
              <button onClick={() => setActiveTab('solutions')} className={`hover:text-[#566262] transition-colors ${activeTab === 'solutions' ? 'text-[#001429] font-black underline underline-offset-8' : ''}`}>Soluciones</button>
              <button onClick={() => setActiveTab('methodology')} className={`hover:text-[#566262] transition-colors ${activeTab === 'methodology' ? 'text-[#001429] font-black underline underline-offset-8' : ''}`}>Método</button>
              <button onClick={() => setActiveTab('admission')} className={`hover:text-[#566262] transition-colors ${activeTab === 'admission' ? 'text-[#001429] font-black underline underline-offset-8' : ''}`}>Admisión</button>
              <button onClick={() => setActiveTab('status')} className={`hover:text-[#566262] transition-colors ${activeTab === 'status' ? 'text-[#001429] font-black underline underline-offset-8' : ''}`}>Estado</button>
            </div>
            <div className="flex items-center gap-4">
              <button onClick={() => setIsNotifOpen(true)} className="p-2 text-[#001429]/40 hover:text-[#001429] relative transition-all">
                <Bell className="w-5 h-5" />
                <div className="absolute top-1 right-1 w-2 h-2 bg-[#566262] rounded-full border-2 border-[#FDFCF8]" />
              </button>
              <div onClick={() => setActiveTab('settings')} className="w-10 h-10 rounded-full bg-slate-200 overflow-hidden cursor-pointer border border-slate-300 hover:ring-2 hover:ring-[#566262] transition-all">
                <img src="https://i.pravatar.cc/150?u=forma" alt="Profile" />
              </div>
            </div>
          </header>
        )}

        {/* --- Home --- */}
        {activeTab === 'home' && (
          <div className="w-full animate-in fade-in">
            <section className="relative px-6 pt-32 pb-40 text-center max-w-6xl mx-auto">
              <div className="inline-flex items-center gap-3 px-6 py-2 rounded-full border border-slate-200 bg-slate-50 text-[#566262] text-[10px] font-black tracking-widest uppercase mb-12">
                <Sparkle className="w-3 h-3" /> Redefiniendo la Educación del Futuro
              </div>
              <h1 className="text-5xl md:text-[140px] font-serif text-[#001429] tracking-tighter leading-[0.75] mb-12">
                Aprender con <br/> 
                <span className="italic font-normal text-[#566262]">intención.</span>
              </h1>
              <p className="text-lg md:text-2xl text-slate-600 max-w-2xl mx-auto leading-relaxed mb-16 px-4">
                FORMA Academy no es solo un colegio, es un ecosistema de aprendizaje potenciado por IA donde el potencial humano no tiene límites.
              </p>
              <div className="flex flex-wrap justify-center gap-6">
                <button onClick={() => setActiveTab('admission')} className="px-8 md:px-12 py-5 md:py-6 bg-[#001429] text-white rounded-full font-bold text-lg md:text-xl hover:shadow-[0_20px_50px_rgba(0,20,41,0.2)] transition-all">Inscripción 2025</button>
                <button onClick={() => setActiveTab('dashboard')} className="px-8 md:px-12 py-5 md:py-6 bg-white border border-slate-200 text-[#001429] rounded-full font-bold text-lg md:text-xl hover:bg-slate-50 transition-all">Panel Alumno</button>
              </div>
            </section>
          </div>
        )}

        {/* --- Dashboard --- */}
        {activeTab === 'dashboard' && (
          <div className="w-full pt-8 pb-40 animate-in fade-in">
            <header className="mb-12 flex flex-col md:flex-row md:justify-between md:items-end gap-6">
                <div>
                  <span className="text-[#566262] font-black tracking-[0.4em] uppercase text-[10px] mb-4 block">Dashboard Estudiantil</span>
                  <h2 className="text-4xl md:text-5xl font-serif text-[#001429]">Resumen Académico de <span className="italic text-[#566262]">Hoy.</span></h2>
                </div>
                <div className="bg-white border border-slate-100 p-6 rounded-3xl shadow-sm text-center md:text-right">
                   <p className="text-[10px] font-black uppercase text-slate-400 mb-1">Hora Local Campus</p>
                   <p className="text-3xl font-serif text-[#566262]">{currentTime.toLocaleTimeString()}</p>
                   <p className="text-[10px] text-slate-400">{currentTime.toLocaleDateString('es-ES', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}</p>
                </div>
            </header>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 md:gap-8 mb-12">
              {[
                { label: "Promedio", val: "9.05", icon: Trophy, color: "text-[#566262] bg-slate-50" },
                { label: "Asistencia", val: "98.2%", icon: Activity, color: "text-blue-600 bg-blue-50" },
                { label: "Créditos", val: "142/240", icon: Library, color: "text-[#001429] bg-slate-100" },
                { label: "Pendientes", val: "2", icon: AlertCircle, color: "text-orange-600 bg-orange-50" }
              ].map((kpi, i) => (
                <div key={i} className="bg-white p-6 md:p-8 rounded-[32px] md:rounded-[40px] border border-slate-100 shadow-lg group hover:shadow-2xl transition-all cursor-pointer">
                  <div className={`w-10 h-10 md:w-12 h-12 rounded-2xl flex items-center justify-center mb-6 ${kpi.color}`}>
                    <kpi.icon className="w-5 h-5 md:w-6 h-6" />
                  </div>
                  <p className="text-[9px] md:text-[10px] font-black uppercase text-slate-400 mb-1">{kpi.label}</p>
                  <h4 className="text-2xl md:text-3xl font-serif text-[#001429]">{kpi.val}</h4>
                </div>
              ))}
            </div>
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
               <div className="lg:col-span-2 bg-white border border-slate-200 rounded-[40px] md:rounded-[50px] p-8 md:p-12 shadow-xl">
                  <h3 className="text-2xl font-serif text-[#001429] mb-8">Cronograma del Día</h3>
                  <div className="space-y-6">
                     {[
                       { time: "08:00 AM", subject: "Cálculo Multivariado", room: "A-201", active: false },
                       { time: "10:30 AM", subject: "Neurociencia Cognitiva", room: "Lab B", active: true },
                       { time: "01:00 PM", subject: "Ética en IA", room: "Auditorio", active: false }
                     ].map((item, i) => (
                        <div key={i} className={`flex items-center gap-6 md:gap-8 p-6 rounded-[32px] transition-all ${item.active ? 'bg-slate-50 border border-slate-100 shadow-inner' : 'bg-slate-50'}`}>
                           <p className="text-sm font-bold text-slate-400 w-16 md:w-20">{item.time}</p>
                           <div className="flex-1">
                              <h4 className="font-serif text-lg md:text-xl text-[#001429]">{item.subject}</h4>
                              <p className="text-[10px] font-black uppercase text-slate-300">{item.room}</p>
                           </div>
                           {item.active && <div className="px-4 py-2 bg-[#001429] text-white text-[9px] font-black uppercase rounded-full animate-pulse shadow-lg shadow-[#001429]/20">En Curso</div>}
                        </div>
                     ))}
                  </div>
               </div>
               <div className="bg-[#001429] p-8 md:p-12 rounded-[40px] md:rounded-[50px] text-white shadow-2xl relative overflow-hidden flex flex-col justify-between">
                  <div>
                     <Sparkle className="w-10 h-10 text-[#566262] mb-8" />
                     <h3 className="text-2xl md:text-3xl font-serif mb-4 leading-none italic">Siguiente Meta: Dominio en Cálculo.</h3>
                     <p className="text-white/40 text-sm leading-relaxed mb-12 italic">Has completado el 85% del módulo. Termina la práctica de hoy para acreditar créditos extra.</p>
                  </div>
                  <button onClick={() => setActiveTab('lesson')} className="w-full py-6 bg-[#566262] rounded-[28px] font-black uppercase text-[10px] tracking-widest hover:bg-slate-500 transition-all shadow-xl active:scale-95">Comenzar Sesión</button>
               </div>
            </div>
          </div>
        )}

        {/* --- Settings & Deployment --- */}
        {activeTab === 'settings' && (
           <div className="w-full flex flex-col pt-16 pb-40 animate-in fade-in max-w-4xl mx-auto">
              <header className="mb-20">
                 <h1 className="text-7xl font-serif text-[#001429] italic mb-4">Ajustes & <span className="text-[#566262]">Configuración.</span></h1>
              </header>
              <div className="space-y-12">
                 {/* Hostinger Deployment Card */}
                 <div className="bg-white border-2 border-[#566262]/20 rounded-[40px] p-12 shadow-2xl overflow-hidden relative group">
                    <div className="absolute top-0 right-0 p-12 opacity-5 group-hover:opacity-10 transition-opacity">
                       <Cloud className="w-48 h-48" />
                    </div>
                    <div className="flex items-center gap-4 mb-8">
                       <div className="p-3 bg-slate-100 text-[#001429] rounded-2xl">
                          <Server className="w-6 h-6" />
                       </div>
                       <h3 className="text-3xl font-serif text-[#001429]">Hostinger Cloud Link</h3>
                    </div>
                    <p className="text-slate-500 italic mb-10 leading-relaxed">Configura el despliegue automático de FORMA ACADEMY en tu alojamiento compartido de Hostinger.</p>
                    
                    <div className="space-y-6 mb-12">
                       <div className="flex gap-4 items-start">
                          <div className="w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center shrink-0 font-bold text-xs">1</div>
                          <p className="text-sm text-slate-600">Sube el archivo <b>.htaccess</b> incluido en el paquete a tu carpeta <b>public_html</b>.</p>
                       </div>
                       <div className="flex gap-4 items-start">
                          <div className="w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center shrink-0 font-bold text-xs">2</div>
                          <p className="text-sm text-slate-600">Copia el contenido del <b>index.html</b> y crea el archivo en el directorio raíz de Hostinger.</p>
                       </div>
                       <div className="flex gap-4 items-start">
                          <div className="w-6 h-6 rounded-full bg-slate-100 flex items-center justify-center shrink-0 font-bold text-xs">3</div>
                          <p className="text-sm text-slate-600">Configura tu <b>API_KEY</b> en el Panel de Control de Hostinger si usas un bundler, o inyéctala directamente en el script.</p>
                       </div>
                    </div>
                    
                    <button onClick={() => alert("Paquete de despliegue generado. Revisa tu carpeta de descargas.")} className="w-full py-6 bg-[#001429] text-white rounded-[32px] font-black uppercase text-[10px] tracking-widest hover:bg-[#001429]/90 transition-all flex items-center justify-center gap-3">
                       <Download className="w-4 h-4" /> Generar Bundle para Hostinger
                    </button>
                 </div>

                 <div className="bg-white border border-slate-200 rounded-[40px] p-12 shadow-xl">
                    <h3 className="text-2xl font-serif text-[#001429] mb-12">Datos Personales</h3>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                       <div className="space-y-2">
                          <label className="text-[10px] font-black uppercase text-slate-400">Nombre de Usuario</label>
                          <input type="text" className="w-full p-4 bg-slate-50 border border-slate-100 rounded-2xl" defaultValue="Juan Rivera" />
                       </div>
                       <div className="space-y-2">
                          <label className="text-[10px] font-black uppercase text-slate-400">ID Estudiantil</label>
                          <input type="text" className="w-full p-4 bg-slate-200 border border-slate-100 rounded-2xl" defaultValue="FORMA-2025-001" disabled />
                       </div>
                    </div>
                    <div className="mt-12 flex justify-end">
                       <button onClick={() => alert("Perfil actualizado.")} className="px-12 py-5 bg-[#001429] text-white rounded-2xl font-black uppercase text-[10px] hover:bg-slate-700 transition-all">Actualizar Perfil</button>
                    </div>
                 </div>
              </div>
           </div>
        )}

        {/* --- Academic Records --- */}
        {activeTab === 'academic-records' && (
           <div className="w-full flex flex-col pt-16 pb-40 animate-in fade-in max-w-5xl">
              <BackToHub />
              <header className="mb-16 flex flex-col md:flex-row justify-between items-end gap-6">
                 <div>
                    <span className="text-[#566262] font-black tracking-[0.4em] uppercase text-[10px] mb-8 block">Control Escolar</span>
                    <h1 className="text-5xl md:text-7xl font-serif text-[#001429]">Registro <span className="italic text-[#566262]">Académico.</span></h1>
                 </div>
                 <button className="flex items-center gap-2 px-6 py-4 border border-slate-200 rounded-2xl text-[10px] font-black uppercase hover:bg-slate-50 transition-all">
                    <Download className="w-4 h-4" /> Exportar PDF
                 </button>
              </header>
              <div className="bg-white border border-slate-200 rounded-[40px] shadow-2xl overflow-hidden overflow-x-auto">
                 <table className="w-full min-w-[600px]">
                    <thead className="bg-slate-50 border-b border-slate-100">
                       <tr className="text-left">
                          <th className="p-8 text-[10px] font-black uppercase text-slate-400">Asignatura</th>
                          <th className="p-8 text-[10px] font-black uppercase text-slate-400 text-center">Créditos</th>
                          <th className="p-8 text-[10px] font-black uppercase text-slate-400 text-center">Nota</th>
                          <th className="p-8 text-[10px] font-black uppercase text-slate-400 text-right">Estatus</th>
                       </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-100">
                       {[
                         { name: "Cálculo Multivariado", credits: 12, grade: "9.2", status: "Acreditado" },
                         { name: "IA Ethics", credits: 8, grade: "9.5", status: "Acreditado" },
                         { name: "Neurociencia II", credits: 10, grade: "8.8", status: "En Curso" },
                         { name: "Robótica Avanzada", credits: 15, grade: "-", status: "Pendiente" }
                       ].map((item, i) => (
                          <tr key={i} className="hover:bg-slate-50 transition-all group">
                             <td className="p-8 font-serif text-2xl text-[#001429] group-hover:text-[#566262] transition-colors">{item.name}</td>
                             <td className="p-8 text-center font-bold text-slate-400">{item.credits}</td>
                             <td className="p-8 text-center font-serif text-3xl text-[#566262] font-bold">{item.grade}</td>
                             <td className="p-8 text-right">
                                <span className={`text-[9px] font-black uppercase px-4 py-2 rounded-full ${
                                  item.status === 'Acreditado' ? 'bg-[#566262]/10 text-[#566262]' : 
                                  item.status === 'En Curso' ? 'bg-[#001429]/10 text-[#001429]' : 'bg-slate-100 text-slate-400'
                                }`}>{item.status}</span>
                             </td>
                          </tr>
                       ))}
                    </tbody>
                 </table>
              </div>
           </div>
        )}

        {/* --- Faculty --- */}
        {activeTab === 'faculty' && (
           <div className="w-full flex flex-col pt-16 pb-40 animate-in fade-in max-w-6xl">
              <header className="mb-24 text-center">
                 <span className="text-[#566262] font-black tracking-[0.4em] uppercase text-[10px] mb-8 block">Mentores FORMA</span>
                 <h1 className="text-6xl md:text-8xl font-serif text-[#001429]">Liderazgo <span className="italic text-[#566262]">Cognitivo.</span></h1>
              </header>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-12">
                 {facultyData.map((mentor, i) => (
                    <div key={i} onClick={() => setSelectedFaculty(mentor)} className="bg-white border border-slate-100 p-8 md:p-12 rounded-[50px] shadow-lg hover:shadow-2xl transition-all text-center group cursor-pointer border-b-4 border-transparent hover:border-[#566262]">
                       <div className="w-32 h-32 md:w-40 h-40 rounded-full mx-auto mb-8 overflow-hidden border-4 border-slate-50 group-hover:border-[#566262] transition-all shadow-lg">
                          <img src={mentor.img} alt={mentor.name} className="w-full h-full object-cover grayscale group-hover:grayscale-0 transition-all" />
                       </div>
                       <h3 className="text-2xl md:text-3xl font-serif text-[#001429] mb-2">{mentor.name}</h3>
                       <p className="text-[10px] font-black uppercase text-[#566262] tracking-widest">{mentor.role}</p>
                       <p className="mt-6 text-sm text-slate-400 italic line-clamp-3 leading-relaxed opacity-0 group-hover:opacity-100 transition-opacity">{mentor.bio}</p>
                    </div>
                 ))}
              </div>

              {/* Faculty Detail Modal */}
              {selectedFaculty && (
                 <div className="fixed inset-0 z-[200] flex items-center justify-center p-6 animate-in fade-in">
                    <div className="absolute inset-0 bg-black/60 backdrop-blur-md" onClick={() => setSelectedFaculty(null)} />
                    <div className="relative bg-white w-full max-w-2xl rounded-[60px] p-12 md:p-16 shadow-3xl overflow-hidden animate-in zoom-in-95">
                       <button onClick={() => setSelectedFaculty(null)} className="absolute top-8 right-8 p-2 hover:bg-slate-50 rounded-full transition-all text-slate-400 hover:text-red-500"><X className="w-6 h-6" /></button>
                       <div className="flex flex-col md:flex-row gap-12 items-center text-center md:text-left">
                          <img src={selectedFaculty.img} className="w-48 h-48 rounded-[40px] object-cover shadow-2xl" />
                          <div>
                             <h3 className="text-5xl font-serif text-[#001429] mb-2">{selectedFaculty.name}</h3>
                             <p className="text-[#566262] font-black uppercase text-[10px] tracking-widest mb-6">{selectedFaculty.role}</p>
                             <p className="text-lg text-slate-500 italic leading-relaxed">{selectedFaculty.bio}</p>
                          </div>
                       </div>
                    </div>
                 </div>
              )}
           </div>
        )}

      </main>

      {/* --- Notification Panel --- */}
      {isNotifOpen && (
         <div className="fixed inset-0 z-[200] flex justify-end animate-in fade-in">
            <div className="absolute inset-0 bg-black/40 backdrop-blur-md" onClick={() => setIsNotifOpen(false)} />
            <div className="relative w-full max-w-md bg-white h-full shadow-3xl p-10 md:p-12 overflow-y-auto animate-in slide-in-from-right-full">
               <div className="flex justify-between items-center mb-12">
                  <h3 className="text-4xl font-serif text-[#001429] italic">Alertas FORMA</h3>
                  <button onClick={() => setIsNotifOpen(false)} className="p-2 hover:bg-slate-50 rounded-full transition-all"><X className="w-6 h-6 text-slate-400" /></button>
               </div>
               <div className="space-y-8">
                  {[
                    { title: "Calificación Publicada", desc: "Neurociencia II: 9.5", time: "10m ago", icon: Trophy, color: "text-[#566262] bg-slate-50" },
                    { title: "Aviso de Pago", desc: "Colegiatura Mayo liquidada", time: "2h ago", icon: CreditCard, color: "text-blue-600 bg-blue-50" },
                    { title: "Evento Mañana", desc: "Conferencia Ética IA", time: "5h ago", icon: Calendar, color: "text-[#001429] bg-slate-100" }
                  ].map((notif, i) => (
                     <div key={i} className="flex gap-6 pb-8 border-b border-slate-50 last:border-0 hover:bg-slate-50 transition-all rounded-2xl p-4 -mx-4 group">
                        <div className={`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 shadow-sm ${notif.color}`}>
                           <notif.icon className="w-6 h-6" />
                        </div>
                        <div className="flex-1">
                           <div className="flex justify-between items-center mb-1">
                              <p className="font-bold text-[#001429] group-hover:text-[#566262] transition-colors">{notif.title}</p>
                              <span className="text-[9px] font-black uppercase text-slate-300">{notif.time}</span>
                           </div>
                           <p className="text-sm text-slate-500 italic">{notif.desc}</p>
                        </div>
                     </div>
                  ))}
               </div>
            </div>
         </div>
      )}

      {/* IA Overlays (Chat, etc.) */}
      {activeTab === 'chat' && (
        <div className="fixed inset-0 pt-16 md:pt-24 md:pl-20 bg-[#001429] flex flex-col items-center z-[150] animate-in fade-in">
           <div className="w-full max-w-5xl px-4 md:px-8 h-full flex flex-col pb-24 md:pb-12">
              <header className="mb-12 flex justify-between items-center">
                 <div className="flex items-center gap-4 md:gap-6 text-white">
                    <button onClick={() => setActiveTab('home')} className="text-white/40 hover:text-white transition-colors p-2"><ArrowLeft className="w-6 h-6" /></button>
                    <div>
                       <h2 className="text-3xl md:text-4xl font-serif italic">Diálogo Estratégico</h2>
                       <p className="text-[#566262] text-[9px] md:text-[10px] font-black uppercase tracking-widest">IA Núcleo • Gemini 3.1 Pro</p>
                    </div>
                 </div>
                 <button onClick={() => setIsSearching(!isSearching)} className={`flex items-center gap-3 px-5 py-2.5 rounded-full border transition-all ${isSearching ? 'bg-[#566262] border-[#566262] text-white shadow-lg shadow-[#566262]/20' : 'bg-white/5 border-white/10 text-white/40 hover:text-white'}`}>
                    <Search className="w-4 h-4" />
                    <span className="text-[9px] md:text-[10px] font-black uppercase tracking-widest hidden sm:inline">Grounding Activo</span>
                 </button>
              </header>
              <div className="flex-1 overflow-y-auto space-y-8 pb-12 pr-2 scrollbar-hide">
                 {messages.length === 0 && (
                   <div className="h-full flex flex-col items-center justify-center text-center space-y-6 opacity-20">
                      <Brain className="w-20 h-20 text-white" />
                      <p className="text-2xl font-serif text-white italic">¿Qué desafío cognitivo resolveremos hoy?</p>
                   </div>
                 )}
                 {messages.map((m, i) => (
                   <div key={i} className={`flex flex-col ${m.role === 'user' ? 'items-end' : 'items-start'}`}>
                      <div className={`max-w-[90%] md:max-w-[80%] p-6 md:p-8 rounded-[32px] md:rounded-[40px] ${m.role === 'user' ? 'bg-[#566262] text-white shadow-2xl shadow-[#566262]/20' : 'bg-white/5 border border-white/10 text-slate-300 shadow-xl'}`}>
                         <p className="text-sm md:text-base leading-relaxed">{m.text}</p>
                         {m.sources && m.sources.length > 0 && (
                            <div className="mt-8 pt-8 border-t border-white/10 space-y-3">
                               <p className="text-[9px] font-black uppercase tracking-widest text-[#566262]">Referencias de búsqueda</p>
                               {m.sources.map((src, si) => (
                                  <a key={si} href={src.web?.uri} target="_blank" className="flex items-center gap-2 text-[10px] text-white/40 hover:text-[#566262] transition-colors">
                                     <LinkIcon className="w-3 h-3" /> {src.web?.title || 'Fuente Externa'}
                                  </a>
                               ))}
                            </div>
                         )}
                      </div>
                   </div>
                 ))}
                 {isTyping && (
                   <div className="flex items-center gap-3 text-[#566262] font-bold animate-pulse text-[10px] tracking-widest uppercase italic">
                     <Loader2 className="w-4 h-4 animate-spin" /> Analizando bases de datos...
                   </div>
                 )}
              </div>
              <form onSubmit={handleSendMessage} className="pt-8 flex gap-3 md:gap-4 sticky bottom-0 bg-[#001429] pb-6">
                 <input 
                   type="text" 
                   value={chatInput} 
                   onChange={(e) => setChatInput(e.target.value)}
                   className="flex-1 bg-white/5 border border-white/10 rounded-full py-5 md:py-6 px-8 md:px-12 text-white outline-none focus:border-[#566262] transition-all text-sm shadow-inner"
                   placeholder="Escribe tu consulta académica..."
                 />
                 <button type="submit" className="w-16 h-16 md:w-20 md:h-20 bg-[#566262] rounded-full flex items-center justify-center text-white shadow-2xl active:scale-90 transition-all shrink-0"><Send className="w-6 h-6 md:w-8 h-8" /></button>
              </form>
           </div>
        </div>
      )}

      {/* Live Voice Overlay */}
      {activeTab === 'live' && (
        <div className="fixed inset-0 pt-24 pl-0 md:pl-20 bg-[#001429] flex flex-col items-center z-[200] animate-in fade-in">
           <div className="w-full max-w-4xl px-8 h-full flex flex-col items-center justify-center relative">
              <button onClick={() => { stopLiveSession(); setActiveTab('home'); }} className="absolute top-12 right-12 text-white/40 hover:text-white p-4"><X className="w-8 h-8" /></button>
              <div className="relative mb-24">
                 <div className={`w-64 h-64 md:w-80 md:h-80 rounded-full flex items-center justify-center transition-all duration-700 ${isLiveActive ? 'bg-[#566262] scale-110 shadow-[0_0_120px_rgba(86,98,98,0.4)]' : 'bg-white/5 border border-white/10'}`}>
                    {isLiveActive ? <Mic className="w-20 h-20 md:w-24 md:h-24 text-white" /> : <MicOff className="w-20 h-20 md:w-24 md:h-24 text-white/10" />}
                 </div>
                 {isLiveActive && (
                    <div className="absolute inset-0 flex items-center justify-center">
                       {[1,2,3].map(i => (
                          <div key={i} className="absolute border-2 border-[#566262] rounded-full animate-ping-slow" style={{ width: `${100 + i*40}%`, height: `${100 + i*40}%`, animationDelay: `${i*0.2}s` }} />
                       ))}
                    </div>
                 )}
              </div>
              <div className="text-center space-y-12">
                 <h2 className="text-6xl md:text-8xl font-serif text-white italic leading-none">Canal Directo.</h2>
                 <p className="text-white/40 max-w-lg mx-auto text-lg md:text-xl leading-relaxed italic">Inicia una conversación fluida con el tutor inteligente de FORMA para resolver dudas complejas al instante.</p>
                 {!isLiveActive ? (
                    <button onClick={startLiveSession} className="px-16 md:px-24 py-6 md:py-8 bg-white rounded-full font-black uppercase tracking-[0.4em] text-[10px] text-[#001429] hover:scale-105 transition-all shadow-2xl">Activar Micrófono</button>
                 ) : (
                    <button onClick={stopLiveSession} className="px-16 md:px-24 py-6 md:py-8 border border-red-500/40 text-red-500 rounded-full font-black uppercase tracking-[0.4em] text-[10px] hover:bg-red-500/5 transition-all">Detener Sesión</button>
                 )}
              </div>
           </div>
        </div>
      )}

      <style>{`
        .font-serif { font-family: 'Instrument Serif', serif; }
        .scrollbar-hide::-webkit-scrollbar { display: none; }
        .scrollbar-hide { -ms-overflow-style: none; scrollbar-width: none; }
        @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
        .animate-in { animation: fade-in 0.8s cubic-bezier(0.16, 1, 0.3, 1); }
        .animate-ping-slow { animation: ping-slow 3s cubic-bezier(0, 0, 0.2, 1) infinite; }
        @keyframes ping-slow { 75%, 100% { transform: scale(2); opacity: 0; } }
        button:active { transform: scale(0.96); }
        .animate-slide-in-right { animation: slide-in-right 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards; }
        @keyframes slide-in-right { from { transform: translateX(100%); } to { transform: translateX(0); } }
        .line-clamp-3 { display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
        .shadow-3xl { shadow-color: rgba(0,0,0,0.4); shadow-offset: {width: 0, height: 20}; shadow-radius: 40; }
      `}</style>
    </div>
  );
};

const rootElement = document.getElementById('root');
if (rootElement) {
  createRoot(rootElement).render(<App />);
}
