const { useState, useEffect, useRef } = React;

// Dynamically detect server origin to support both localhost and Cloud Run production deployments
const API_BASE = "/api";

function App() {
    const [token, setToken] = useState(localStorage.getItem("token"));
    const [user, setUser] = useState(null);

    useEffect(() => {
        if (token) {
            axios.get(`${API_BASE}/users/me`, {
                headers: { Authorization: `Bearer ${token}` }
            })
                .then(res => setUser(res.data))
                .catch(() => {
                    setToken(null);
                    localStorage.removeItem("token");
                });
        }
    }, [token]);

    const handleLogin = (newToken) => {
        setToken(newToken);
        localStorage.setItem("token", newToken);
    };

    const handleLogout = () => {
        setToken(null);
        setUser(null);
        localStorage.removeItem("token");
    };

    return (
        <div className="flex flex-col min-h-screen bg-relac-light">
            <header className="bg-relac-dark text-white shadow-md z-10">
                <div className="container mx-auto px-4 py-3 flex justify-between items-center">
                    <div className="flex items-center space-x-3">
                        <div className="w-10 h-10 bg-relac-green rounded-full flex items-center justify-center text-white font-bold text-xl">
                            R
                        </div>
                        <h1 className="text-xl font-semibold tracking-wide">
                            ReLAC <span className="text-relac-green">AI-Assistant</span>
                        </h1>
                    </div>
                    {user && (
                        <div className="flex items-center space-x-4">
                            <span className="text-sm opacity-80">{user.email}</span>
                            <button
                                onClick={handleLogout}
                                className="text-sm border border-white/30 hover:bg-white/10 px-3 py-1.5 rounded transition"
                            >
                                Salir
                            </button>
                        </div>
                    )}
                </div>
            </header>

            <main className="relative flex-1 container mx-auto p-4 md:p-6 lg:p-8 flex flex-col items-center justify-center overflow-hidden">
                <div className="z-10 w-full max-w-4xl flex justify-center">
                    {!token ? (
                        <AuthForm onLogin={handleLogin} />
                    ) : (
                        <ChatInterface token={token} />
                    )}
                </div>
            </main>
        </div>
    );
}

function AuthForm({ onLogin }) {
    const [isLogin, setIsLogin] = useState(true);
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [error, setError] = useState("");
    const [msg, setMsg] = useState("");
    const [loading, setLoading] = useState(false);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setError("");
        setMsg("");
        setLoading(true);

        try {
            if (isLogin) {
                const params = new URLSearchParams();
                params.append('username', email);
                params.append('password', password);

                const res = await axios.post(`${API_BASE}/auth/login`, params);
                onLogin(res.data.access_token);
            } else {
                const res = await axios.post(`${API_BASE}/auth/register`, { email, password });
                setMsg("Registro exitoso. Se ha enviado un enlace de verificación a tu correo. Por favor valida tu cuenta antes de ingresar.");
                setIsLogin(true);
            }
        } catch (err) {
            setError(err.response?.data?.detail || "Ha ocurrido un error");
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="w-full max-w-md glass-panel rounded-xl shadow-lg border border-gray-100 p-8 transform transition-all">
            <h2 className="text-2xl font-bold text-relac-dark mb-6 text-center">
                {isLogin ? "Iniciar Sesión" : "Crear Cuenta"}
            </h2>

            {error && <div className="bg-red-50 text-relac-red p-3 rounded mb-4 text-sm border border-red-100">{error}</div>}
            {msg && <div className="bg-green-50 text-relac-green p-3 rounded mb-4 text-sm border border-green-100">{msg}</div>}

            <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Correo Electrónico</label>
                    <input
                        type="email"
                        value={email}
                        onChange={e => setEmail(e.target.value)}
                        className="w-full px-4 py-2 border border-gray-300 rounded focus:ring-2 focus:ring-relac-green focus:border-transparent outline-none transition"
                        placeholder="ejemplo@correo.com"
                        required
                    />
                </div>
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">Contraseña</label>
                    <input
                        type="password"
                        value={password}
                        onChange={e => setPassword(e.target.value)}
                        className="w-full px-4 py-2 border border-gray-300 rounded focus:ring-2 focus:ring-relac-green focus:border-transparent outline-none transition"
                        placeholder="••••••••"
                        required
                    />
                </div>
                <button
                    disabled={loading}
                    className="w-full bg-relac-green hover:bg-green-600 text-white font-semibold py-2.5 rounded shadow-sm transition disabled:opacity-50"
                >
                    {loading ? "Procesando..." : (isLogin ? "Ingresar" : "Registrarse")}
                </button>
            </form>

            <p className="mt-6 text-center text-sm text-gray-600">
                {isLogin ? "¿No tienes cuenta? " : "¿Ya tienes cuenta? "}
                <button
                    onClick={() => setIsLogin(!isLogin)}
                    className="text-relac-green font-semibold hover:underline"
                >
                    {isLogin ? "Regístrate aquí" : "Inicia sesión"}
                </button>
            </p>
        </div>
    );
}

const renderMessageContent = (content) => {
    if (!content) return null;
    const lines = content.split('\n');
    return lines.map((line, i) => {
        // Parse bold **text**
        const parts = line.split(/(\*\*.*?\*\*)/g);
        const formattedParts = parts.map((part, j) => {
            if (part.startsWith('**') && part.endsWith('**')) {
                return <strong key={j} className="font-semibold">{part.slice(2, -2)}</strong>;
            }
            return part;
        });

        const trimmed = line.trim();
        // Unordered lists
        if (trimmed.startsWith('* ') || trimmed.startsWith('- ')) {
            const listText = trimmed.slice(2);
            // Re-parse the rest for bold
            const listParts = listText.split(/(\*\*.*?\*\*)/g).map((part, j) => {
                if (part.startsWith('**') && part.endsWith('**')) return <strong key={j}>{part.slice(2, -2)}</strong>;
                return part;
            });
            return (
                <div key={i} className="flex ml-4 mb-2 items-start mt-2">
                    <span className="mr-2 mt-0.5">•</span>
                    <span>{listParts}</span>
                </div>
            );
        }

        // Ordered lists
        const orderedMatch = trimmed.match(/^(\d+)\.\s(.*)/);
        if (orderedMatch) {
            const listPrefix = orderedMatch[1];
            const listText = orderedMatch[2];
            const listParts = listText.split(/(\*\*.*?\*\*)/g).map((part, j) => {
                if (part.startsWith('**') && part.endsWith('**')) return <strong key={j}>{part.slice(2, -2)}</strong>;
                return part;
            });
            return (
                <div key={i} className="flex ml-4 mb-2 items-start mt-2">
                    <span className="mr-2 font-medium mt-0.5">{listPrefix}.</span>
                    <span>{listParts}</span>
                </div>
            );
        }

        return <p key={i} className="mb-2 whitespace-pre-wrap last:mb-0">{formattedParts}</p>;
    });
};

function ChatInterface({ token }) {
    const [messages, setMessages] = useState([
        { role: "assistant", content: "¡Hola! Soy el asistente de la biblioteca ReLAC. ¿En qué puedo ayudarte hoy? Por ejemplo, puedes pedirme: 'Encuentra evaluaciones sobre género en Ecuador'." }
    ]);
    const [input, setInput] = useState("");
    const [loading, setLoading] = useState(false);
    const [loadingTime, setLoadingTime] = useState(0);
    const messagesEndRef = useRef(null);
    const inputRef = useRef(null);

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    };

    useEffect(() => {
        const lastMessage = messages[messages.length - 1];
        if (lastMessage && lastMessage.role === "user") {
            scrollToBottom();
        }
    }, [messages]);

    useEffect(() => {
        if (loading) {
            scrollToBottom();
        }
    }, [loading]);

    useEffect(() => {
        if (inputRef.current) {
            inputRef.current.focus();
        }
    }, []);

    useEffect(() => {
        let interval;
        if (loading) {
            setLoadingTime(0);
            interval = setInterval(() => {
                setLoadingTime((prev) => prev + 1);
            }, 1000);
        } else {
            setLoadingTime(0);
        }
        return () => clearInterval(interval);
    }, [loading]);

    const handleSend = async (e) => {
        e.preventDefault();
        if (!input.trim() || loading) return;

        const userMsg = input.trim();
        setInput("");
        setMessages(prev => [...prev, { role: "user", content: userMsg }]);
        setLoading(true);

        try {
            const res = await axios.post(`${API_BASE}/chat`,
                { prompt: userMsg },
                { headers: { Authorization: `Bearer ${token}` } }
            );

            const botResp = res.data;
            setMessages(prev => [...prev, {
                role: "assistant",
                content: botResp.answer,
                citations: botResp.citations,
                prompt: userMsg
            }]);
        } catch (err) {
            let errorMsg = "Lo siento, ocurrió un error.";
            if (err.response?.status === 429) {
                errorMsg = "Has alcanzado el límite de 20 consultas en 24 horas.";
            } else if (err.response?.status === 503) {
                errorMsg = "El sistema está ocupado. Por favor intenta de nuevo en unos minutos.";
            }
            setMessages(prev => [...prev, { role: "assistant", content: errorMsg, isError: true }]);
        } finally {
            setLoading(false);
            // Re-focus the input after submission completes
            setTimeout(() => {
                inputRef.current?.focus();
            }, 50);
        }
    };

    const handleFeedback = async (msgIndex, isPositive) => {
        const msg = messages[msgIndex];
        if (msg.feedbackSubmitted) return;

        try {
            await axios.post(`${API_BASE}/feedback`, {
                query_prompt: msg.prompt || "Desconocido",
                bot_response: msg.content,
                is_positive: isPositive
            }, { headers: { Authorization: `Bearer ${token}` } });

            setMessages(prev => prev.map((m, i) => i === msgIndex ? { ...m, feedbackSubmitted: true } : m));
        } catch (err) {
            console.error("Feedback error", err);
        }
    };

    return (
        <div className="w-full max-w-4xl h-[80vh] flex flex-col glass-panel rounded-2xl shadow-xl overflow-hidden border border-gray-100">
            {/* Header */}
            <div className="bg-relac-dark border-b border-gray-100 p-4 flex items-center justify-between">
                <div>
                    <h3 className="font-semibold text-white text-lg">Bibliografía AI-Assistant</h3>
                    <p className="text-xs text-white/70">Respuestas basadas en el catálogo de 1000+ recursos</p>
                </div>
                <div>
                    <img src="/frontend/Logo_Relac_2026_Blanco.png" alt="ReLAC Logo" className="h-24 w-auto object-contain" />
                </div>
            </div>

            {/* Chat Area */}
            <div className="flex-1 overflow-y-auto p-4 md:p-6 space-y-6 bg-gray-50/50">
                {messages.map((msg, idx) => (
                    <div key={idx} className={`flex w-full message-anim ${msg.role === "user" ? "justify-end" : "justify-start"}`}>
                        <div className={`max-w-[85%] md:max-w-[75%] rounded-2xl p-4 shadow-sm ${msg.role === "user"
                            ? "bg-relac-dark text-white rounded-tr-none"
                            : msg.isError ? "bg-red-50 text-red-800 border border-red-100 rounded-tl-none" : "bg-white text-gray-800 border border-gray-100 rounded-tl-none"
                            }`}>
                            <div className="text-sm md:text-base leading-relaxed">
                                {renderMessageContent(msg.content)}
                            </div>

                            {/* Citations */}
                            {msg.citations && msg.citations.length > 0 && (
                                <div className="mt-4 pt-4 border-t border-gray-100">
                                    <p className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">Fuentes y Documentos Citados:</p>
                                    <div className="space-y-2">
                                        {msg.citations.map((cit, cIdx) => (
                                            <div key={cIdx} className="bg-gray-50 p-3 rounded border border-gray-100 text-sm flex flex-col sm:flex-row sm:items-start justify-between gap-3">
                                                <div>
                                                    <p className="font-semibold text-relac-dark mb-1">{cit.title}</p>
                                                    <p className="text-xs text-gray-600">{cit.author}</p>
                                                </div>
                                                {cit.link && (
                                                    <a href={cit.link} target="_blank" rel="noopener noreferrer" className="shrink-0 inline-flex items-center space-x-1 text-xs font-semibold px-3 py-1.5 bg-relac-green/10 text-relac-green rounded hover:bg-relac-green hover:text-white transition group">
                                                        <span>Acceder</span>
                                                        <svg className="w-3 h-3 transform group-hover:-translate-y-0.5 group-hover:translate-x-0.5 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" /></svg>
                                                    </a>
                                                )}
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {/* Feedback Mechanism */}
                            {msg.role === "assistant" && !msg.isError && msg.prompt && (
                                <div className="mt-3 pt-3 border-t border-gray-100 flex justify-end space-x-2 items-center">
                                    {msg.feedbackSubmitted && <span className="text-xs text-gray-400 mr-2">¡Gracias por tu retroalimentación!</span>}
                                    <button
                                        onClick={() => handleFeedback(idx, true)}
                                        disabled={msg.feedbackSubmitted}
                                        className={`p-1.5 rounded transition ${msg.feedbackSubmitted ? 'opacity-50 cursor-not-allowed text-gray-400' : 'text-gray-400 hover:text-relac-green hover:bg-green-50'}`}
                                        title="Buena respuesta"
                                    >
                                        <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"></path></svg>
                                    </button>
                                    <button
                                        onClick={() => handleFeedback(idx, false)}
                                        disabled={msg.feedbackSubmitted}
                                        className={`p-1.5 rounded transition ${msg.feedbackSubmitted ? 'opacity-50 cursor-not-allowed text-gray-400' : 'text-gray-400 hover:text-relac-red hover:bg-red-50'}`}
                                        title="Mala respuesta"
                                    >
                                        <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17"></path></svg>
                                    </button>
                                </div>
                            )}

                        </div>
                    </div>
                ))}

                {loading && (
                    <div className="flex justify-start message-anim">
                        <div className="bg-white border border-gray-100 rounded-2xl rounded-tl-none p-4 shadow-sm flex space-x-3 items-center text-gray-500">
                            <div className="flex space-x-1.5 items-center">
                                <div className="w-2 h-2 bg-relac-green rounded-full animate-bounce"></div>
                                <div className="w-2 h-2 bg-relac-green rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
                                <div className="w-2 h-2 bg-relac-green rounded-full animate-bounce" style={{ animationDelay: '0.4s' }}></div>
                            </div>
                            <span className="text-xs text-gray-400 border-l border-gray-200 pl-3">
                                Analizando catálogo... ({loadingTime}s)
                            </span>
                        </div>
                    </div>
                )}
                <div ref={messagesEndRef} />
            </div>

            {/* Input Area */}
            <div className="bg-white border-t border-gray-100 p-4">
                <form onSubmit={handleSend} className="relative flex items-center">
                    <input
                        ref={inputRef}
                        type="text"
                        value={input}
                        onChange={(e) => setInput(e.target.value)}
                        placeholder="Ej. Encuentra evaluaciones sobre educación en Perú..."
                        className="w-full bg-gray-50 border border-gray-200 text-gray-800 rounded-full py-3.5 pl-6 pr-14 focus:outline-none focus:ring-2 focus:ring-relac-green/50 focus:border-relac-green transition shadow-inner disabled:bg-gray-100"
                        disabled={loading}
                    />
                    <button
                        type="submit"
                        disabled={loading || !input.trim()}
                        className="absolute right-2 p-2 bg-relac-green text-white rounded-full hover:bg-green-600 disabled:opacity-50 disabled:cursor-not-allowed transition transform hover:scale-105 shadow-sm"
                    >
                        <svg className="w-5 h-5 -ml-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" /></svg>
                    </button>
                </form>
                <div className="text-center mt-2">
                    <p className="text-[10px] text-gray-400">ReLAC AI MVP • Límite de 20 consultas por día.</p>
                </div>
            </div>
        </div>
    );
}

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