import React, { useState, useEffect  } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';

const Header = () => {
    const [display_name, setDisplay_name] = useState('');
    const [avatar, setAvatar] = useState('');
    const [isLoading, setIsLoading] = useState(true);
    const [isAnimated, setIsAnimated] = useState(false);
    
    useEffect(() => {
        const checkSession = async () => {
            try {
                const response = await axios.get('/api/users/me');
                setDisplay_name(response.data.display_name);
                setAvatar(response.data.avatar_url);
            } catch {}  
            setIsLoading(false);
            setTimeout(() => setIsAnimated(true), 150);
        };
        checkSession();
    }, []);
    
    return (
    <header className="header">
      <div className="header-container">
        <div className="logo">
          <Link to="/main">
            <h1>Fool-stack</h1>
          </Link>
        </div>
        <nav className="nav">
          {!isLoading && (
            <ul className={`nav-list ${isAnimated ? 'visible' : ''}`}>
              {display_name ? (
                <>
                  <li><Link to="/Kanban-Boards-List">Канбан-доски</Link></li>
                  <li><Link to="/profile">{display_name}<img className="nav-avatar" src={avatar}></img></Link></li>
                </>
              ) : (
                <>
                  <li><Link to="/registration">Регистрация</Link></li>
                  <li><Link to="/login">Вход</Link></li>
                </>
              )}
            </ul>
          )}
        </nav>
      </div>
    </header>
    );
};

export default Header;