import { useState, useEffect } from 'react';
import io from 'socket.io-client';

const socket = io('http://chat.viensonjette.fr'); // Ton URL de reverse proxy

function App() {
  const [user, setUser] = useState(null);
  const [form, setForm] = useState({ pseudo: '', age: '', city: '', rooms: ['general'] });

  const joinChat = () => {
    if (form.pseudo) {
      setUser(form);
      socket.emit('join_system', form);
    }
  };

  if (!user) {
    return (
      <div className="bg-black text-green-500 min-h-screen font-mono p-10">
        <h1 className="text-2xl mb-4 uppercase">{">"} Authentification_</h1>
        <input placeholder="PSEUDO" className="bg-transparent border-b block mb-4" 
               onChange={(e) => setForm({...form, pseudo: e.target.value})} />
        <input placeholder="AGE" type="number" className="bg-transparent border-b block mb-4" 
               onChange={(e) => setForm({...form, age: e.target.value})} />
        <button onClick={joinChat} className="border border-green-500 px-4 py-2 hover:bg-green-500 hover:text-black">
          INITIALIZE_SESSION
        </button>
      </div>
    );
  }

  return <ChatScreen user={user} />;
}

// Composant simplifié pour le Chat
function ChatScreen({ user }) {
  const [msg, setMsg] = useState("");
  const [list, setList] = useState([]);

  useEffect(() => {
    socket.on('receive_msg', (data) => setList((prev) => [...prev, data]));
  }, []);

  const send = () => {
    socket.emit('send_msg', { text: msg, room: 'general', pseudo: user.pseudo });
    setMsg("");
  };

  return (
    <div className="bg-black text-green-400 min-h-screen p-4 font-mono">
      <div className="h-64 overflow-y-auto border border-green-900 mb-4 p-2">
        {list.map((m, i) => <p key={i}>[{m.pseudo}]: {m.text}</p>)}
      </div>
      <input value={msg} onChange={(e) => setMsg(e.target.value)} className="bg-gray-900 w-full p-2" />
      <button onClick={send} className="mt-2 text-xs">[ ENVOYER ]</button>
    </div>
  );
}

export default App;