// Extraemos los hooks de React al nivel superior para que todos los componentes los puedan usar
const { useState, useEffect } = React;

// --- ICONOS VECTORIALES ---
const IconCamera = () => <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"/><circle cx="12" cy="13" r="3"/></svg>;
const IconFilm = () => <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="2" width="20" height="20" rx="2.18" ry="2.18"/><line x1="7" y1="2" x2="7" y2="22"/><line x1="17" y1="2" x2="17" y2="22"/><line x1="2" y1="12" x2="22" y2="12"/><line x1="2" y1="7" x2="7" y2="7"/><line x1="2" y1="17" x2="7" y2="17"/><line x1="17" y1="17" x2="22" y2="17"/><line x1="17" y1="7" x2="22" y2="7"/></svg>;
const IconUser = () => <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>;
const IconUsers = () => <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>;
const IconCheck = () => <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>;
const IconFile = () => <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>;
const IconInfo = () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>;
const IconQR = () => <svg width="60" height="60" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><path d="M14 14h.01M17 14h.01M14 17h.01M17 17h.01M20 14h.01M20 17h.01M14 20h.01"/></svg>;
const AvatarNeutro = () => <svg viewBox="0 0 100 100" className="w-full h-full fill-slate-400"><path d="M50 50C63.8 50 75 38.8 75 25C75 11.2 63.8 0 50 0C36.2 0 25 11.2 25 25C25 38.8 36.2 50 50 50ZM50 60C33.3 60 0 68.3 0 85V100H100V85C100 68.3 66.7 60 50 60Z"/></svg>;

// --- DATOS PM² COMPLETOS ---
const actividadesPM2 = [
    { id: 1, title: "Fase de Inicio", icon: "🚀", acts: [ {id: "1a", t: "Reunión de Inicio"}, {id: "1b", t: "Solicitud de Inicio"}, {id: "1c", t: "Caso de Negocio"}, {id: "1d", t: "Acta de Constitución"} ]},
    { id: 2, title: "Planificación", icon: "📋", acts: [ {id: "2a", t: "Manual del Proyecto"}, {id: "2b", t: "Matriz de Roles"}, {id: "2c", t: "Plan de Trabajo"}, {id: "2d", t: "Plan de Externalización"}, {id: "2e", t: "Plan de Aceptación"}, {id: "2f", t: "Plan de Transición"}, {id: "2g", t: "Plan de Implementación"} ]},
    { id: 3, title: "Ejecución", icon: "🎬", acts: [ {id: "3a", t: "Reunión de Lanzamiento"}, {id: "3b", t: "Ejecución del Plan"}, {id: "3c", t: "Garantía de Calidad"}, {id: "3d", t: "Informes de Proyecto"}, {id: "3e", t: "Distribución de Info"} ]},
    { id: 4, title: "Seguimiento", icon: "🔍", acts: [ {id: "4a", t: "Monitorizar Rendimiento"}, {id: "4b", t: "Control de Cronograma"}, {id: "4c", t: "Control de Costes"}, {id: "4d", t: "Gestión de Calidad"}, {id: "4e", t: "Gestión de Riesgos"}, {id: "4f", t: "Gestión de Problemas"}, {id: "4g", t: "Gestión de Cambios"} ]},
    { id: 5, title: "Cierre", icon: "🏁", acts: [ {id: "5a", t: "Revisión Final"}, {id: "5b", t: "Aceptación Final"}, {id: "5c", t: "Transición del Proyecto"}, {id: "5d", t: "Informe Final"}, {id: "5e", t: "Lecciones Aprendidas"} ]}
];

const pm2InfoData = {
    '1a': { title: 'Reunión de Inicio', icon: '🤝', text: 'El primer contacto formal. Se discute la idea inicial y se decide si vale la pena invertir esfuerzo en desarrollar un caso de negocio.' },
    '1b': { title: 'Solicitud de Inicio', icon: '📝', text: 'Define quién es el cliente, qué problema quiere resolver y qué resultados espera. Sin esto, no hay proyecto.' },
    '1c': { title: 'Caso de Negocio', icon: '💼', text: '¿Vale la pena hacer este proyecto? Calculamos si los beneficios superan los costos para convencer a la alta dirección.' },
    '1d': { title: 'Acta de Constitución', icon: '📜', text: '¡Luz verde! El contrato oficial que otorga autoridad al Director de Proyecto, define el alcance a alto nivel, el presupuesto y los grandes riesgos.' },
    '2a': { title: 'Manual del Proyecto', icon: '📖', text: 'Las reglas del juego internas. Define cómo se comunicará el equipo, cómo se documentará y qué herramientas se usarán.' },
    '2b': { title: 'Matriz de Roles', icon: '🎭', text: 'Define quién manda (PO), quién pide (BM), quién provee (SP) y quién dirige (PM). Establece la Gobernanza.' },
    '2c': { title: 'Plan de Trabajo', icon: '📅', text: 'El cronograma detallado. Quién hace qué, cuándo y cuánto costará exactamente.' },
    '2d': { title: 'Plan de Externalización', icon: '🤝', text: 'Si el equipo no puede hacerlo todo, ¿qué proveedores o terceros necesitamos contratar y cómo los gestionaremos?' },
    '2e': { title: 'Plan de Aceptación', icon: '✅', text: 'Define exactamente qué criterios deben cumplirse para que el cliente diga "Esto es lo que pedí, está perfecto".' },
    '2f': { title: 'Plan de Transición', icon: '🔄', text: 'Cómo pasaremos el resultado del proyecto (el nuevo software, el edificio) a las operaciones diarias del negocio.' },
    '2g': { title: 'Plan de Implementación', icon: '🏢', text: 'Preparar a la organización para recibir el cambio. ¿Necesitan formación? ¿Nuevo hardware?' },
    '3a': { title: 'Reunión de Lanzamiento', icon: '🎉', text: 'El famoso Kick-off. Reunimos a todo el equipo que va a trabajar en el proyecto para asegurar que todos entienden el objetivo y el plan.' },
    '3b': { title: 'Ejecución del Plan', icon: '⚙️', text: 'La acción pura y dura. El director coordina al equipo para que construyan los entregables acordados.' },
    '3c': { title: 'Garantía de Calidad', icon: '🛡️', text: 'Asegurarnos de que *estamos haciendo las cosas de la forma correcta*, siguiendo los procesos establecidos.' },
    '3d': { title: 'Informes de Proyecto', icon: '📊', text: 'Redactar el estado del proyecto para mantener a los Stakeholders informados (estado de avance, dinero gastado, etc).' },
    '3e': { title: 'Distribución de Info', icon: '📢', text: 'Asegurar que la información correcta llegue a las personas correctas en el momento preciso.' },
    '4a': { title: 'Monitorizar Rendimiento', icon: '📈', text: 'Vigilar la salud general del proyecto. ¿Vamos según lo planeado en el Caso de Negocio?' },
    '4b': { title: 'Control de Cronograma', icon: '⏱️', text: 'Comparar el avance real con el Plan de Trabajo. ¿Vamos retrasados? ¿Hay que acelerar?' },
    '4c': { title: 'Control de Costes', icon: '💰', text: 'Vigilar la caja fuerte. Asegurarnos de que no estamos gastando más de lo presupuestado (Earned Value).' },
    '4d': { title: 'Gestión de Calidad', icon: '🔍', text: 'Revisar el producto final (entregable) para ver si cumple con los requisitos del Plan de Aceptación.' },
    '4e': { title: 'Gestión de Riesgos', icon: '⚠️', text: 'Vigilar aquellas cosas que *podrían* salir mal y aplicar estrategias antes de que ocurran.' },
    '4f': { title: 'Gestión de Problemas', icon: '🔥', text: 'Resolver los incendios diarios. Cuando un riesgo se hace realidad o surge un imprevisto, hay que solucionarlo.' },
    '4g': { title: 'Gestión de Cambios', icon: '🔄', text: 'Procesar las nuevas ideas o alteraciones del alcance. Si el cliente pide algo nuevo, se evalúa su impacto en tiempo y costo.' },
    '5a': { title: 'Revisión Final', icon: '🧐', text: 'Reunión para confirmar que se entregó todo y discutir si el proyecto fue un éxito general.' },
    '5b': { title: 'Aceptación Final', icon: '🤝', text: 'La firma definitiva del cliente o PO (Dueño de Proyecto) aceptando formalmente el producto.' },
    '5c': { title: 'Transición del Proyecto', icon: '🚚', text: 'Entregar físicamente el resultado al área de operaciones de la empresa y darles el soporte necesario.' },
    '5d': { title: 'Informe Final', icon: '📝', text: 'El documento que resume cómo fue el proyecto: si cumplió tiempo, costo y objetivos.' },
    '5e': { title: 'Lecciones Aprendidas', icon: '🧠', text: 'Documentar qué hicimos muy bien para repetirlo, y qué hicimos mal para no volver a fallar en futuros proyectos.' }
};

const encuestas = {
    cine: [
        { q: "1. ¿Qué Género cinematográfico te define?", options: ["Sci-Fi / Aventura / Acción", "Thriller / Heist / Suspense", "Drama / Cine de Autor"] }, 
        { q: "2. Visualmente, prefieres películas de la era...", options: ["Años 40s-70s (Cine Clásico)", "Años 80s-90s (Blockbusters)", "2000s+ (Modernas)"] }, 
        { q: "3. El Ritmo narrativo perfecto debe ser:", options: ["Frenético, pura adrenalina", "Constante y estructurado", "Lento (Slow burn), gran tensión"] }, 
        { q: "4. ¿Qué Tono disfrutas más?", options: ["Vibrante e inspirador", "Oscuro, crudo y realista", "Satírico o reflexivo"] } 
    ],
    pm2: [
        { q: "El proyecto se retrasa. Según PM², tu primera acción es:", options: ["Ajustar el Work Plan y evaluar", "Pedir horas extra al equipo", "Ignorarlo, ya pasará"] }, 
        { q: "Un inversor exige un cambio crítico de guion:", options: ["Activo la Gestión de Cambios", "Acepto todo para evitar enojos", "Lo rechazo tajantemente"] }, 
        { q: "En la fase de Ejecución, lo más vital es:", options: ["Coordinar y generar entregables", "Gastar el presupuesto rápido", "Escribir la solicitud inicial"] }, 
        { q: "Para evitar desviaciones en el rodaje utilizas:", options: ["El Log de Riesgos y Problemas", "Tu pura intuición de director", "Reuniones de 4 horas diarias"] }, 
        { q: "El proyecto termina. La Fase de Cierre exige:", options: ["Documentar Lecciones Aprendidas", "Apagar cámaras e irse", "Hacer fiesta y olvidar los papeles"] }
    ]
};

const peliculasEducativas = [
    { id: 'm1', titulo: "THE FOUNDER", desc: "El origen de McDonald's. Ideal para entender el Business Case y la Estrategia.", tag: "Inicio" },
    { id: 'm2', titulo: "APOLLO 13", desc: "Gestión de crisis y Control de Problemas extremos en tiempo real.", tag: "Control" },
    { id: 'm3', titulo: "OCEAN'S ELEVEN", desc: "Plan de Trabajo milimétrico y roles súper especializados.", tag: "Planificación" },
    { id: 'm4', titulo: "IMITATION GAME", desc: "Complejidad técnica, Stakeholders difíciles y Gobernanza PM².", tag: "Plan/Ejecución" }
];

// --- HELPERS ---
const parseHash = (h) => { const m = h?.toUpperCase().match(/G(\d)A(\d)R(\d)T(\d)E(\d{2})/); return m ? { valido: true, g: +m[1] } : { valido: false }; };
const getHashColor = (h) => { const p = parseHash(h); return p.valido ? ({1:'bg-yellow-400', 2:'bg-emerald-500', 3:'bg-sky-400'}[p.g] || 'bg-slate-500') : 'bg-slate-500'; };

// --- COMPONENTES REUTILIZABLES ---
const InfoModal = ({ isOpen, data, onClose }) => {
    if (!isOpen || !data) return null;
    return (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-sm fade-in">
            <div className="card-app max-w-sm w-full bg-slate-800 p-8 text-center border-sky-500 shadow-[0_8px_0_0_#0284c7] relative">
                <button onClick={onClose} className="absolute top-4 right-4 text-slate-400 hover:text-white bg-slate-700 w-8 h-8 rounded-full font-bold flex items-center justify-center transition-colors">&times;</button>
                <div className="w-20 h-20 bg-sky-500 rounded-full flex items-center justify-center text-4xl mx-auto mb-4 border-4 border-slate-900 shadow-[0_4px_0_0_#0284c7]">{data.icon}</div>
                <h3 className="text-2xl font-black text-white mb-3 uppercase tracking-wide">{data.title}</h3>
                <p className="text-slate-300 text-base leading-relaxed font-medium mb-6">{data.text}</p>
                <button onClick={onClose} className="btn-app bg-sky-500 border-sky-600 w-full py-4 text-white hover:brightness-110">¡Entendido!</button>
            </div>
        </div>
    );
};

const DossierInput = ({ label, placeholder, value, onChange }) => (
    <div className="mb-5 text-left">
        <label className="block text-sm font-black text-slate-300 uppercase mb-2 ml-2 tracking-wide">{label}</label>
        <textarea 
            rows="2" placeholder={placeholder} value={value || ''} onChange={onChange}
            className="w-full bg-slate-900 border-4 border-slate-700 rounded-2xl px-5 py-4 text-sky-300 font-mono text-base md:text-lg focus:border-sky-500 focus:outline-none custom-scrollbar resize-none transition-colors shadow-inner"
        />
    </div>
);

const SuccessArtifactView = ({ title, desc, children }) => (
    <div className="fade-in card-app-light p-6 md:p-8 relative overflow-hidden text-left">
        <div className="absolute top-0 left-0 w-full h-3 bg-emerald-500"></div>
        <div className="flex items-center gap-4 mb-6 border-b-4 border-slate-100 pb-4">
            <div className="p-4 bg-emerald-100 text-emerald-600 rounded-2xl"><IconFile /></div>
            <div>
                <h4 className="text-2xl font-black uppercase tracking-tight text-slate-800">Artefacto Oficial PM²</h4>
                <p className="text-slate-500 font-bold text-sm">{title} - {desc}</p>
            </div>
        </div>
        {children}
        <div className="mt-8 text-center">
            <span className="text-xs font-black uppercase tracking-widest text-emerald-700 bg-emerald-100 border-2 border-emerald-200 px-6 py-3 rounded-full inline-block shadow-sm">✓ Análisis Validado y Guardado</span>
        </div>
    </div>
);

// --- VISTAS DE FLUJO (Extraídas fuera de la app principal) ---
const StepRegistro = ({ user, setUser, nextStep }) => (
    <div className="bounce-in max-w-md w-full mx-auto card-app p-10 text-center">
        <div className="bg-yellow-400 w-20 h-20 rounded-3xl flex items-center justify-center mx-auto mb-6 shadow-[0_4px_0_0_#ca8a04] rotate-3 text-slate-900"><IconFilm /></div>
        <h1 className="text-4xl font-black text-white mb-2 uppercase">¡Bienvenido!</h1>
        <p className="text-slate-400 mb-8 font-bold">Inicia tu aventura cinematográfica PM²</p>
        <input 
            type="text" placeholder="¿Tu nombre?" 
            value={user.nombre} onChange={(e) => setUser({...user, nombre: e.target.value})}
            className="w-full bg-slate-800 border-4 border-slate-600 rounded-2xl px-5 py-4 text-white text-xl font-bold mb-6 text-center focus:border-yellow-400 focus:outline-none"
        />
        <button onClick={nextStep} disabled={!user.nombre} className="btn-app w-full py-4 text-xl">Siguiente</button>
    </div>
);

const StepAvatar = ({ user, setUser, nextStep }) => {
    const [cfg, setCfg] = useState(user.avatar || { genero: 'M', sombrero: '', gafas: '', gadget: '' });
    const update = (k, v) => setCfg(p => ({...p, [k]: v}));
    const save = () => { setUser({...user, avatar: cfg}); nextStep(); };
    return (
        <div className="fade-in max-w-4xl w-full mx-auto grid md:grid-cols-2 gap-8 items-start">
            <div className="card-app p-8 flex flex-col items-center">
                <h2 className="text-2xl font-black text-white mb-6 uppercase">Tu Personaje</h2>
                <div className="flex gap-4 w-full mb-8">
                    <button onClick={() => update('genero', 'M')} className={`flex-1 py-3 rounded-2xl font-black ${cfg.genero==='M'?'bg-sky-400 text-slate-900':'bg-slate-700 text-slate-300'}`}>Chico</button>
                    <button onClick={() => update('genero', 'F')} className={`flex-1 py-3 rounded-2xl font-black ${cfg.genero==='F'?'bg-pink-400 text-slate-900':'bg-slate-700 text-slate-300'}`}>Chica</button>
                </div>
                <div className="w-48 h-48 bg-slate-700 rounded-full flex items-center justify-center overflow-hidden border-4 border-slate-600 relative">
                    <AvatarNeutro />
                    <div className="absolute top-4 text-4xl">{cfg.sombrero}</div>
                    <div className="absolute top-16 text-3xl">{cfg.gafas}</div>
                    <div className="absolute bottom-6 right-6 text-3xl">{cfg.gadget}</div>
                </div>
            </div>
            <div className="card-app p-8">
                <h3 className="text-xl font-black text-white mb-4 uppercase tracking-widest">Vestuario</h3>
                {[{l:"Cabeza", k:"sombrero", o:['','🧢','🎩','🤠']}, {l:"Cara", k:"gafas", o:['','👓','🕶️','🥽']}, {l:"Gadget", k:"gadget", o:['','🎬','📱','☕']}].map(cat => (
                    <div key={cat.k} className="mb-5">
                        <label className="block text-xs text-slate-400 font-bold mb-2 uppercase">{cat.l}</label>
                        <div className="grid grid-cols-4 gap-2">
                            {cat.o.map(opt => <button key={opt} onClick={() => update(cat.k, opt)} className={`h-12 rounded-xl text-xl ${cfg[cat.k] === opt ? 'bg-yellow-400' : 'bg-slate-700'}`}>{opt || '🚫'}</button>)}
                        </div>
                    </div>
                ))}
                <button onClick={save} className="btn-app w-full py-4 mt-2">Confirmar</button>
            </div>
        </div>
    );
};

const SurveySlider = ({ title, questions, onFinish }) => {
    const [idx, setIdx] = useState(0);
    const [ansList, setAnsList] = useState([]);
    const handle = (ai) => {
        const n = [...ansList, ai];
        if(idx < questions.length - 1) { setAnsList(n); setIdx(idx + 1); } else { onFinish(n); }
    };
    return (
        <div className="max-w-2xl w-full mx-auto card-app p-10 min-h-[450px] flex flex-col fade-in">
            <div className="mb-8 text-center">
                <h2 className="text-3xl font-black text-yellow-400 uppercase">{title}</h2>
                <div className="mt-4 flex gap-2 justify-center">
                    {questions.map((_, i) => <div key={i} className={`h-2.5 w-8 rounded-full ${i <= idx ? 'bg-yellow-400' : 'bg-slate-700'}`}></div>)}
                </div>
            </div>
            <div className="flex-1 flex flex-col justify-center">
                <h3 className="text-2xl font-bold text-white mb-8 text-center">{questions[idx].q}</h3>
                <div className="space-y-4">
                    {questions[idx].options.map((o, i) => (
                        <button key={i} onClick={() => handle(i)} className="w-full text-left p-5 rounded-2xl bg-slate-700 border-b-4 border-slate-900 hover:bg-slate-600 text-white font-bold transition-all">{o}</button>
                    ))}
                </div>
            </div>
        </div>
    );
};

const StepExploradorPM2 = ({ user, setUser, nextStep }) => {
    const [sel, setSel] = useState(user.actividadesSeleccionadas || []);
    const toggle = (id) => setSel(p => p.includes(id) ? p.filter(x => x !== id) : [...p, id]);
    
    const toggleFase = (faseActs) => {
        const allSelected = faseActs.every(a => sel.includes(a.id));
        if(allSelected) {
            setSel(sel.filter(id => !faseActs.find(a => a.id === id)));
        } else {
            const newSel = [...sel];
            faseActs.forEach(a => { if(!newSel.includes(a.id)) newSel.push(a.id); });
            setSel(newSel);
        }
    };

    const save = () => { setUser({...user, actividadesSeleccionadas: sel}); nextStep(); };
    return (
        <div className="fade-in max-w-6xl w-full mx-auto">
            <div className="text-center mb-8"><h2 className="text-4xl font-black text-white uppercase">Mapa de Misiones PM²</h2><p className="font-bold text-slate-400">Selecciona las fases y módulos de la metodología oficial que analizarás.</p></div>
            <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6 mb-10 items-start">
                {actividadesPM2.map(f => (
                    <div key={f.id} className="card-app p-6 bg-slate-800">
                        <div className="flex justify-between items-center mb-4 border-b-2 border-slate-700 pb-3">
                            <h3 className="text-xl font-black text-white flex items-center gap-2"><span>{f.icon}</span> {f.title}</h3>
                            <button onClick={() => toggleFase(f.acts)} className="text-xs uppercase font-bold text-sky-400 bg-slate-700 px-3 py-1 rounded-full">Todo</button>
                        </div>
                        <div className="space-y-2 max-h-[220px] overflow-y-auto custom-scrollbar pr-2">
                            {f.acts.map(a => (
                                <label key={a.id} className={`flex items-center gap-3 p-2.5 rounded-xl cursor-pointer border-2 transition-all ${sel.includes(a.id) ? 'bg-emerald-500/20 border-emerald-500 text-emerald-400' : 'bg-slate-700/30 border-transparent text-slate-300 hover:bg-slate-700'}`}>
                                    <input type="checkbox" checked={sel.includes(a.id)} onChange={() => toggle(a.id)} className="custom-checkbox shrink-0" style={{width:'1.25rem', height:'1.25rem'}} />
                                    <span className="text-xs md:text-sm font-bold leading-tight">{a.t}</span>
                                </label>
                            ))}
                        </div>
                    </div>
                ))}
            </div>
            <button onClick={save} disabled={sel.length === 0} className="btn-app w-full max-w-md mx-auto py-4">Siguiente Misión</button>
        </div>
    );
};

const StepModalidad = ({ user, setUser, nextStep }) => {
    const save = (m) => { setUser({...user, modalidad: m}); nextStep(); };
    return (
        <div className="fade-in max-w-3xl w-full mx-auto text-center">
            <h2 className="text-4xl font-black text-white mb-10 uppercase">¿Cómo vas a jugar?</h2>
            <div className="grid md:grid-cols-2 gap-8">
                <button onClick={() => save('Individual')} className="card-app p-10 group hover:border-sky-400 transition-all">
                    <div className="w-20 h-20 bg-sky-500/20 text-sky-400 rounded-full flex items-center justify-center mx-auto mb-6 group-hover:bg-sky-500 group-hover:text-white"><IconUser/></div>
                    <h3 className="text-2xl font-black text-white mb-2">Individual</h3>
                    <p className="text-slate-400 font-bold">Gestionas tu producción a solas.</p>
                </button>
                <button onClick={() => save('Grupal')} className="card-app p-10 group hover:border-emerald-400 transition-all">
                    <div className="w-20 h-20 bg-emerald-500/20 text-emerald-400 rounded-full flex items-center justify-center mx-auto mb-6 group-hover:bg-emerald-500 group-hover:text-white"><IconUsers/></div>
                    <h3 className="text-2xl font-black text-white mb-2">Grupal</h3>
                    <p className="text-slate-400 font-bold">Forma un equipo de rodaje.</p>
                </button>
            </div>
        </div>
    );
};

const StepHashTicket = ({ user, setUser, nextStep }) => {
    const hash = `G${(user.resCine?.[0]||0)+1}A${(user.resCine?.[1]||0)+1}R${(user.resCine?.[2]||0)+1}T${(user.resCine?.[3]||0)+1}E99`;
    const color = getHashColor(hash);
    const save = () => { setUser({...user, cineHash: hash}); if(user.modalidad === 'Individual') nextStep(true); else nextStep(); };
    return (
        <div className="bounce-in max-w-sm w-full mx-auto text-center">
            <h2 className="text-3xl font-black text-white mb-8 uppercase">Tu Cine-Hash</h2>
            <div className="card-app-light overflow-hidden border-4">
                <div className={`py-4 ${color} text-slate-900 font-black uppercase text-xl`}>ADN Calculado</div>
                <div className="p-10 flex flex-col items-center">
                    <div className="bg-slate-100 p-2 rounded-2xl mb-4 border-2"><IconQR /></div>
                    <h3 className="text-4xl font-black text-slate-800 font-mono">{hash}</h3>
                </div>
                <div className="bg-slate-50 p-4 m-4 mt-0 rounded-2xl flex justify-between items-center border-2">
                    <div className="text-left"><p className="text-xs font-black uppercase text-slate-400">Player</p><p className="font-black text-slate-800">{user.nombre}</p></div>
                    <div className="w-12 h-12 bg-slate-200 rounded-full overflow-hidden"><AvatarNeutro/></div>
                </div>
            </div>
            <button onClick={save} className="btn-app w-full py-4 mt-6">Continuar</button>
        </div>
    );
};

const StepCasting = ({ user, setUser, nextStep }) => {
    const [h, setH] = useState('');
    const [list, setList] = useState(user.equipo || []);
    const add = () => { if(h.length >= 6) { const nl = [...list, h]; setList(nl); setH(''); } };
    const save = () => { setUser({...user, equipo: list}); nextStep(); };
    return (
        <div className="fade-in max-w-md w-full mx-auto card-app p-10 text-center">
            <h2 className="text-3xl font-black text-white mb-4 uppercase">Casting Local</h2>
            <p className="text-slate-400 font-bold mb-8">Escanea o escribe los códigos de tu equipo.</p>
            <div className="flex gap-2 mb-8">
                <input 
                    type="text" placeholder="G_A_R_..." value={h} onChange={(e)=>setH(e.target.value.toUpperCase())}
                    className="flex-1 bg-slate-800 border-4 border-slate-600 rounded-2xl px-4 py-3 text-white font-mono"
                />
                <button onClick={add} className="btn-app px-6">Añadir</button>
            </div>
            <div className="space-y-3 mb-8">
                {list.map((x,i) => <div key={i} className="bg-slate-700 p-3 rounded-xl font-mono text-emerald-400 flex justify-between"><span>{x}</span><span>Miembro</span></div>)}
            </div>
            <button onClick={save} disabled={list.length === 0} className="btn-app w-full py-4">Generar Cartelera</button>
        </div>
    );
};

const StepShortlist = ({ user, setUser, nextStep }) => {
    const save = (m) => { setUser({...user, pelicula: m}); nextStep(); };
    return (
        <div className="fade-in max-w-6xl w-full mx-auto">
            <div className="text-center mb-10"><h2 className="text-5xl font-black text-white uppercase">Cartelera</h2><p className="text-slate-400 font-bold">Selecciona tu Caso de Estudio.</p></div>
            <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-6">
                {peliculasEducativas.map(m => (
                    <div key={m.id} onClick={() => save(m)} className="poster-card cursor-pointer group">
                        <div className="p-6 bg-white h-full flex flex-col text-center">
                            <span className="bg-yellow-400 text-slate-900 px-3 py-1 rounded-full text-[10px] font-black uppercase mb-4 self-center">{m.tag}</span>
                            <h3 className="text-2xl font-black text-slate-800 mb-4 h-16 flex items-center justify-center leading-none">{m.titulo}</h3>
                            <p className="text-sm font-bold text-slate-500 mb-6 flex-1 italic">"{m.desc}"</p>
                            <button className="btn-app w-full text-xs py-3">Seleccionar</button>
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
};

const StepEstudio = ({ user, openInfo }) => {
    const [active, setActive] = useState(null);
    const [comp, setComp] = useState([]);
    const [formData, setFormData] = useState({}); 

    useEffect(() => {
        if (active && !comp.includes(active)) {
            openInfo(active);
        }
    }, [active]);

    const roadmap = user.actividadesSeleccionadas.map(id => {
        let a = null; actividadesPM2.forEach(f => { const found = f.acts.find(x => x.id === id); if(found) a = {...found, icon: f.icon}; });
        return a;
    }).filter(Boolean);

    const updateField = (node, field, val) => {
        setFormData(prev => ({ ...prev, [node]: { ...(prev[node] || {}), [field]: val } }));
    };

    const finish = (id) => { if(!comp.includes(id)) setComp([...comp, id]); setActive(null); };

    const renderCustomModule = () => {
        if(active === '1b') return (
            <div className="space-y-6">
                <DossierInput label="1. Solicitante / Promotor" placeholder="¿Qué personaje o entidad origina la petición oficial en la película?" value={formData['1b']?.['solicitante']} onChange={(e) => updateField('1b', 'solicitante', e.target.value)} />
                <DossierInput label="2. Problema / Necesidad de Negocio" placeholder="Describe el problema central o la crisis que justifica el proyecto." value={formData['1b']?.['necesidad']} onChange={(e) => updateField('1b', 'necesidad', e.target.value)} />
                <DossierInput label="3. Resultados Esperados" placeholder="¿Qué resultados tangibles esperan lograr al finalizar la misión?" value={formData['1b']?.['resultados']} onChange={(e) => updateField('1b', 'resultados', e.target.value)} />
                <button onClick={() => finish('1b')} className="btn-app w-full py-4">Validar Solicitud de Inicio</button>
            </div>
        );
        if(active === '1c') return (
            <div className="space-y-6">
                <DossierInput label="1. Contexto y Urgencia" placeholder="Describe la situación actual. ¿Por qué es urgente actuar ahora?" value={formData['1c']?.['contexto']} onChange={(e) => updateField('1c', 'contexto', e.target.value)} />
                <DossierInput label="2. Soluciones Alternativas" placeholder="¿Qué otras opciones se consideraron antes de elegir este camino?" value={formData['1c']?.['alternativas']} onChange={(e) => updateField('1c', 'alternativas', e.target.value)} />
                <DossierInput label="3. Análisis de Presupuesto e Inversión" placeholder="¿Qué recursos, sacrificios monetarios o humanos exige este proyecto?" value={formData['1c']?.['costes']} onChange={(e) => updateField('1c', 'costes', e.target.value)} />
                <DossierInput label="4. Beneficios Esperados (ROI)" placeholder="¿Qué valor, ventaja estratégica o beneficio final se obtendrá?" value={formData['1c']?.['beneficios']} onChange={(e) => updateField('1c', 'beneficios', e.target.value)} />
                <button onClick={() => finish('1c')} className="btn-app w-full py-4">Validar Caso de Negocio</button>
            </div>
        );
        if(active === '1d') return (
            <div className="space-y-6">
                <DossierInput label="1. Alcance (In-Scope / Out-of-Scope)" placeholder="¿Cuáles son los límites de la misión? ¿Qué se incluye y qué se descarta?" value={formData['1d']?.['alcance']} onChange={(e) => updateField('1d', 'alcance', e.target.value)} />
                <DossierInput label="2. Entregables Principales" placeholder="¿Qué objetos, software, acuerdos o resultados finales deben producirse?" value={formData['1d']?.['entregables']} onChange={(e) => updateField('1d', 'entregables', e.target.value)} />
                <DossierInput label="3. Hitos Clave (Cronograma)" placeholder="Menciona los 3 o 4 eventos temporales clave para el éxito en la trama." value={formData['1d']?.['hitos']} onChange={(e) => updateField('1d', 'hitos', e.target.value)} />
                <DossierInput label="4. Riesgos Críticos Iniciales" placeholder="Identifica las principales amenazas que podrían hacer fracasar todo." value={formData['1d']?.['riesgos']} onChange={(e) => updateField('1d', 'riesgos', e.target.value)} />
                <button onClick={() => finish('1d')} className="btn-app w-full py-4">Firmar Acta de Constitución</button>
            </div>
        );
        if(active === '2b') return (
            <div>
                <div className="grid md:grid-cols-2 gap-6 mb-8">
                    {[
                        {id: 'PO', title: 'Dueño del Proyecto (PO)'}, 
                        {id: 'BM', title: 'Responsable de Negocio (BM)'}, 
                        {id: 'SP', title: 'Proveedor de Soluciones (SP)'}, 
                        {id: 'PM', title: 'Director de Proyecto (PM)'}
                    ].map(r => (
                        <div key={r.id} className="bg-slate-900 p-6 rounded-3xl border-4 border-slate-700">
                            <h4 className="font-black text-yellow-400 mb-4">{r.title}</h4>
                            <div className="space-y-4">
                                <div>
                                    <label className="text-[10px] uppercase font-bold text-slate-500 mb-1 block">Personaje Asignado</label>
                                    <input type="text" placeholder="¿Quién asume este rol en la trama?" value={formData['2b']?.[`${r.id}_char`] || ''} onChange={(e)=>updateField('2b', `${r.id}_char`, e.target.value)} className="w-full bg-slate-800 border-2 border-slate-700 rounded-xl px-4 py-2 text-white font-bold focus:border-yellow-400 focus:outline-none"/>
                                </div>
                                <div>
                                    <label className="text-[10px] uppercase font-bold text-slate-500 mb-1 block">Responsabilidad Oficial PM²</label>
                                    <textarea rows="2" placeholder="Ej: Aprueba el presupuesto, define requisitos técnicos..." value={formData['2b']?.[`${r.id}_resp`] || ''} onChange={(e)=>updateField('2b', `${r.id}_resp`, e.target.value)} className="w-full bg-slate-800 border-2 border-slate-700 rounded-xl px-4 py-2 text-white text-sm focus:border-yellow-400 focus:outline-none custom-scrollbar resize-none"/>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
                <button onClick={() => finish('2b')} className="btn-app w-full py-4">Consolidar Matriz de Roles</button>
            </div>
        );
        
        return (
            <div className="space-y-6">
                <div className="bg-sky-900/30 border-2 border-sky-500 p-4 rounded-xl mb-6">
                    <p className="text-sky-300 text-sm font-bold flex gap-2"><IconInfo/> Modulo de Análisis Universal de PM².</p>
                </div>
                <DossierInput label="1. Contexto en la trama" placeholder="¿En qué momento o escena de la película se aborda esta actividad?" value={formData[active]?.['contexto']} onChange={(e) => updateField(active, 'contexto', e.target.value)} />
                <DossierInput label="2. Aplicación y Decisiones" placeholder="¿Cómo aplica el protagonista (PM) esta herramienta o qué decisión metodológica toma?" value={formData[active]?.['aplicacion']} onChange={(e) => updateField(active, 'aplicacion', e.target.value)} />
                <DossierInput label="3. Impacto en el Proyecto" placeholder="¿Qué consecuencia tuvo hacer (o no hacer) bien este proceso PM²?" value={formData[active]?.['impacto']} onChange={(e) => updateField(active, 'impacto', e.target.value)} />
                <button onClick={() => finish(active)} className="btn-app w-full py-4 bg-emerald-500 border-emerald-600 text-white shadow-[0_4px_0_0_#059669]">Guardar Análisis PM²</button>
            </div>
        );
    };

    return (
        <div className="fade-in w-full max-w-6xl mx-auto pb-10">
            <div className="text-center mb-10">
                <span className="bg-rose-500 px-4 py-1.5 rounded-full text-[10px] font-black uppercase shadow-lg">Estudio de Producción</span>
                <h2 className="text-4xl md:text-5xl font-black text-white mt-4 uppercase">{user.pelicula?.titulo}</h2>
            </div>

            <div className="card-app p-6 md:p-10 mb-10 overflow-x-auto custom-scrollbar flex justify-start items-center gap-6 min-w-max relative" style={{scrollSnapType: 'x mandatory'}}>
                <div className="absolute top-1/2 left-10 right-10 h-3 bg-slate-800 -translate-y-1/2 rounded-full z-0"></div>
                {roadmap.map((n, i) => (
                    <div key={n.id} className="relative z-10 flex flex-col items-center" style={{scrollSnapAlign: 'center'}}>
                        <button 
                            onClick={() => setActive(n.id)}
                            className={`w-16 h-16 md:w-20 md:h-20 rounded-full flex items-center justify-center text-2xl md:text-3xl border-4 transition-all flex-shrink-0
                                ${active === n.id ? 'bg-sky-400 border-white scale-110 md:scale-125' : 
                                comp.includes(n.id) ? 'bg-emerald-400 border-emerald-200' : 'bg-slate-700 border-slate-600'}`}
                        >{comp.includes(n.id) ? <IconCheck/> : n.icon}</button>
                        <p className="mt-4 text-[9px] md:text-[10px] font-black uppercase text-slate-400 w-20 md:w-24 text-center leading-tight">{n.t}</p>
                    </div>
                ))}
            </div>

            {active && (
                <div className="card-app p-6 md:p-10 border-t-8 border-sky-400 bounce-in">
                    <div className="flex justify-between items-start mb-8 md:mb-10">
                        <div className="flex items-center gap-3">
                            <h3 className="text-2xl md:text-3xl font-black uppercase text-white leading-tight">{roadmap.find(n => n.id === active)?.t}</h3>
                            <button onClick={() => openInfo(active)} className="w-8 h-8 rounded-full bg-slate-700 hover:bg-sky-400 transition-colors flex items-center justify-center flex-shrink-0"><IconInfo/></button>
                        </div>
                        <button onClick={() => setActive(null)} className="text-4xl text-slate-500 hover:text-white leading-none">&times;</button>
                    </div>

                    {comp.includes(active) ? (
                        <SuccessArtifactView title="Análisis PM² Validado" desc={roadmap.find(n => n.id === active)?.t}>
                            <div className="space-y-4">
                                <div className="grid gap-3">
                                    {Object.entries(formData[active] || {}).map(([k, v]) => (
                                        <div key={k} className="bg-slate-50 p-4 rounded-xl border-2 border-slate-200">
                                            <span className="text-[10px] uppercase font-black text-slate-400 block mb-1">{k}</span>
                                            <p className="font-bold text-slate-800 text-sm md:text-base">{v || 'Sin datos registrados.'}</p>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </SuccessArtifactView>
                    ) : renderCustomModule()}
                </div>
            )}
        </div>
    );
};

// --- COMPONENTE PRINCIPAL ---
window.UscTfmTool = function({ theme, navigate }) {
    useEffect(() => {
        const styleId = "pm2-cinehash-styles";
        if (!document.getElementById(styleId)) {
            const styleNode = document.createElement("style");
            styleNode.id = styleId;
            styleNode.innerHTML = `
                @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;800;900&family=Bebas+Neue&family=Courier+Prime:wght@400;700&display=swap');
                
                .tfm-container { font-family: 'Nunito', sans-serif; }
                .tfm-container .fade-in { animation: tfmFadeIn 0.4s ease-out forwards; }
                .tfm-container .slide-in-right { animation: tfmSlideInRight 0.3s ease-out forwards; }
                .tfm-container .bounce-in { animation: tfmBounceIn 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55) forwards; }
                
                @keyframes tfmFadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
                @keyframes tfmSlideInRight { from { opacity: 0; transform: translateX(30px); } to { opacity: 1; transform: translateX(0); } }
                @keyframes tfmBounceIn { 0% { transform: scale(0.5); opacity: 0; } 100% { transform: scale(1); opacity: 1; } }

                .tfm-container .card-app { background: #1e293b; border-radius: 28px; border: 4px solid #334155; box-shadow: 0 8px 0 0 #0f172a; }
                .tfm-container .card-app-light { background: #ffffff; border-radius: 28px; border: 4px solid #cbd5e1; box-shadow: 0 8px 0 0 #94a3b8; color: #0f172a; }
                .tfm-container .btn-app {
                    background: #facc15; color: #0f172a; font-weight: 900; border-radius: 18px; border: 3px solid #ca8a04; border-bottom-width: 6px; transition: all 0.1s; text-transform: uppercase; letter-spacing: 0.05em; display: flex; align-items: center; justify-content: center; gap: 0.5rem; box-shadow: 0 4px 0 0 rgba(0,0,0,0.1);
                }
                .tfm-container .btn-app:hover:not(:disabled) { filter: brightness(1.05); transform: translateY(-1px); }
                .tfm-container .btn-app:active:not(:disabled) { transform: translateY(4px); border-bottom-width: 2px; box-shadow: none; }
                .tfm-container .btn-app:disabled { opacity: 0.5; cursor: not-allowed; }
                .tfm-container .custom-scrollbar::-webkit-scrollbar { width: 8px; height: 10px; }
                .tfm-container .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
                .tfm-container .custom-scrollbar::-webkit-scrollbar-thumb { background: #475569; border-radius: 10px; border: 2px solid #1e293b; }
                .tfm-container .custom-checkbox { appearance: none; width: 1.75rem; height: 1.75rem; border: 3px solid #475569; border-radius: 0.5rem; background-color: #1e293b; display: inline-block; position: relative; cursor: pointer; transition: all 0.2s; }
                .tfm-container .custom-checkbox:checked { background-color: #10b981; border-color: #059669; }
                .tfm-container .custom-checkbox:checked::after { content: ''; position: absolute; left: 8px; top: 3px; width: 6px; height: 14px; border: solid #fff; border-width: 0 3px 3px 0; transform: rotate(45deg); }
                .tfm-container .poster-card { background: #fff; border-radius: 20px; overflow: hidden; border: 4px solid #cbd5e1; box-shadow: 0 10px 0 0 #94a3b8; transition: transform 0.2s; }
                .tfm-container .poster-card:hover { transform: translateY(-5px); }
            `;
            document.head.appendChild(styleNode);
        }
    }, []);

    const [step, setStep] = useState(0);
    const [info, setInfo] = useState(null);
    const [user, setUser] = useState({
        nombre: '', avatar: null, modalidad: 'Individual',
        actividadesSeleccionadas: [], equipo: [], pelicula: null
    });

    const next = (skip = false) => {
        if(skip) setStep(8); else setStep(s => s + 1);
        window.scrollTo(0,0);
    };

    return (
        <div className="tfm-container w-full bg-[#0f172a] text-[#f8fafc] min-h-screen py-10 px-4 md:px-6 rounded-3xl border-4 border-slate-800/50 shadow-2xl overflow-hidden relative">
            <InfoModal isOpen={!!info} data={info} onClose={() => setInfo(null)} />
            
            {/* Header de Progreso Integrado (Sticky) */}
            <div className="sticky top-0 z-50 w-full h-16 bg-slate-900 rounded-2xl border-b-4 border-slate-800 flex items-center justify-between px-4 md:px-8 mb-10 shadow-lg">
                <div className="flex items-center gap-2 md:gap-3 font-black text-lg md:text-xl text-white uppercase tracking-tighter">
                    <IconCamera/>
                    <span className="text-yellow-400 hidden sm:inline">Cine-Hash</span>
                </div>
                <div className="flex gap-1 md:gap-2">
                    {[0,1,2,3,4,5,6,7,8,9].map(i => (
                        <div key={i} className={`h-2 md:h-2.5 w-4 md:w-6 rounded-full transition-all ${i===step?'bg-yellow-400 w-8 md:w-10':'bg-slate-700'}`}></div>
                    ))}
                </div>
            </div>

            {/* Router Interno usando los subcomponentes extraídos */}
            {step === 0 && <StepRegistro user={user} setUser={setUser} nextStep={() => next()} />}
            {step === 1 && <StepAvatar user={user} setUser={setUser} nextStep={() => next()} />}
            {step === 2 && <SurveySlider title="Perfil Cine" questions={encuestas.cine} onFinish={(a) => {setUser({...user, resCine: a}); next();}} />}
            {step === 3 && <StepExploradorPM2 user={user} setUser={setUser} nextStep={() => next()} />}
            {step === 4 && <StepModalidad user={user} setUser={setUser} nextStep={() => next()} />}
            {step === 5 && <SurveySlider title="Roles PM²" questions={encuestas.pm2} onFinish={(a) => {setUser({...user, resPM2: a}); next();}} />}
            {step === 6 && <StepHashTicket user={user} setUser={setUser} nextStep={(s) => next(s)} />}
            {step === 7 && <StepCasting user={user} setUser={setUser} nextStep={() => next()} />}
            {step === 8 && <StepShortlist user={user} setUser={setUser} nextStep={() => next()} />}
            {step === 9 && <StepEstudio user={user} openInfo={(id) => setInfo(pm2InfoData[id] || {title: 'Módulo PM²', icon: '💡', text: 'Análisis metodológico de la guía PM².'})} />}
        </div>
    );
};
