import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { authService } from '../services/auth';
import './Navigation.css';

function Navigation() {
  const [user, setUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const userData = await authService.getUser();
        setUser(userData);
      } catch (error) {
        console.error('Auth check failed:', error);
      } finally {
        setIsLoading(false);
      }
    };

    checkAuth();
  }, []);

  const handleLogin = async () => {
    try {
      await authService.login();
    } catch (error) {
      console.error('Login failed:', error);
    }
  };

  const handleLogout = async () => {
    try {
      await authService.logout();
      setUser(null);
    } catch (error) {
      console.error('Logout failed:', error);
    }
  };

  if (isLoading) {
    return (
      <nav className="navigation">
        <div className="nav-brand">
          <Link to="/">Container Mom</Link>
        </div>
        <div className="nav-loading">Loading...</div>
      </nav>
    );
  }

  return (
    <nav className="navigation">
      <div className="nav-brand">
        <Link to="/">Container Mom</Link>
      </div>
      
      {user ? (
        <div className="nav-user">
          <div className="user-menu">
            <button className="user-button">
              {user.email}
              <span className="arrow">▼</span>
            </button>
            <div className="dropdown-menu">
              <Link to="/profile">Profile</Link>
              <Link to="/deployments">Deployments</Link>
              <button onClick={handleLogout}>
                Log Out
              </button>
            </div>
          </div>
        </div>
      ) : (
        <div className="nav-auth">
          <button onClick={handleLogin} className="login-btn">
            Log In
          </button>
          <button 
            onClick={handleLogin} 
            className="signup-btn"
          >
            Sign Up
          </button>
        </div>
      )}
    </nav>
  );
}

export default Navigation; 