hello! hope you're having a fantastic day.

right now, when i enter email/password:
- it logs me in, but:
- i have to refresh the page to see changes in the menu like changing to log out button
- the email inside the button doesn't change until i refresh

when I log out, the changes happen immediately. this is the functionality i'm after (the second one) for both buttons. 
- Log in 
- menu updates
- log out, 
- menu updates. 

the 4 components here are "Nav.astro" and 2 astro actions "signinAccount.ts" and "signoutAccount.ts", and Login.astro the main component. 
---

---
import { Astronav, MenuItems, MenuIcon, Dropdown, DropdownItems } from "astro-navbar";
import { Login, RegisterUser, LogOutButton } from './auth';

const categories = [
  { value: 'mental-health-basics', label: 'Mental Health Basics' },
  { value: 'self-care-practices', label: 'Self-Care Practices' },
  { value: 'emotional-well-being', label: 'Emotional Well-being' },
  { value: 'relationships-and-communication', label: 'Relationships and Communication' },
  { value: 'work-life-balance', label: 'Work-Life Balance' },
  { value: 'music-and-mental-health', label: 'Music and Mental Health' },
  { value: 'therapies-and-treatments', label: 'Therapies and Treatments' },
  { value: 'personal-growth-and-development', label: 'Personal Growth and Development' },
  { value: 'mental-health-and-lifestyle', label: 'Mental Health and Lifestyle' },
  { value: 'crisis-management-and-support', label: 'Crisis Management and Support' },
];

const { userEmail } = Astro.locals;
---

<header class="bg-transparent nav-bar">
  <Astronav>
    <div class="max-w8xl mx-auto px-2">
      <div class="flex items-center justify-between h-16">
        <a href="/" class="text-gray-800 hover:text-gray-500">Home</a>
        <MenuIcon class="w-4 h-4 text-gray-800 lg:hidden" />
        <MenuItems class="hidden w-full lg:w-auto mt-2 lg:flex lg:mt-0">
          <ul class="flex flex-col lg:flex-row lg:gap-3">
            <li><a href="/journal" class="text-gray-800 hover:text-gray-500">Journal App</a></li>
            <li><a href="/about" class="text-gray-800 hover:text-gray-500">About</a></li>
            <li><a href="/contact" class="text-gray-800 hover:text-gray-500">Contact</a></li>
            <li>
              <Dropdown class="group">
                <button class="flex items-center text-gray-800 hover:text-gray-500">
                  <span>Categories</span>
                  <svg
                    aria-hidden="true"
                    class="w-5 h-5 ml-1 group-open:rotate-180 transition-transform" 
                    xmlns="http://www.w3.org/2000/svg" 
                    viewBox="0 0 20 20" 
                    fill="currentColor">
                    <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                  </svg>
                </button>
                <DropdownItems>
                  <div class="lg:absolute lg:left-1/2 lg:-translate-x-1/3 lg:top-full lg:mt-2 w-screen max-w-screen-xl bg-white/10 backdrop-blur-lg shadow-lg rounded-lg p-4">
                    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                      {categories.map((category) => (
                        <a href={`/categories/${category.value}`} class="text-gray-800 hover:text-green-500 hover:bg-gray-100 rounded-lg p-2 transition-colors">
                          {category.label}
                        </a>
                      ))}
                    </div>
                  </div>
                </DropdownItems>
              </Dropdown>
            </li>

            <li class="relative">
              <button class="flex items-center text-gray-800 hover:text-gray-500 account-button">
                <span id="account-button-text">{userEmail ? `Welcome, ${userEmail}` : 'Account'}</span>
                <svg
                  aria-hidden="true"
                  class="w-5 h-5 ml-1 transition-transform" 
                  xmlns="http://www.w3.org/2000/svg" 
                  viewBox="0 0 20 20" 
                  fill="currentColor">
                  <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                </svg>
              </button>
              <Login />
            </li>
          </div>
        </div>
      </Astronav>
    </header>
    
<style>
  /* Add any additional styles here */
  @media (max-width: 1023px) {
    .lg\:hidden:not(.hidden) + .lg\:flex {
      display: none;
    }
  }
</style>

---
import { Input, Button } from '../';
const { class: additionalClasses } = Astro.props;
---

<div class="login-wrapper">
  <div id="login-content">
    <form class="login-form" id="sign-in">
      <div class="form-fields">
        <Input name="email" type="email" placeholder="Email/username..." />
        <Input name="password" type="password" placeholder="Password..." />
      </div>
      <Button type="submit" id="submit-button">
        <span id="button-text">Log in to Your Account</span>
        <span id="loading-icon" class="hidden">
          <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
        </span>
      </Button>
    </form>
  </div>
</div>

<script>
  import { actions, isInputError } from "astro:actions";

  const loginWrapper = document.querySelector(".login-wrapper") as HTMLDivElement;
  const loginContent = document.querySelector("#login-content") as HTMLDivElement;
  const accountButtonText = document.querySelector('#account-button-text') as HTMLSpanElement;
  const accountButton = document.querySelector('.account-button') as HTMLButtonElement;

  let currentUser = null;

  // Function to set the loading state of the submit button
  function setLoading(isLoading: boolean) {
    const submitButton = document.querySelector("#submit-button") as HTMLButtonElement;
    const buttonText = document.querySelector("#button-text") as HTMLSpanElement;
    const loadingIcon = document.querySelector("#loading-icon") as HTMLSpanElement;
    
    submitButton.disabled = isLoading;
    buttonText.classList.toggle('hidden', isLoading);
    loadingIcon.classList.toggle('hidden', !isLoading);
  }

  // Function to show the login form
  function showLoginForm() {
    loginWrapper.style.display = 'block';
    setTimeout(() => {
      loginWrapper.style.opacity = '1';
      loginWrapper.style.transform = 'translateY(0)';
    }, 10);
  }

  // Function to hide the login form
  function hideLoginForm() {
    loginWrapper.style.opacity = '0';
    loginWrapper.style.transform = 'translateY(-10px)';
    setTimeout(() => {
      loginWrapper.style.display = 'none';
    }, 300);
  }

  // Function to update UI based on login state
  function updateUIForUser(email) {
    currentUser = email;
    accountButtonText.textContent = `Welcome, ${email}`;
    loginContent.innerHTML = `
      <p>Welcome back, ${email}!</p>
      <button id="logout-button" class="mt-4">Log Out</button>
    `;
    addLogoutListener();
    hideLoginForm();
  }

  // Function to update UI for logged out state
  function updateUIForLoggedOut() {
    currentUser = null;
    accountButtonText.textContent = 'Account';
    loginContent.innerHTML = `
      <form class="login-form" id="sign-in">
        <div class="form-fields">
          <input name="email" type="email" placeholder="Email/username..." />
          <input name="password" type="password" placeholder="Password..." />
        </div>
        <button type="submit" id="submit-button">
          <span id="button-text">Log in to Your Account</span>
          <span id="loading-icon" class="hidden">
            <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
          </span>
        </button>
      </form>
    `;
    addLoginListener();
  }

  // Function to add logout listener
  function addLogoutListener() {
    const logoutButton = document.querySelector('#logout-button');
    logoutButton?.addEventListener('click', handleLogout);
  }

  // Function to add login listener
  function addLoginListener() {
    const loginForm = document.querySelector("#sign-in") as HTMLFormElement;
    loginForm?.addEventListener('submit', handleLogin);
  }

  // Handle login
  async function handleLogin(e) {
    e.preventDefault();
    setLoading(true);

    try {
      const { error, data } = await actions.signinAccount(new FormData(e.target));
      if (error) {
        console.log(error);
        if (isInputError(error)) {
          console.log(error.fields);
        }
        return;
      } 
      updateUIForUser(data.email);
      window.dispatchEvent(new CustomEvent('userLoggedIn', { detail: { email: data.email } }));
    } catch (error) {
      console.error('An unexpected error occurred:', error);
      // You might want to show an error message to the user here
    } finally {
      setLoading(false);
    }
  }

  // Handle logout
  async function handleLogout() {
    try {
      await actions.signoutAccount();
      updateUIForLoggedOut();
      window.dispatchEvent(new CustomEvent('userLoggedOut'));
    } catch (error) {
      console.error('An error occurred during logout:', error);
    }
  }

  // Toggle login form when Account button is clicked
  accountButton?.addEventListener('click', (e) => {
    e.stopPropagation();
    if (loginWrapper.style.display === 'none' || loginWrapper.style.display === '') {
      showLoginForm();
    } else {
      hideLoginForm();
    }
  });

  // Hide login form when clicking outside
  document.addEventListener('click', (e) => {
    if (!loginWrapper.contains(e.target as Node) && !accountButton?.contains(e.target as Node)) {
      hideLoginForm();
    }
  });

  // Prevent form from closing when clicking inside it
  loginWrapper.addEventListener('click', (e) => {
    e.stopPropagation();
  });

  // Initial setup
  function initializeLoginState() {
    if (accountButtonText.textContent.startsWith('Welcome')) {
      const email = accountButtonText.textContent.replace('Welcome, ', '');
      updateUIForUser(email);
    } else {
      updateUIForLoggedOut();
    }
  }

  // Call the initialization function when the script loads
  initializeLoginState();
</script>

<style>
  .login-wrapper {
    position: absolute;
    top: 100%;
    right: 0;
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    padding: 20px;
    z-index: 1000;
    display: none;
    opacity: 0;
    transform: translateY(-10px);
    transition: opacity 0.3s ease, transform 0.3s ease;
    width: 300px; /* Set a fixed width to maintain size */
    font-size: 1rem; /* Set a fixed font size */
  }

  .login-form {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }

  .form-fields {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  /* Style for the logout button */
  #logout-button {
    background-color: #f44336;
    color: white;
    padding: 10px 15px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }

  #logout-button:hover {
    background-color: #d32f2f;
  }
</style>

// signinAccount.ts
import { defineAction } from 'astro:actions';
import { z } from 'astro:schema';
import { signInWithEmailAndPassword } from 'firebase/auth';
import { auth } from '../firebase/client';

export const signinAccount = defineAction({
  accept: "form",
  input: z.object({
    email: z.string().email(),
    password: z.string(),
  }),
  handler: async ({ email, password }) => {
    await signInWithEmailAndPassword(auth, email, password);
    window.dispatchEvent(new CustomEvent('userLoggedIn', { detail: { email } }));
  },
});

// signoutAccount.ts
import { defineAction } from 'astro:actions';
import { auth } from '../firebase/client';

export const signoutAccount = defineAction({
  handler: async () => {
    await auth.signOut();
    window.dispatchEvent(new CustomEvent('userLoggedOut'));
  },
});