// components/Header.jsx

/**
 * Application Header Component
 *
 * Displays the site logo/title, desktop navigation, mobile menu toggle,
 * and user authentication status (Sign In button or User Profile dropdown).
 */

// React, Hooks, and PropTypes are globally available

const Header = ({ isMobileMenuOpen, onToggleMobileMenu, user, onSignout }) => {
  // --- State ---
  const [isProfileMenuOpen, setIsProfileMenuOpen] = useState(false);

  // --- Event Handlers ---

  // Close profile dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        isProfileMenuOpen &&
        !event.target.closest(".profile-menu-container")
      ) {
        setIsProfileMenuOpen(false);
      }
    };
    if (isProfileMenuOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    }
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [isProfileMenuOpen]);

  // Toggle the profile dropdown menu
  const toggleProfileMenu = () => {
    setIsProfileMenuOpen((prev) => !prev);
  };

  // Close profile menu and call the main signout handler from App.jsx
  const handleSignoutClick = () => {
    setIsProfileMenuOpen(false);
    onSignout();
  };

  // Close profile menu when navigating to profile page
  const handleProfileLinkClick = () => {
    setIsProfileMenuOpen(false);
  };

  // Close mobile menu when a link inside it is clicked
  const handleMobileLinkClick = () => {
    if (isMobileMenuOpen) {
        onToggleMobileMenu();
    }
  };

  // --- Render ---
  return (
    <header className="app-header">
      <div className="header-content container">
        {/* Logo - Renamed */}
        <div className="logo">
          <a href="#/">Naalam</a>
        </div>

        {/* Desktop Navigation */}
        <nav className="app-nav-desktop">
          <ul>
            <li>
              {/* Renamed Courses link to Home */}
              <a
                href="#/"
                className={
                  // Active state logic: active if root or starts with /courses (or just root now)
                  window.location.hash === "#/" || window.location.hash === "" ? "active" : ""
                }
              >
                Home
              </a>
            </li>
            <li>
              <a
                href="#/about"
                className={window.location.hash === "#/about" ? "active" : ""}
              >
                About
              </a>
            </li>
            <li>
              <a
                href="#/contact"
                className={window.location.hash === "#/contact" ? "active" : ""}
              >
                Contact
              </a>
            </li>
          </ul>
        </nav>

        {/* Authentication Status / User Menu */}
        <div className="auth-section">
          {user ? (
            // --- User is Logged In: Profile Menu ---
            <div className="profile-menu-container">
              <button
                onClick={toggleProfileMenu}
                className="profile-button"
                aria-haspopup="true"
                aria-expanded={isProfileMenuOpen}
                aria-controls="profile-dropdown-menu"
              >
                <div className="profile-avatar">
                  {user.profile_picture ? (
                    <img
                      src={user.profile_picture}
                      alt="Profile"
                      className="profile-pic"
                      onError={(e) => { e.target.src = 'https://via.placeholder.com/32?text=U'; }}
                    />
                  ) : (
                    <i className="fas fa-user default-avatar"></i>
                  )}
                </div>
                <span className="profile-username">{user.username}</span>
                <i
                  className={`fas fa-chevron-${isProfileMenuOpen ? "up" : "down"} profile-chevron`}
                ></i>
              </button>

              {/* Profile Dropdown Menu */}
              {isProfileMenuOpen && (
                <div className="profile-dropdown" role="menu" id="profile-dropdown-menu">
                  <a
                    href="#/profile"
                    className="dropdown-item"
                    role="menuitem"
                    onClick={handleProfileLinkClick}
                  >
                    <i className="fas fa-user-circle dropdown-icon"></i> Profile
                  </a>
                  <button
                    onClick={handleSignoutClick}
                    className="dropdown-item"
                    role="menuitem"
                  >
                    <i className="fas fa-sign-out-alt dropdown-icon"></i> Sign Out
                  </button>
                </div>
              )}
            </div>
          ) : (
            // --- User is Logged Out: Sign In Button ---
            <a href="#/signin" className="signin-button button-primary">
              Sign In
            </a>
          )}
        </div>

        {/* Mobile Menu Toggle Button */}
        <button
          className="mobile-menu-toggle"
          onClick={onToggleMobileMenu}
          aria-label="Toggle mobile menu"
          aria-expanded={isMobileMenuOpen}
          aria-controls="mobile-nav-menu"
        >
          <span></span>
          <span></span>
          <span></span>
        </button>
      </div>

      {/* Mobile Navigation Menu */}
      <nav className={`app-nav-mobile ${isMobileMenuOpen ? "open" : ""}`} id="mobile-nav-menu">
        <ul>
          <li>
            {/* Renamed Courses link to Home */}
            <a href="#/" onClick={handleMobileLinkClick}>
              Home
            </a>
          </li>
          <li>
            <a href="#/about" onClick={handleMobileLinkClick}>
              About
            </a>
          </li>
          <li>
            <a href="#/contact" onClick={handleMobileLinkClick}>
              Contact
            </a>
          </li>
          {/* Show Sign In/Profile links based on user state */}
          {user ? (
            <>
              <li>
                <a href="#/profile" onClick={handleMobileLinkClick}>
                  Profile
                </a>
              </li>
              <li>
                <button onClick={() => { handleMobileLinkClick(); handleSignoutClick(); }} className="mobile-signout-btn">
                  Sign Out
                </button>
              </li>
            </>
          ) : (
            <li>
              <a href="#/signin" onClick={handleMobileLinkClick}>
                Sign In
              </a>
            </li>
          )}
        </ul>
      </nav>
    </header>
  );
};

// --- Prop Type Validation ---
Header.propTypes = {
  isMobileMenuOpen: PropTypes.bool.isRequired,
  onToggleMobileMenu: PropTypes.func.isRequired,
  user: PropTypes.shape({
    id: PropTypes.number,
    username: PropTypes.string,
    email: PropTypes.string,
    full_name: PropTypes.string,
    profile_picture: PropTypes.string,
  }),
  onSignout: PropTypes.func.isRequired,
};

// Make Header component globally available
window.Header = Header;
