// ==========================================
// COMPONENTES COMPARTIDOS (Iconos y Tarjetas)
// ==========================================
window.Icon = ({ name, className = "" }) => {
    const ref = React.useRef(null);
    React.useEffect(() => {
        if (ref.current && window.lucide) {
            const iconName = name.split('-').map(p => p.charAt(0).toUpperCase() + p.slice(1)).join('');
            const iconNode = window.lucide.icons[iconName];
            if (iconNode) {
                const svgElement = window.lucide.createElement(iconNode);
                if (className) svgElement.setAttribute('class', `${svgElement.getAttribute('class') || ''} ${className}`.trim());
                ref.current.innerHTML = '';
                ref.current.appendChild(svgElement);
            }
        }
    }, [name, className]);
    return <span ref={ref} style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}></span>;
};

window.SpotlightCard = ({ children, className = "", onClick, theme, color = "purple" }) => {
    const divRef = React.useRef(null);
    const [pos, setPos] = React.useState({ x: 0, y: 0 });
    const [op, setOp] = React.useState(0);
    const rgb = { purple: '168,85,247', emerald: '16,185,129', blue: '59,130,246', pink: '236,72,153', indigo: '99,102,241', cyan: '6,182,212' }[color] || '168,85,247';
    const borderClass = `hover:border-${color}-500/50`;
    
    return (
        <div ref={divRef} onMouseMove={e=>{const r=divRef.current.getBoundingClientRect(); setPos({x:e.clientX-r.left, y:e.clientY-r.top})}} onMouseEnter={()=>setOp(1)} onMouseLeave={()=>setOp(0)} onClick={onClick} className={`relative overflow-hidden rounded-2xl border transition-all duration-300 ${borderClass} hover:shadow-[0_0_20px_rgba(${rgb},0.15)] ${theme === 'dark' ? 'bg-white/5 border-white/5' : 'bg-white border-slate-200 shadow-sm'} ${className}`}>
            <div className="absolute -inset-px opacity-0 transition-opacity duration-300 pointer-events-none" style={{ opacity: op, background: `radial-gradient(600px circle at ${pos.x}px ${pos.y}px, rgba(${rgb},0.15), transparent 40%)` }} />
            <div className="relative z-10 h-full">{children}</div>
        </div>
    );
};


// ==========================================
// PANTALLA PRINCIPAL (LANDING PAGE)
// ==========================================
window.LandingPage = ({ theme, navigate, isAdminLoggedIn }) => {
    const { useState, useMemo } = React;
    const [searchQuery, setSearchQuery] = useState("");

    // Datos de Herramientas
    const tools = [
        { id: "tool-palette", title: "Generador de Paletas", desc: "Estudio cromático maestro v4.1", icon: <window.Icon name="palette" />, tag: "Pro", color: "purple", url: "/paletadecolor" },
        { id: "tool-font-editor", title: "Font Editor Pro", desc: "Degradados interactivos y exportación SVG.", icon: <window.Icon name="type" />, tag: "Nuevo", color: "blue", url: "/fonteditor" },
        { id: "tool-wcag", title: "Chequeador WCAG", desc: "Auditoría de contraste y legibilidad.", icon: <window.Icon name="eye" />, tag: "Essential", color: "emerald", url: "/wcag" },
        { id: "tool-qr", title: "QR Generator", desc: "Códigos QR personalizados para marca.", icon: <window.Icon name="qr-code" />, tag: "Utility", color: "pink", url: "/qr" },
        { id: "tool-mesh", title: "Mesh Editor", desc: "Gradientes orgánicos y sombras CSS.", icon: <window.Icon name="layers" />, tag: "Creative", color: "indigo", url: "/mesh" },
        { id: "tool-svg", title: "SVG Editor", desc: "Edición vectorial avanzada en navegador.", icon: <window.Icon name="pen-tool" />, tag: "Próximamente", color: "cyan", url: "/svgeditor" }
    ];

    // Datos del Blog (Mock)
    const BLOG_POSTS = [
        { id: 1, title: "Psicología del Color en UI", cat: "Teoría", img: "https://images.unsplash.com/photo-1550684848-fac1c5b4e853?w=800&q=80", excerpt: "Cómo los colores afectan la toma de decisiones del usuario." },
        { id: 2, title: "Sistemas de Diseño Escalables", cat: "Sistemas", img: "https://images.unsplash.com/photo-1558655146-d09347e92766?w=800&q=80", excerpt: "Guía para crear componentes que crecen con tu producto." },
        { id: 3, title: "Accesibilidad es Innovación", cat: "Ética", img: "https://images.unsplash.com/photo-1550751827-4bd374c3f58b?w=800&q=80", excerpt: "Diseñar para todos mejora la experiencia general." }
    ];

    // Paleta de la semana
    const weeklyColors = ['#0F172A', '#334155', '#94A3B8', '#38BDF8', '#818CF8'];

    // Buscador interactivo
    const searchResults = useMemo(() => {
        if (!searchQuery.trim()) return [];
        const q = searchQuery.toLowerCase();
        return tools.filter(t => t.title.toLowerCase().includes(q) || t.desc.toLowerCase().includes(q));
    }, [searchQuery]);

    return (
        <div className="space-y-32 text-inherit animate-fade-in pb-20">
            
            {/* HERO Y BUSCADOR */}
            <section className="text-center pt-10 max-w-5xl mx-auto px-6">
                <div className={`inline-flex items-center gap-2 px-3 py-1 border rounded-full text-[10px] font-bold uppercase mb-8 ${theme==='dark'?'bg-white/5 border-white/10 text-purple-400':'bg-purple-50 border-purple-200 text-purple-600'}`}>
                    <window.Icon name="zap" className="w-3.5 h-3.5" /> Laboratorio Creativo v2.5
                </div>
                <h1 className="text-4xl md:text-7xl font-extrabold mb-6 tracking-tight leading-[0.9] text-inherit">
                    Diseña el Futuro, <br/><span className="text-transparent bg-clip-text bg-gradient-to-r from-purple-500 to-blue-500">Pixel a Pixel.</span>
                </h1>
                <p className={`text-xl max-w-2xl mx-auto mb-12 font-normal leading-relaxed ${theme==='dark'?'text-gray-400':'text-slate-600'}`}>
                    Todas las herramientas que necesitas en un solo lugar. <br className="hidden sm:block"/> Sin descargas, sin configuraciones.
                </p>
                
                <div className="max-w-xl mx-auto relative group z-30 mb-16 w-full text-left">
                    <div className={`relative flex items-center p-1 rounded-2xl border transition-all ${theme==='dark'?'bg-white/5 border-white/5':'bg-white border-slate-200 shadow-xl'} focus-within:ring-2 focus-within:ring-purple-500/50 shadow-2xl shadow-purple-500/10`}>
                        <window.Icon name="search" className="ml-4 w-5 h-5 text-gray-400" />
                        <input type="text" placeholder="Busca herramientas..." className="w-full py-3 px-4 bg-transparent outline-none text-inherit font-medium uppercase tracking-widest text-[10px]" value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} />
                        {searchQuery && (<button onClick={()=>setSearchQuery('')} className="mr-2 text-gray-400 hover:text-white"><window.Icon name="x" className="w-4 h-4"/></button>)}
                    </div>
                    {/* Resultados del Buscador */}
                    {searchQuery && (
                        <div className={`absolute top-full left-0 w-full mt-2 rounded-xl border overflow-hidden shadow-2xl animate-fade-in ${theme==='dark'?'bg-[#16181d] border-white/10':'bg-white border-slate-200'}`}>
                            {searchResults.length > 0 ? (
                                <div className="max-h-60 overflow-y-auto">
                                    {searchResults.map((res, i) => (
                                        <div key={i} onClick={() => { navigate(res.id, res.url); setSearchQuery(''); }} className={`p-4 border-b last:border-0 cursor-pointer flex items-center gap-3 hover:bg-purple-500/10 transition-colors ${theme==='dark'?'border-white/5':'border-slate-100'}`}>
                                            <div className="p-2 rounded-lg bg-blue-500/20 text-blue-500"><window.Icon name="wrench" className="w-4 h-4" /></div>
                                            <div><div className="font-bold text-sm text-inherit">{res.title}</div><div className="text-[10px] opacity-50 uppercase tracking-widest">Herramienta</div></div>
                                        </div>
                                    ))}
                                </div>
                            ) : (<div className="p-4 text-center text-sm opacity-50">No hay resultados.</div>)}
                        </div>
                    )}
                </div>
            </section>

            {/* SECCIÓN ENTERPRISE B2B */}
            <section className="max-w-7xl mx-auto px-6">
                <div className="flex items-center gap-4 mb-10 opacity-30 uppercase font-black">
                    <h2 className="text-[10px] tracking-[0.4em] text-inherit">Enterprise Access</h2>
                    <div className={`h-px flex-1 ${theme==='dark'?'bg-white':'bg-black'}`}></div>
                </div>
                <window.SpotlightCard theme={theme} color="blue" className="bg-gradient-to-br from-[#1e293b] to-[#0f172a] border-blue-500/20 group shadow-2xl">
                    <div className="p-10 md:p-16 flex flex-col md:flex-row items-center gap-10">
                        <div className="w-20 h-20 bg-blue-500/10 rounded-2xl flex items-center justify-center shrink-0 border border-blue-500/20 transition-transform group-hover:scale-110 shadow-lg"><window.Icon name="file-text" className="text-blue-500 w-10 h-10" /></div>
                        <div className="text-center md:text-left">
                            <span className="px-3 py-1 rounded-full bg-blue-600 text-white text-[9px] font-black uppercase mb-4 inline-block tracking-widest">B2B Solution</span>
                            <h3 className="text-4xl font-black mb-3 text-white tracking-tighter uppercase leading-none">Orbity Forms Pro</h3>
                            <p className="text-slate-400 font-light max-w-xl text-lg text-white">Gestión avanzada de activos corporativos para equipos de alto rendimiento.</p>
                        </div>
                        <a href="/orbity-forms/index.html" className="md:ml-auto px-10 py-4 bg-blue-600 text-white font-black rounded-2xl text-[10px] uppercase tracking-widest hover:bg-blue-500 transition-all shadow-xl hover:scale-105 flex items-center justify-center">Acceso Pro</a>
                    </div>
                </window.SpotlightCard>
            </section>

            {/* GRILLA DE HERRAMIENTAS */}
            <section className="max-w-7xl mx-auto px-6 text-inherit">
                <div className="flex items-end justify-between mb-12 uppercase font-black text-inherit">
                    <h2 className="text-3xl tracking-tight text-inherit">Laboratorio</h2>
                    <span className="text-[10px] opacity-40 font-mono text-inherit">06 Tools Available</span>
                </div>
                <div className="grid md:grid-cols-3 gap-8">
                    {tools.map((tool, index) => (
                        <window.SpotlightCard key={index} theme={theme} color={tool.color} onClick={() => tool.tag !== 'Próximamente' && navigate(tool.id, tool.url)} className={tool.tag === 'Próximamente' ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer group'}>
                            <div className="p-8 h-full flex flex-col">
                                <div className="flex justify-between items-start mb-8 text-inherit">
                                    <div className={`p-4 rounded-2xl ${theme==='dark'?'bg-white/5 shadow-inner':'bg-slate-50 border border-slate-100 shadow-inner'}`}>
                                        <div className={`text-${tool.color}-500`}>{tool.icon}</div>
                                    </div>
                                    {tool.tag && <span className={`px-2 py-1 text-[9px] font-black uppercase rounded-full tracking-widest bg-${tool.color}-500/10 text-${tool.color}-500 border border-${tool.color}-500/20`}>{tool.tag}</span>}
                                </div>
                                <h3 className={`text-xl font-black mb-3 transition-colors uppercase tracking-tight group-hover:text-${tool.color}-500`}>{tool.title}</h3>
                                <p className="text-sm opacity-60 leading-relaxed mb-8 font-light text-inherit">{tool.desc}</p>
                                {tool.tag !== 'Próximamente' && (
                                    <div className={`mt-auto pt-6 flex items-center text-[10px] font-black uppercase tracking-[0.2em] opacity-0 -translate-x-2 group-hover:opacity-100 group-hover:translate-x-0 transition-all text-${tool.color}-500`}>Lanzar Tool <window.Icon name="arrow-right" className="w-4 h-4 ml-2" /></div>
                                )}
                            </div>
                        </window.SpotlightCard>
                    ))}
                </div>
            </section>

            {/* PALETA DE LA SEMANA */}
            <section className="max-w-7xl mx-auto px-6">
                <div className="flex justify-between mb-8 items-end">
                    <div>
                        <div className="flex gap-2 mb-2 items-center"><span className="w-2 h-2 rounded-full bg-green-400 animate-pulse"></span><h2 className="text-xs font-black uppercase tracking-widest text-purple-400">Weekly Drop</h2></div>
                        <h3 className="text-2xl font-bold tracking-tight">Paleta de la Semana</h3>
                    </div>
                    {/* BOTÓN ADMIN: Solo visible si iniciaste sesión como Pro */}
                    {isAdminLoggedIn && (
                        <button className="px-4 py-2 bg-yellow-500/20 text-yellow-500 border border-yellow-500/50 rounded-lg text-[10px] uppercase font-black tracking-widest hover:bg-yellow-500 hover:text-black transition-all">
                            ✏️ Editar Paleta
                        </button>
                    )}
                </div>
                <div className="flex h-40 rounded-2xl overflow-hidden shadow-2xl border border-white/5">
                    {weeklyColors.map((hex, i) => (
                        <div key={i} className="flex-1 transition-all hover:flex-[1.5] group relative" style={{backgroundColor: hex}}>
                            <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 bg-black/20 backdrop-blur-sm transition-opacity">
                                <span className="font-mono font-bold text-white tracking-widest uppercase text-xs">{hex}</span>
                            </div>
                        </div>
                    ))}
                </div>
            </section>

            {/* ORBITY JOURNAL (BLOG) */}
            <section className="max-w-7xl mx-auto px-6 text-inherit">
                <div className="flex justify-between items-end mb-12 text-inherit text-left">
                    <div>
                        <h2 className="text-4xl font-black tracking-tighter uppercase text-inherit leading-none">Orbity Journal</h2>
                        <p className="opacity-50 font-light text-lg text-inherit">Inspiración y técnica.</p>
                    </div>
                    <div className="flex gap-4 items-center">
                        {/* BOTÓN ADMIN: Solo visible si iniciaste sesión como Pro */}
                        {isAdminLoggedIn && (
                            <button className="px-4 py-2 bg-yellow-500/20 text-yellow-500 border border-yellow-500/50 rounded-lg text-[10px] uppercase font-black tracking-widest hover:bg-yellow-500 hover:text-black transition-all">
                                ➕ Nuevo Post
                            </button>
                        )}
                        <button className="text-[10px] font-black flex items-center gap-2 hover:text-purple-500 uppercase tracking-[0.2em] text-inherit transition-all">Ver todo <window.Icon name="arrow-right" className="w-4 h-4" /></button>
                    </div>
                </div>
                <div className="grid md:grid-cols-3 gap-8 text-inherit">
                    {BLOG_POSTS.map(post => (
                        <article key={post.id} className="group cursor-pointer text-left transition-all">
                            <div className="aspect-[16/10] rounded-2xl overflow-hidden mb-6 relative border border-white/10 shadow-lg">
                                <img src={post.img} className="w-full h-full object-cover grayscale opacity-60 group-hover:grayscale-0 group-hover:opacity-100 group-hover:scale-105 transition-all duration-700" />
                                <div className="absolute top-4 left-4 text-white">
                                    <span className="px-3 py-1 bg-black/50 backdrop-blur-md rounded-full text-[10px] font-black uppercase tracking-widest border border-white/10 leading-none">{post.cat}</span>
                                </div>
                            </div>
                            <h3 className="text-xl font-black group-hover:text-purple-500 mb-2 tracking-tight uppercase leading-none transition-colors">{post.title}</h3>
                            <p className="text-sm opacity-60 line-clamp-2 leading-relaxed font-light">{post.excerpt}</p>
                        </article>
                    ))}
                </div>
            </section>

        </div>
    );
};