window.FontTool = ({ theme, navigate }) => {
    const { useState, useEffect, useRef } = React;

    const [text, setText] = useState("Orbitylab");
    const [font, setFont] = useState("Inter");
    const [weight, setWeight] = useState("900");
    const [style, setStyle] = useState("fill");
    const [gradType, setGradType] = useState("linear");
    
    // Conexión con el Ecosistema: Buscar paleta guardada
    const [gradientStops, setGradientStops] = useState(() => {
        const savedPalette = localStorage.getItem('orbity_active_palette');
        if (savedPalette) {
            try {
                const imported = JSON.parse(savedPalette);
                if (imported && imported.length >= 2) {
                    return imported.slice(0, 4).map((c, i) => ({
                        id: i + 1, color: c, pos: Math.round((i / (Math.min(imported.length, 4) - 1)) * 100)
                    }));
                }
            } catch (e) { console.error("Error leyendo paleta:", e); }
        }
        return [{ id: 1, color: '#6D2D52', pos: 0 }, { id: 2, color: '#11FFC9', pos: 100 }];
    });
    const [activeStopId, setActiveStopId] = useState(1);
    const [nodePos, setNodePos] = useState({ start: {x: 20, y: 50}, end: {x: 80, y: 50} });
    
    const svgContainerRef = useRef(null);
    const exportTargetRef = useRef(null);

    // Cargar fuente de Google dinámicamente
    useEffect(() => {
        const linkId = `font-${font.replace(/\s+/g, '')}`;
        if (!document.getElementById(linkId)) {
            const link = document.createElement('link'); 
            link.id = linkId;
            link.href = `https://fonts.googleapis.com/css2?family=${font.replace(/ /g, '+')}:wght@400;900&display=swap`;
            link.rel = 'stylesheet'; 
            document.head.appendChild(link);
        }
    }, [font]);

    // Renderizar gradiente SVG en React
    const renderGradient = () => {
        const stops = [...gradientStops].sort((a,b) => a.pos - b.pos).map(s => 
            <stop key={s.id} offset={`${s.pos}%`} stopColor={s.color} />
        );
        if (gradType === 'linear') {
            return <linearGradient id="orbityGrad" x1={`${nodePos.start.x}%`} y1={`${nodePos.start.y}%`} x2={`${nodePos.end.x}%`} y2={`${nodePos.end.y}%`}>{stops}</linearGradient>;
        } else {
            const dx = nodePos.end.x - nodePos.start.x; 
            const dy = nodePos.end.y - nodePos.start.y;
            const r = Math.sqrt(dx*dx + dy*dy);
            return <radialGradient id="orbityGrad" cx={`${nodePos.start.x}%`} cy={`${nodePos.start.y}%`} r={`${r}%`}>{stops}</radialGradient>;
        }
    };

    // Motor de arrastre (Soporte Mouse y Táctil)
    const handleNodeDrag = (e, nodeType) => {
        e.preventDefault();
        const container = svgContainerRef.current.getBoundingClientRect();
        
        const onMove = (moveEvent) => {
            const clientX = moveEvent.touches ? moveEvent.touches[0].clientX : moveEvent.clientX;
            const clientY = moveEvent.touches ? moveEvent.touches[0].clientY : moveEvent.clientY;
            let x = ((clientX - container.left) / container.width) * 100;
            let y = ((clientY - container.top) / container.height) * 100;
            // Limitar dentro del contenedor
            x = Math.max(0, Math.min(100, x));
            y = Math.max(0, Math.min(100, y));
            setNodePos(prev => ({ ...prev, [nodeType]: { x, y } }));
        };
        
        const onUp = () => {
            document.removeEventListener('mousemove', onMove); 
            document.removeEventListener('mouseup', onUp);
            document.removeEventListener('touchmove', onMove); 
            document.removeEventListener('touchend', onUp);
        };
        
        document.addEventListener('mousemove', onMove); 
        document.addEventListener('mouseup', onUp);
        document.addEventListener('touchmove', onMove, {passive: false}); 
        document.addEventListener('touchend', onUp);
    };

    // Funciones de Exportación
    const downloadPNG = async () => {
        const target = exportTargetRef.current;
        const uiElements = target.querySelectorAll('.ui-element');
        uiElements.forEach(el => el.style.display = 'none');
        
        try {
            const canvas = await html2canvas(target, { backgroundColor: null, scale: 3, useCORS: true });
            const link = document.createElement('a'); 
            link.download = `orbity-font-${Date.now()}.png`; 
            link.href = canvas.toDataURL('image/png'); 
            link.click();
        } catch (err) { alert("Error exportando imagen."); } 
        finally { uiElements.forEach(el => el.style.display = ''); }
    };

    const downloadSVG = () => {
        const liveSvg = document.getElementById('orbityExportSVG').outerHTML;
        const fontImport = `<style>@import url('https://fonts.googleapis.com/css2?family=${font.replace(/ /g, '+')}:wght@${weight}&amp;display=swap');</style>`;
        const finalSvg = liveSvg.replace('<defs>', `<defs>${fontImport}`);
        const blob = new Blob([finalSvg], {type: 'image/svg+xml;charset=utf-8'});
        const link = document.createElement('a'); 
        link.href = URL.createObjectURL(blob); 
        link.download = `orbity-font-${Date.now()}.svg`; 
        link.click();
    };

    return (
        <div className="max-w-7xl mx-auto px-6 text-inherit animate-fade-in text-left">
            {/* Botón Volver */}
            <button onClick={() => navigate('home', '/')} className="mb-10 flex items-center gap-2 text-[10px] font-black opacity-50 hover:opacity-100 uppercase tracking-widest transition-all">
                <window.Icon name="arrow-left" className="w-4 h-4" /> Dashboard
            </button>

            <div className="mb-12">
                <h2 className="text-4xl md:text-5xl font-extrabold tracking-tight mb-4 leading-none uppercase">Font Editor Pro</h2>
                <p className="opacity-60 max-w-2xl font-light text-xl leading-relaxed">Aplica degradados complejos, interactivos y radiales a tipografías con exportación vectorial pura.</p>
            </div>

            <div className="grid lg:grid-cols-3 gap-8">
                {/* Panel de Controles */}
                <div className={`p-8 rounded-3xl border h-fit space-y-8 ${theme === 'dark' ? 'bg-white/5 border-white/10 text-white shadow-2xl' : 'bg-white border-slate-200 shadow-sm'}`}>
                    
                    <div className="space-y-4">
                        <div>
                            <label className="text-[10px] font-black uppercase block mb-2 opacity-50 tracking-widest">Texto</label>
                            <input type="text" value={text} onChange={e=>setText(e.target.value)} className={`w-full border rounded-xl px-4 py-3 text-sm outline-none font-medium transition-colors ${theme === 'dark' ? 'bg-[#16181d] border-white/10 focus:border-blue-500' : 'bg-slate-50 border-slate-200 focus:border-blue-500'}`}/>
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                            <div>
                                <label className="text-[10px] font-black uppercase block mb-2 opacity-50 tracking-widest">Fuente</label>
                                <select value={font} onChange={e=>setFont(e.target.value)} className={`w-full border rounded-xl px-3 py-3 text-xs font-bold uppercase cursor-pointer ${theme === 'dark' ? 'bg-[#16181d] border-white/10' : 'bg-slate-50 border-slate-200'}`}>
                                    {['Inter', 'Montserrat', 'Oswald', 'Poppins', 'Playfair Display', 'Righteous', 'Syne'].map(f=><option key={f} value={f}>{f}</option>)}
                                </select>
                            </div>
                            <div>
                                <label className="text-[10px] font-black uppercase block mb-2 opacity-50 tracking-widest">Grosor</label>
                                <select value={weight} onChange={e=>setWeight(e.target.value)} className={`w-full border rounded-xl px-3 py-3 text-xs font-bold uppercase cursor-pointer ${theme === 'dark' ? 'bg-[#16181d] border-white/10' : 'bg-slate-50 border-slate-200'}`}>
                                    <option value="400">Regular</option><option value="900">Black</option>
                                </select>
                            </div>
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                            <div>
                                <label className="text-[10px] font-black uppercase block mb-2 opacity-50 tracking-widest">Estilo</label>
                                <select value={style} onChange={e=>setStyle(e.target.value)} className={`w-full border rounded-xl px-3 py-3 text-xs font-bold uppercase cursor-pointer ${theme === 'dark' ? 'bg-[#16181d] border-white/10' : 'bg-slate-50 border-slate-200'}`}>
                                    <option value="fill">Sólido</option><option value="stroke">Contorno</option>
                                </select>
                            </div>
                            <div>
                                <label className="text-[10px] font-black uppercase block mb-2 opacity-50 tracking-widest">Dirección</label>
                                <select value={gradType} onChange={e=>setGradType(e.target.value)} className={`w-full border rounded-xl px-3 py-3 text-xs font-bold uppercase cursor-pointer ${theme === 'dark' ? 'bg-[#16181d] border-white/10' : 'bg-slate-50 border-slate-200'}`}>
                                    <option value="linear">Lineal</option><option value="radial">Radial</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    {/* Editor de Puntos de Color */}
                    <div className={`p-5 rounded-2xl border ${theme === 'dark' ? 'bg-[#0a0c10]/50 border-white/5' : 'bg-slate-50 border-slate-200'}`}>
                        <div className="flex justify-between items-center mb-4">
                            <label className="text-[10px] font-black uppercase opacity-50 tracking-widest">Puntos de Color</label>
                            <button onClick={() => setGradientStops([...gradientStops, {id: Date.now(), color: '#ffffff', pos: 50}])} className="text-[10px] font-bold uppercase text-blue-500 hover:text-blue-400">+ Añadir</button>
                        </div>
                        
                        <div className="space-y-3">
                            {gradientStops.map((stop, i) => (
                                <div key={stop.id} className="flex items-center gap-3">
                                    <div className="relative w-8 h-8 rounded-lg overflow-hidden shrink-0 border border-white/20 shadow-sm">
                                        <input type="color" value={stop.color.substring(0,7)} onChange={e=>{const n=[...gradientStops]; n[i].color=e.target.value; setGradientStops(n);}} className="absolute -top-2 -left-2 w-16 h-16 cursor-pointer" />
                                    </div>
                                    <input type="text" value={stop.color} onChange={e=>{const n=[...gradientStops]; n[i].color=e.target.value.toUpperCase(); setGradientStops(n);}} className={`w-24 font-mono text-xs px-2 py-2 rounded-lg border outline-none ${theme === 'dark' ? 'bg-[#16181d] border-white/10' : 'bg-white border-slate-200'}`} />
                                    <input type="range" min="0" max="100" value={stop.pos} onChange={e=>{const n=[...gradientStops]; n[i].pos=Number(e.target.value); setGradientStops(n);}} className="flex-1 cursor-pointer accent-blue-500" />
                                    {gradientStops.length > 2 && (
                                        <button onClick={() => setGradientStops(gradientStops.filter(s => s.id !== stop.id))} className="text-red-500 opacity-50 hover:opacity-100"><window.Icon name="x" className="w-4 h-4" /></button>
                                    )}
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* Botones de Exportación */}
                    <div className="grid grid-cols-2 gap-4 pt-4 border-t border-white/10">
                        <button onClick={downloadPNG} className="py-4 bg-blue-600 hover:bg-blue-500 text-white font-black rounded-xl text-[10px] uppercase tracking-widest shadow-xl transition-all hover:-translate-y-1">PNG Transparente</button>
                        <button onClick={downloadSVG} className="py-4 border border-blue-500/50 hover:bg-blue-500/10 text-blue-500 font-black rounded-xl text-[10px] uppercase tracking-widest shadow-xl transition-all hover:-translate-y-1">Vector SVG</button>
                    </div>
                </div>
                
                {/* Lienzo Interactivo */}
                <div className="lg:col-span-2 flex items-center justify-center p-8 rounded-3xl border shadow-2xl relative overflow-hidden" style={{ backgroundColor: theme === 'dark' ? '#08090d' : '#f8fafc', borderColor: theme === 'dark' ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.1)' }}>
                    {/* Grid background base */}
                    <div className="absolute inset-0 opacity-20" style={{ backgroundImage: 'radial-gradient(rgba(139, 92, 246, 0.4) 1px, transparent 1px)', backgroundSize: '20px 20px' }}></div>
                    
                    <div ref={exportTargetRef} className="relative w-full aspect-[2/1] max-w-4xl flex items-center justify-center">
                        <div ref={svgContainerRef} className="absolute inset-0">
                            {/* SVG de Exportación (Lo que se descarga) */}
                            <svg className="w-full h-full overflow-visible" viewBox="0 0 800 400" id="orbityExportSVG">
                                <defs>{renderGradient()}</defs>
                                <text x="50%" y="50%" textAnchor="middle" dominantBaseline="middle" fontSize="140px" fontFamily={`'${font}', sans-serif`} fontWeight={weight} fill={style === 'fill' ? 'url(#orbityGrad)' : 'transparent'} stroke={style === 'stroke' ? 'url(#orbityGrad)' : 'none'} strokeWidth={style === 'stroke' ? '4px' : '0'} style={{ filter: theme === 'dark' ? 'drop-shadow(0px 10px 20px rgba(0,0,0,0.5))' : 'drop-shadow(0px 10px 20px rgba(0,0,0,0.1))' }}>
                                    {text}
                                </text>
                            </svg>
                            
                            {/* Nodos de Interfaz Interactiva (Se ocultan al exportar a PNG) */}
                            <svg className="absolute inset-0 w-full h-full pointer-events-none opacity-50 ui-element">
                                <line x1={`${nodePos.start.x}%`} y1={`${nodePos.start.y}%`} x2={`${nodePos.end.x}%`} y2={`${nodePos.end.y}%`} stroke="#3B82F6" strokeWidth="2" strokeDasharray="5,5"/>
                                {gradType === 'radial' && <circle cx={`${nodePos.start.x}%`} cy={`${nodePos.start.y}%`} r={`${Math.sqrt(Math.pow(nodePos.end.x-nodePos.start.x,2)+Math.pow(nodePos.end.y-nodePos.start.y,2))}%`} fill="none" stroke="#3B82F6" strokeWidth="2" strokeDasharray="5,5"/>}
                            </svg>
                            <div className="absolute w-5 h-5 bg-white border-2 border-blue-500 rounded-full cursor-grab shadow-lg z-10 hover:scale-125 transition-transform ui-element" style={{ left: `${nodePos.start.x}%`, top: `${nodePos.start.y}%`, transform: 'translate(-50%, -50%)' }} onMouseDown={e=>handleNodeDrag(e, 'start')} onTouchStart={e=>handleNodeDrag(e, 'start')}></div>
                            <div className="absolute w-5 h-5 bg-white border-2 border-blue-500 rounded-full cursor-grab shadow-lg z-10 hover:scale-125 transition-transform ui-element" style={{ left: `${nodePos.end.x}%`, top: `${nodePos.end.y}%`, transform: 'translate(-50%, -50%)' }} onMouseDown={e=>handleNodeDrag(e, 'end')} onTouchStart={e=>handleNodeDrag(e, 'end')}></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};