'use client';

import { useAuth, useClerk } from '@clerk/nextjs';
import * as Popover from '@radix-ui/react-popover';
import {
  useExperiment,
  useGateValue,
  useStatsigClient,
} from '@statsig/react-bindings';
import clsx from 'clsx';
import { omit } from 'lodash-es';
import { observer } from 'mobx-react-lite';
import { Trans, useTranslation } from 'next-i18next';
import dynamic from 'next/dynamic';
import { usePathname } from 'next/navigation';
import React, { useCallback, useMemo, useRef } from 'react';
import storageAvailable from 'storage-available';
import { twMerge } from 'tailwind-merge';

import { useStores } from '@/app/(root)/AppProviders';
import { useOrpheusExperimentGroup } from '@/app/(root)/chat/hooks/useOrpheusExperimentGroup';
import { SUNOVERSE_WEB_FEATURE_FLAG } from '@/app/(root)/live-radio/constants';
import Button, {
  Props as ButtonProps,
  ButtonShape,
  ButtonSize,
  ButtonVariant,
} from '@/components/button/Button';
import { UpsellCard } from '@/components/card/UpsellCard';
import Logo from '@/components/image/Logo';
import { SkeletonBone } from '@/components/layout/Skeleton';
import Link from '@/components/link/Link';
import LoginBar, {
  LoginBarAvatar,
  Props as LoginBarProps,
} from '@/components/login/LoginBar';
import ChangelogModal from '@/components/modal/ChangelogModal';
import ProfileEditModal from '@/components/modal/ProfileEditModal';
import { ModalTypes } from '@/components/modal/constants/ModalTypes';
import NotificationDot from '@/components/notification/NotificationDot';
import { MediaQueryOnly } from '@/components/responsive/Responsive';
import { Tooltip } from '@/components/tooltip/Tooltip';
import { useModalContext } from '@/context/ModalContext';
import useChangelogItems from '@/hooks/useChangelogItems';
import useDisclosure from '@/hooks/useDisclosure';
import { useSubscriptionInfo } from '@/hooks/useSubscriptionInfo';
import {
  ChevronDownIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
  CreateIcon,
  ExploreIcon,
  GiftIcon,
  HomeIcon,
  HooksIcon,
  LibraryIcon,
  LoginIcon,
  MoreVerticalIcon,
  NewsIcon,
  NotificationsIcon,
  PlusIcon,
  RadioBroadcastIcon,
  SearchIcon,
  StarIcon,
  StudioIcon,
  WarningIcon,
} from '@/icons';
import logWebUserEvent, {
  logHookWebGeneralEvent,
} from '@/logging/logWebUserEvent';
import { FeatureKey, PlanFeature } from '@/state/sessionStore';
import {
  REFERRER_PARAM,
  SIGNUP_SOURCE_PARAM,
  SIGNUP_SOURCE_VALUES,
  TAILWIND_MEDIUM_MIN_WIDTH,
} from '@/utils/constants';
import { canGenerateSong, isFeatureEnabledForPlan } from '@/utils/session';
import {
  getClerkSignInRedirectProps,
  getSignUpSource,
  isActiveNavTab,
} from '@/utils/utils';

import SocialMediaBar from './SocialMediaBar';

const SideSubNav = dynamic(() => import('@/components/section/SideSubNav'), {
  ssr: false,
});

export type Props = React.HTMLAttributes<HTMLDivElement> & {
  isInMobileSongPageV2Experiment?: boolean;
  collapsible?: boolean;
  mountCollapsed?: boolean;
};

type RenderPropArgs<T> = T extends (...args: any[]) => any
  ? Parameters<T>[0]
  : never;

type LoginBarChildProps = RenderPropArgs<LoginBarProps['children']>;

const NAV_BUTTON_HOVER_CLASSNAME = clsx(
  'enabled:hover:before:bg-transparent hover:before:bg-transparent',
  'hover:text-foreground-primary focus-visible:text-foreground-primary'
);

const SIDENAV_FULL_WIDTH = '200px';
const SIDENAV_COLLAPSED_WIDTH = '66px';
// We need to shift the avatar to the right so it's centered with the icons below it.
const SIDENAV_AVATAR_X_CORRECTION = '3px';

// localStorage key used to remember whether the sidebar was collapsed
const SIDENAV_COLLAPSED_STORAGE_KEY = 'sidenav-collapsed-state';

const ProfileRowButton: React.FC<
  LoginBarChildProps & { showTooltip?: boolean }
> = observer((props) => {
  const { session } = useStores();
  const pathname = usePathname();
  const showHandle = !!(
    session.user?.display_name &&
    session.user?.handle &&
    session.user?.is_handle_updated
  );

  const tooltipText =
    session.user?.display_name ||
    (session.user?.handle ? `@${session.user?.handle}` : 'Anonymous');

  return (
    <NavButton
      active={pathname === `/@${session.user?.handle}`}
      iconEnd={ChevronDownIcon}
      tooltipLabel={tooltipText}
      showTooltip={props.showTooltip}
      className={clsx(
        'group block w-full px-0.5 py-0',
        'translate-x-[calc(-1 * var(--avatar-x-correction))]',
        {
          'text-foreground-secondary': pathname !== `/@${session.user?.handle}`,
          'text-foreground-primary': pathname === `/@${session.user?.handle}`,
        }
      )}
      iconClassName='w-2 h-2 text-foreground-inactive group-data-[show-content=false]/sidebar:invisible'
      hideChildrenWhenCollapsed={false}
    >
      <div className='w-max shrink-0'>
        <LoginBarAvatar
          className={clsx(
            'before:absolute before:-inset-[4px] before:rounded-full before:border-transparent',
            'before:border-2 before:border-transparent',
            'before:transition-colors before:duration-75',
            'group-hover:before:border-border-primary',
            'group-focus-within:before:border-border-primary'
          )}
          {...omit(props, 'showTooltip')}
        />
      </div>
      <div className='flex min-w-0 flex-1 flex-col items-start justify-center gap-0.5 group-data-[show-content=false]/sidebar:invisible'>
        <p
          className={clsx(
            'max-w-full',
            'text-left text-[14px] leading-[16px] font-medium',
            'group-hover:text-foreground-primary group-focus:text-foreground-primary',
            {
              'line-clamp-1': showHandle,
              'line-clamp-2': !showHandle,
            }
          )}
        >
          {session.user?.display_name ||
            (session.user?.handle ? `@${session.user?.handle}` : 'Anonymous')}
        </p>
        {showHandle && (
          <p
            className={clsx(
              'max-w-full',
              'line-clamp-1 text-left text-[13px] leading-[16px]',
              'text-foreground-inactive',
              'group-hover:text-foreground-tertiary group-focus:text-foreground-tertiary'
            )}
          >
            @{session.user?.handle}
          </p>
        )}
      </div>
    </NavButton>
  );
});

// NavButton component for sidebar navigation items.
// hideChildrenWhenCollapsed prop controls whether NavButton wraps children in visibility-controlling span:
// - true (default): Children are wrapped in <span className='group-data-[show-content=false]/sidebar:hidden'>
//                   This hides the text when sidebar is collapsed.
// - false: Children are NOT wrapped, allowing custom visibility control.
//          Used by ProfileRowButton which manually adds visibility classes to its internal elements.
//          Without custom handling, text would overflow when collapsed!
const NavButton: React.FC<
  ButtonProps & {
    hideChildrenWhenCollapsed?: boolean;
    tooltipLabel?: string;
    showTooltip?: boolean;
  }
> = ({
  hideChildrenWhenCollapsed = true,
  tooltipLabel,
  showTooltip = false,
  ...props
}) => {
  const button = (
    <Button
      variant={ButtonVariant.Tertiary}
      size={ButtonSize.Small}
      shape={ButtonShape.Rounded}
      active={false}
      {...props}
      className={twMerge(
        NAV_BUTTON_HOVER_CLASSNAME,
        'w-full px-2 py-1',
        'text-[16px] leading-[16px]',
        props.className
      )}
      contentClassName={twMerge('justify-start', props.contentClassName)}
      iconClassName={twMerge('w-[18px] h-[18px]', props.iconClassName)}
    >
      {hideChildrenWhenCollapsed ? (
        <span className='group-data-[show-content=false]/sidebar:hidden'>
          {props.children}
        </span>
      ) : (
        props.children
      )}
    </Button>
  );

  // Only render tooltip when showTooltip is true and tooltipLabel exists
  if (tooltipLabel && showTooltip) {
    return (
      <Tooltip label={tooltipLabel} placement='right'>
        {button}
      </Tooltip>
    );
  }

  return button;
};

// NOTE: This `SideNav` component can "collapse".
// Make sure to check any visual changes with the collapsed state.

const MENU_OFFSET: [number, number] = [-6, -46];

const SideNav: React.FC<Props> = observer((props) => {
  // Add state for popover
  const [isEarnCreditsOpen, setIsEarnCreditsOpen] = React.useState(false);

  const {
    className,
    isInMobileSongPageV2Experiment,
    collapsible = false,
    mountCollapsed,
    ...restProps
  } = props;

  // Determine the initial collapsed state.
  const localStorageAvailable = storageAvailable('localStorage');
  const {
    isControlGroup: isInOrpheusControlGroup,
    isLoading: isOrpheusExperimentLoading,
  } = useOrpheusExperimentGroup();

  const initialCollapsed = React.useMemo(() => {
    if (!collapsible) return false;

    // If mountCollapsed is explicitly provided (including false), respect it.
    if (typeof mountCollapsed === 'boolean') {
      return mountCollapsed;
    }

    // Otherwise attempt to restore the previous state from localStorage.
    if (localStorageAvailable) {
      const storedValue = localStorage.getItem(SIDENAV_COLLAPSED_STORAGE_KEY);
      return storedValue === 'true';
    }

    return false;
  }, [collapsible, mountCollapsed, localStorageAvailable]);

  const [collapsed, setCollapsed] = React.useState(initialCollapsed);

  React.useEffect(() => {
    if (!isOrpheusExperimentLoading && !isInOrpheusControlGroup) {
      setCollapsed(true);
    }
  }, [isInOrpheusControlGroup, isOrpheusExperimentLoading]);

  const {
    library,
    session,
    notifications: notificationsStore,
    menus,
  } = useStores();
  const { isLoaded, isSignedIn } = useAuth();
  const clerk = useClerk();
  const pathname = usePathname();
  const numCreditsRef = useRef<HTMLAnchorElement>(null);
  const [rotatedAuraUrl, setRotatedAuraUrl] = React.useState<string>('');

  // Load notifications on mount
  React.useEffect(() => {
    if (isLoaded && isSignedIn && session.userId) {
      notificationsStore.loadNotifications();
    }
  }, [isLoaded, isSignedIn, session.userId, notificationsStore]);

  const { t } = useTranslation();

  const {
    isOpen: isWhatsNewOpen,
    onOpen: onOpenWhatsNew,
    onClose: onCloseWhatsNew,
  } = useDisclosure();

  const [changelogItems, unviewedChangelogItems, updateChangelogLastViewed] =
    useChangelogItems();

  const {
    isOpen: isNotificationsPanelOpen,
    onOpen: openNotificationsPanel,
    onClose: closeNotificationsPanel,
  } = useDisclosure();

  const statsigClient = useStatsigClient();
  const isVip = statsigClient.checkGate('vip-profile-aura');

  const showCreditsExpiringTooltip = statsigClient.checkGate(
    'show-credits-expiring'
  );
  const hooksEnabled = statsigClient.checkGate('web-hooks-2025');
  const isSunoverseEnabled = useGateValue(SUNOVERSE_WEB_FEATURE_FLAG);
  const labelMakerEnabled = useGateValue('enable-label-maker');
  const sidebarCreditsVisibleExperiment = useExperiment(
    'web-hide-credits-in-sidebar'
  );
  const shouldHideCredits = sidebarCreditsVisibleExperiment.get(
    'hide-credits',
    false
  );

  const {
    data: subscriptionData,
    isLoading: isSubscriptionDataLoading,
    isFetched: isSubscriptionDataFetched,
  } = useSubscriptionInfo();

  const isSubscribed = subscriptionData?.is_active;
  const isPastDue = subscriptionData?.is_past_due;
  const isPremierPlan = subscriptionData?.plan?.plan_key === 'premier';

  const showAuraUpsellCard = !isSubscriptionDataLoading && !isSubscribed;

  const isSongPage = pathname.startsWith('/song/');

  // Add disclosure for ProfileEditModal
  const {
    isOpen: isProfileEditModalOpen,
    onOpen: onOpenProfileEditModal,
    onClose: onCloseProfileEditModal,
  } = useDisclosure();

  // Can't just pass ProfileRowButton directly because of observer(...)
  const handleEditProfile = useCallback(() => {
    logWebUserEvent(
      {
        actionName: 'ArtistProfileEditButtonClicked',
        context: {
          source: 'side-nav',
        },
      },
      session
    );
    onOpenProfileEditModal();
  }, [onOpenProfileEditModal, session]);

  const { openModal } = useModalContext();

  const handleOpenInviteFriend = useCallback(() => {
    logWebUserEvent({
      actionName: canGenerateSong(session)
        ? 'NavbarInviteFriendsButtonClicked'
        : 'NavbarInviteAndEarnButtonClicked',
    });
    setIsEarnCreditsOpen(false);
    openModal(ModalTypes.INVITE_FRIEND, 'SideNav');
  }, [session, openModal]);

  const handleOpenFeedback = useCallback(() => {
    logWebUserEvent({
      actionName: 'NavbarFeedbackButtonClicked',
    });
    openModal(ModalTypes.FEEDBACK_FORM);
  }, [openModal]);

  const renderProfileRow = useCallback<React.ComponentType<LoginBarChildProps>>(
    (loginBarChildProps) => (
      <ProfileRowButton {...loginBarChildProps} showTooltip={collapsed} />
    ),
    [collapsed]
  );

  let clerkRedirectOptions: Record<string, string> = {
    [REFERRER_PARAM]: pathname,
    [SIGNUP_SOURCE_PARAM]: getSignUpSource(pathname),
  };

  // TODO: Remove this once the experiment is over
  if (isInMobileSongPageV2Experiment && isSongPage) {
    clerkRedirectOptions = {
      ...clerkRedirectOptions,
      [SIGNUP_SOURCE_PARAM]: SIGNUP_SOURCE_VALUES.MOBILE_SONG_PAGE,
    };
  }

  // We can't rotate a background image using CSS, so we need to do it in JS.
  React.useEffect(() => {
    const rotateAuraImage = async () => {
      const img = new Image();
      img.crossOrigin = 'anonymous';
      img.src = 'https://cdn-o.suno.com/auras-v2/aura_vip.jpg';

      await new Promise((resolve) => {
        img.onload = resolve;
      });

      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      if (!ctx) return;

      // Set canvas dimensions to match the rotated image
      canvas.width = img.height;
      canvas.height = img.width;

      // Translate to center of canvas
      ctx.translate(canvas.width / 2, canvas.height / 2);

      // Rotate 270 degrees
      ctx.rotate(Math.PI * 1.5);

      // Draw the image centered
      ctx.drawImage(img, -img.width / 2, -img.height / 2);

      // Convert to data URL
      const dataUrl = canvas.toDataURL('image/png');
      setRotatedAuraUrl(dataUrl);
    };

    if (isVip) rotateAuraImage();
  }, [isVip]);

  const vipStyle: React.CSSProperties = useMemo(
    () => ({
      scrollbarWidth: 'none' as const,
      backgroundImage:
        collapsed || !rotatedAuraUrl
          ? undefined
          : `linear-gradient(to right, rgba(13, 8, 8, 1), rgba(13, 8, 8, 0.9) 120px, rgba(13, 8, 8, 0.5) 240px), url("${rotatedAuraUrl}")`,
      backgroundSize: '1200px 1200px',
      backgroundPosition: collapsed ? 'right top' : 'left top',
      backgroundRepeat: 'no-repeat',
    }),
    [collapsed, rotatedAuraUrl]
  );

  // Handle expand/collapse
  const handleToggle = () => {
    setCollapsed(!collapsed);
  };

  // Persist collapsed state changes so we restore them on next visit.
  React.useEffect(() => {
    if (collapsible && localStorageAvailable) {
      localStorage.setItem(SIDENAV_COLLAPSED_STORAGE_KEY, String(collapsed));
    }
  }, [collapsed, collapsible, localStorageAvailable]);

  return (
    <div
      className={clsx(
        'group/sidebar relative h-full',
        'flex flex-col gap-4 max-md:invisible',
        'bg-background-primary text-foreground-primary',
        'border-r border-border-secondary',
        collapsed ? 'overflow-hidden' : 'overflow-y-auto',
        className
      )}
      style={
        {
          '--sidebar-width': collapsed
            ? SIDENAV_COLLAPSED_WIDTH
            : SIDENAV_FULL_WIDTH,
          '--avatar-x-correction': SIDENAV_AVATAR_X_CORRECTION,
          minWidth: 'var(--sidebar-width)',
          maxWidth: 'var(--sidebar-width)',
          ...(isVip ? vipStyle : undefined),
        } as React.CSSProperties
      }
      data-collapsed={collapsed}
      data-show-content={!collapsed}
      {...restProps}
    >
      {collapsible && (
        <Button
          variant={ButtonVariant.Tertiary}
          shape={ButtonShape.Rounded}
          size={ButtonSize.Small}
          className='absolute top-[35px] right-4 z-10 h-8 w-8 p-1 transition-none group-data-[collapsed=true]/sidebar:left-1/2 group-data-[collapsed=true]/sidebar:-translate-x-1/2'
          onClick={handleToggle}
          active={false}
          iconClassName='w-[18px] h-[18px]'
          icon={collapsed ? ChevronRightIcon : ChevronLeftIcon}
        />
      )}
      <div className='flex h-[88px] flex-row justify-start p-4 pt-8'>
        <Logo
          delay={15000}
          className='h-auto w-full max-w-28 p-2 group-data-[show-content=false]/sidebar:invisible'
        />
      </div>
      <div
        style={
          {
            '--avatar-x-correction': SIDENAV_AVATAR_X_CORRECTION,
          } as React.CSSProperties
        }
        className={clsx(
          'flex min-h-14 flex-col items-stretch justify-center gap-1 px-4',
          isSignedIn && '-translate-x-(--avatar-x-correction)'
        )}
      >
        {!isLoaded ||
        !session.sessionIsLoaded ||
        (isSignedIn && !session.user) ? (
          collapsed ? null : ( // Hide during loading when collapsed
            // Show skeleton when expanded
            <div className='flex flex-row items-center justify-start gap-2'>
              <SkeletonBone className='h-9 w-9 rounded-full' />
              <div className='flex-1 group-data-[show-content=false]/sidebar:invisible'>
                <SkeletonBone className='h-3 w-3/4 rounded-md' />
              </div>
            </div>
          )
        ) : isSignedIn ? (
          <LoginBar
            onOpenEditProfile={handleEditProfile}
            menuPlacement='top-start'
            menuOffset={MENU_OFFSET}
            avatarButtonClassName='w-full'
          >
            {renderProfileRow}
          </LoginBar>
        ) : (
          <div>
            <Button
              className='max-w-full'
              variant={ButtonVariant.Primary}
              icon={LoginIcon}
              onClick={() => {
                logWebUserEvent({
                  actionName: 'SignInButtonClicked',
                });
                clerk.openSignIn({
                  withSignUp: true,
                  ...getClerkSignInRedirectProps(
                    pathname,
                    clerkRedirectOptions
                  ),
                });
              }}
            >
              <span className='group-data-[show-content=false]/sidebar:hidden'>
                {t('nav.signIn')}
              </span>
            </Button>
          </div>
        )}
      </div>
      <div className='flex flex-col gap-1 px-4'>
        <NavButton
          icon={HomeIcon}
          active={isActiveNavTab('home', pathname)}
          href='/'
          onClick={() => {
            if (isNotificationsPanelOpen) closeNotificationsPanel();
            logWebUserEvent({ actionName: 'NavbarHomeButtonClicked' });
          }}
          tooltipLabel={t('nav.home')}
          showTooltip={collapsed}
        >
          {t('nav.home')}
        </NavButton>
        <NavButton
          icon={CreateIcon}
          active={isActiveNavTab('create', pathname)}
          href='/create'
          onClick={(e) => {
            if (isNotificationsPanelOpen) closeNotificationsPanel();
            logWebUserEvent({ actionName: 'NavbarCreateButtonClicked' });
            if (!isSignedIn) {
              clerk.openSignIn({
                withSignUp: true,
                ...getClerkSignInRedirectProps('/create', clerkRedirectOptions),
              });
              e.preventDefault();
            }
            library.clearFilters();
          }}
          tooltipLabel={t('nav.create')}
          showTooltip={collapsed}
        >
          {t('nav.create')}
        </NavButton>
        <NavButton
          icon={StudioIcon}
          active={isActiveNavTab('studio', pathname)}
          href='/studio'
          onClick={(e) => {
            e.preventDefault();
            if (isNotificationsPanelOpen) closeNotificationsPanel();
            // logWebUserEvent({ actionName: 'NavbarCreateButtonClicked' });
            if (!isSignedIn) {
              clerk.openSignIn({
                withSignUp: true,
                ...getClerkSignInRedirectProps('/studio', clerkRedirectOptions),
              });
            } else if (!session.isSubLoaded) {
              // no-op
            } else if (!isFeatureEnabledForPlan(session, PlanFeature.Studio)) {
              menus.setCurrentUpsellFeature(FeatureKey.STUDIO);
              menus.openModal(ModalTypes.UPSELL_MODAL);
            } else {
              library.clearFilters();
              window.location.href = '/studio';
              logWebUserEvent({
                actionName: 'NavigatedToStudio',
                context: {
                  trigger: 'main_sidebar',
                },
              });
            }
          }}
          tooltipLabel={t('nav.studio')}
          showTooltip={collapsed}
        >
          {t('nav.studio')}
        </NavButton>
        <NavButton
          icon={LibraryIcon}
          href={session.flags?.['library-v2-page'] ? '/me/v2' : '/me'}
          active={isActiveNavTab('library', pathname)}
          data-testid='navbar-library-tab'
          onClick={(e: React.MouseEvent<HTMLAnchorElement>) => {
            if (isNotificationsPanelOpen) closeNotificationsPanel();
            logWebUserEvent({ actionName: 'NavbarLibraryButtonClicked' });
            if (!isSignedIn) {
              const redirectUrl = session.flags?.['library-v2-page']
                ? '/me/v2'
                : '/me';
              clerk.openSignIn({
                withSignUp: true,
                ...getClerkSignInRedirectProps(
                  redirectUrl,
                  clerkRedirectOptions
                ),
              });
              e.preventDefault();
            }
          }}
          tooltipLabel={t('nav.library')}
          showTooltip={collapsed}
        >
          {t('nav.library')}
        </NavButton>
        <NavButton
          icon={SearchIcon}
          href='/search'
          active={isActiveNavTab('search', pathname)}
          onClick={(e) => {
            if (isNotificationsPanelOpen) closeNotificationsPanel();
            logWebUserEvent({ actionName: 'NavbarSearchButtonClicked' });
            if (!isSignedIn) {
              clerk.openSignIn({
                withSignUp: true,
                ...getClerkSignInRedirectProps('/search', clerkRedirectOptions),
              });
              e.preventDefault();
            }
          }}
          tooltipLabel={t('nav.search')}
          showTooltip={collapsed}
        >
          {t('nav.search')}
        </NavButton>
        {hooksEnabled && (
          <div className='flex flex-row items-center justify-center gap-0'>
            <NavButton
              icon={HooksIcon}
              href='/hooks'
              active={isActiveNavTab('hooks', pathname)}
              onClick={(e) => {
                if (isNotificationsPanelOpen) closeNotificationsPanel();
                if (!isSignedIn) {
                  clerk.openSignIn({
                    withSignUp: true,
                    ...getClerkSignInRedirectProps(
                      '/hooks',
                      clerkRedirectOptions
                    ),
                  });
                  e.preventDefault();
                }
              }}
              tooltipLabel={t('nav.hooks')}
              showTooltip={collapsed}
            >
              {t('nav.hooks')}
            </NavButton>
            <Button
              icon={PlusIcon}
              size={ButtonSize.Micro}
              variant={ButtonVariant.Standard}
              shape={ButtonShape.Pill}
              href='/hooks/create'
              className='p-1.5 group-data-[show-content=false]/sidebar:hidden'
              onClick={() => {
                logHookWebGeneralEvent({
                  actionName: 'CreateHookClicked',
                  context: {
                    hookId: '',
                    recommendationItemId: '',
                    entryPoint: 'sidebar',
                  },
                });
              }}
            >
              Create
            </Button>
          </div>
        )}
        <NavButton
          icon={ExploreIcon}
          active={isActiveNavTab('explore', pathname)}
          href={'https://suno.com/explore'}
          onClick={() => {
            if (isNotificationsPanelOpen) closeNotificationsPanel();
            logWebUserEvent({ actionName: 'NavbarExploreButtonClicked' });
          }}
          tooltipLabel={t('nav.explore')}
          showTooltip={collapsed}
        >
          {t('nav.explore')}
        </NavButton>
        <NavButton
          icon={RadioBroadcastIcon}
          href='/live-radio'
          active={isActiveNavTab('live-radio', pathname)}
          onClick={() => {
            if (isNotificationsPanelOpen) closeNotificationsPanel();
            // logWebUserEvent({ actionName: 'NavbarLivingRadioButtonClicked' });
          }}
          tooltipLabel='Radio'
          showTooltip={collapsed}
        >
          Radio
        </NavButton>
        {isSunoverseEnabled && (
          <NavButton
            icon={StarIcon}
            href='/sunoverse'
            active={isActiveNavTab('sunoverse', pathname)}
            tooltipLabel='Sunoverse'
            showTooltip={collapsed}
          >
            Sunoverse
          </NavButton>
        )}
        {isSignedIn && (
          <MediaQueryOnly
            mediaQuery={`(min-width: ${TAILWIND_MEDIUM_MIN_WIDTH}px)`}
          >
            <NavButton
              icon={NotificationsIcon}
              href='/notifications'
              active={
                isActiveNavTab('notifications', pathname) ||
                isNotificationsPanelOpen
              }
              tooltipLabel={t('nav.notifications')}
              showTooltip={collapsed}
              className='group-data-[collapsed=true]/sidebar:relative'
              iconClassName='group-data-[collapsed=true]/sidebar:relative'
              iconEnd={
                notificationsStore.unreadCount > 0 ? (
                  <NotificationDot
                    className={clsx(
                      'animate-pop-in',
                      'group-data-[collapsed=true]/sidebar:w-1.5!',
                      'group-data-[collapsed=true]/sidebar:h-1.5!',
                      'group-data-[collapsed=true]/sidebar:absolute',
                      'group-data-[collapsed=true]/sidebar:top-0.5',
                      'group-data-[collapsed=true]/sidebar:left-[14px]',
                      'group-data-[collapsed=true]/sidebar:min-w-0!'
                    )}
                  >
                    <span className='group-data-[collapsed=true]/sidebar:hidden'>
                      {notificationsStore.unreadCount}
                    </span>
                  </NotificationDot>
                ) : undefined
              }
              onClick={(e) => {
                // Don't do something strange if when we're already on /notifications
                if (isActiveNavTab('notifications', pathname)) {
                  notificationsStore.loadNotifications();
                  return;
                }
                // Allow normal link behavior to open in a new tab
                if (e.ctrlKey || e.metaKey) {
                  return;
                }

                e.preventDefault();
                if (isNotificationsPanelOpen) {
                  // Do not mark as read if hodling shift key
                  if (!e.shiftKey) {
                    notificationsStore.markAllAsRead();
                  }
                  closeNotificationsPanel();
                  logWebUserEvent({
                    actionName: 'NotificationListClosed',
                    context: {
                      unreadCount: notificationsStore.unreadCount,
                      isMobile: false,
                    },
                  });
                } else {
                  notificationsStore.loadNotifications();
                  openNotificationsPanel();

                  logWebUserEvent({
                    actionName: 'NotificationListOpened',
                    context: {
                      unreadCount: notificationsStore.unreadCount,
                      isMobile: false,
                    },
                  });
                }
              }}
            >
              {t('nav.notifications')}
            </NavButton>

            <SideSubNav
              isOpen={isNotificationsPanelOpen}
              onClose={closeNotificationsPanel}
            />
          </MediaQueryOnly>
        )}
      </div>

      <div className='flex-1' />

      <div className='flex h-[12px] flex-col justify-center gap-2'>
        {isSignedIn && session.isCreditsLoaded && !shouldHideCredits ? (
          <div className='flex items-center justify-center gap-1'>
            <Link
              ref={numCreditsRef}
              href='/account'
              className='block text-center text-[14px] whitespace-pre text-foreground-inactive group-data-[show-content=false]/sidebar:text-[14px]'
            >
              <Trans
                t={t}
                i18nKey='account.numCredits'
                values={{
                  count: session.credits,
                  // We can fit five digits in the collapsed sidebar, so clamp to 100K+.
                  formattedCount:
                    collapsed && session.credits > 100000
                      ? '100K+'
                      : session.credits.toLocaleString(),
                }}
                components={{
                  span: collapsed ? (
                    <div className='text-foreground-secondary' />
                  ) : (
                    <span className='text-foreground-secondary' />
                  ),
                }}
              />
            </Link>
            {/* Debug info */}
            {showCreditsExpiringTooltip &&
              session.daysLeftInSubscription !== false && (
                <Tooltip
                  label={`${session.paidCreditsRemaining} credits expiring in ${typeof session.daysLeftInSubscription === 'number' && session.daysLeftInSubscription < 1 ? 'less than 1' : String(session.daysLeftInSubscription)} day${typeof session.daysLeftInSubscription === 'number' && session.daysLeftInSubscription <= 1 ? '' : 's'}`}
                  placement='top'
                >
                  <WarningIcon className='h-3 w-3 cursor-pointer text-accent-yellow-on-primary group-data-[show-content=false]/sidebar:h-2 group-data-[show-content=false]/sidebar:w-2'></WarningIcon>
                </Tooltip>
              )}
          </div>
        ) : null}
      </div>
      <div className='h-[156px] px-4'>
        {isSubscriptionDataLoading ||
        !isSubscriptionDataFetched ? null : showAuraUpsellCard ? (
          <UpsellCard
            className='group-data-[show-content=false]/sidebar:invisible'
            title={t('nav.goPro')}
            description={t('nav.goProDescription')}
            auraImage='https://cdn-o.suno.com/Aura-1-square.png'
            button={
              <Button
                variant={ButtonVariant.LightGlass}
                shape={ButtonShape.Pill}
                size={ButtonSize.Small}
                className='w-full bg-foreground-primary/10 text-foreground-primary'
                href='/account'
              >
                {t('nav.upgrade')}
              </Button>
            }
          />
        ) : (
          <Button
            variant={isPastDue ? ButtonVariant.Primary : ButtonVariant.Standard}
            shape={ButtonShape.Pill}
            size={ButtonSize.Small}
            icon={isPastDue ? WarningIcon : undefined}
            className={twMerge(
              'w-full group-data-[show-content=false]/sidebar:invisible',
              isPastDue &&
                'border-[0.5px] border-white bg-red-700/50 text-white hover:bg-red-700/60'
            )}
            href='/account'
          >
            {isPastDue
              ? 'Update payment'
              : isSubscribed
                ? isPremierPlan
                  ? t('nav.account')
                  : t('nav.upgrade')
                : t('nav.upgrade_to_pro')}
          </Button>
        )}
      </div>
      <div className='flex flex-col gap-1 px-4'>
        <Popover.Root
          open={isEarnCreditsOpen}
          onOpenChange={setIsEarnCreditsOpen}
        >
          <Popover.Trigger asChild>
            <NavButton
              icon={GiftIcon}
              tooltipLabel={t('nav.earnCredits')}
              showTooltip={collapsed}
              className={twMerge(
                NAV_BUTTON_HOVER_CLASSNAME,
                'translate-x-[3px] p-1'
              )}
            >
              {t('nav.earnCredits')}
            </NavButton>
          </Popover.Trigger>
          <Popover.Anchor />
          <Popover.Portal>
            <Popover.Content
              side='bottom'
              sideOffset={-3}
              className={clsx(
                'flex flex-col items-stretch justify-start gap-1 rounded-md border',
                'z-10 min-w-[160px] overflow-clip py-1',
                'md:box-shadow border-border-secondary bg-background-secondary text-foreground-secondary',
                'font-sans text-sm font-medium'
              )}
            >
              <button
                className='block cursor-pointer px-4 py-1 text-left text-current outline-0 hover:bg-background-secondary hover:text-foreground-primary focus:bg-background-secondary focus:text-foreground-primary'
                onClick={handleOpenInviteFriend}
              >
                {canGenerateSong(session)
                  ? t('nav.inviteFriends')
                  : t('nav.inviteAndEarn')}
              </button>
              {labelMakerEnabled && (
                <Link
                  href='/listen-and-rank'
                  className='block px-4 py-1 text-left outline-0 hover:bg-background-secondary hover:text-foreground-primary focus:bg-background-secondary focus:text-foreground-primary'
                  onClick={() => {
                    setIsEarnCreditsOpen(false);
                  }}
                >
                  {t('nav.listenAndRank')}
                </Link>
              )}
            </Popover.Content>
          </Popover.Portal>
        </Popover.Root>
        {changelogItems.length > 0 && (
          <NavButton
            icon={NewsIcon}
            onClick={(e) => {
              e.preventDefault();
              logWebUserEvent({ actionName: 'NavbarWhatsNewButtonClicked' });
              onOpenWhatsNew();
              updateChangelogLastViewed();
            }}
            iconEnd={
              unviewedChangelogItems.length ? (
                <div className='min-w-[24px] rounded-full bg-foreground-primary px-1 py-1 text-center font-sans text-xs font-bold text-background-primary group-data-[show-content=false]/sidebar:hidden'>
                  {unviewedChangelogItems.length}
                </div>
              ) : undefined
            }
            tooltipLabel={t('nav.whatsNew')}
            showTooltip={collapsed}
          >
            {t('nav.whatsNew')}
          </NavButton>
        )}
        <Popover.Root>
          <Popover.Trigger asChild>
            <NavButton
              icon={MoreVerticalIcon}
              tooltipLabel={t('nav.moreFromSuno')}
              showTooltip={collapsed}
              className={twMerge(
                NAV_BUTTON_HOVER_CLASSNAME,
                'translate-x-[3px] p-1'
              )}
              // Shift the menu icon to the right so it's centered with the icons above it.
            >
              {t('nav.moreFromSuno')}
            </NavButton>
          </Popover.Trigger>
          <Popover.Anchor />
          <Popover.Portal>
            <Popover.Content
              side='top'
              align='start'
              alignOffset={0}
              sideOffset={38} // Increased from 40 to 44 for a small additional push
              avoidCollisions={true}
              className={clsx(
                'flex flex-col items-stretch justify-start gap-1 rounded-md border',
                'z-10 min-w-[160px] overflow-clip py-1',
                'md:box-shadow border-border-secondary bg-background-secondary text-foreground-secondary',
                'font-sans text-sm font-medium',
                'translate-y-0'
              )}
            >
              <Link
                className='block px-4 py-1 outline-0 hover:bg-background-secondary hover:text-foreground-primary focus:bg-background-secondary focus:text-foreground-primary'
                href='https://help.suno.com'
              >
                {t('nav.help')}
              </Link>
              <Link
                className='block px-4 py-1 outline-0 hover:bg-background-secondary hover:text-foreground-primary focus:bg-background-secondary focus:text-foreground-primary'
                href='https://suno.com/about'
              >
                {t('nav.about')}
              </Link>
              <Link
                href='https://suno.com/blog'
                className='block px-4 py-1 outline-0 hover:bg-background-secondary hover:text-foreground-primary focus:bg-background-secondary focus:text-foreground-primary'
              >
                {t('nav.blog')}
              </Link>
              <Link
                className='block px-4 py-1 outline-0 hover:bg-background-secondary hover:text-foreground-primary focus:bg-background-secondary focus:text-foreground-primary'
                href='https://jobs.ashbyhq.com/suno'
              >
                {t('nav.careers')}
              </Link>
              {session.user && (
                <button
                  autoFocus={false}
                  className='block px-4 py-1 text-left outline-0 hover:bg-background-secondary hover:text-foreground-primary'
                  onClick={handleOpenFeedback}
                >
                  {t('nav.feedback')}
                </button>
              )}
            </Popover.Content>
          </Popover.Portal>
        </Popover.Root>
      </div>
      <div className='border-t border-border-secondary'>
        <SocialMediaBar
          className='py-4 group-data-[show-content=false]/sidebar:invisible'
          buttonVariant={ButtonVariant.Tertiary}
          buttonClassName={twMerge(NAV_BUTTON_HOVER_CLASSNAME, 'p-1')}
          buttonIconClassName='w-5 h-5 m-0'
        />
      </div>
      <ChangelogModal
        changelogItems={changelogItems || []}
        onClose={onCloseWhatsNew}
        isOpen={isWhatsNewOpen}
      />
      <ProfileEditModal
        isOpen={isProfileEditModalOpen}
        onClose={onCloseProfileEditModal}
        artistProfileInfo={session.artistProfileInfo}
        onArtistProfileInfoUpdate={(updatedInfo) => {
          session.updateArtistProfileInfo(updatedInfo);
        }}
        onSuccess={() => {
          // Profile updated successfully
        }}
      />
    </div>
  );
});

export default SideNav;
