// resources\assets\ts\DataPage\Menubar.tsx
import '../share/qrPopup';
import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import Dialog from '@mui/material/Dialog';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import Toolbar from '@mui/material/Toolbar';
import Tooltip from '@mui/material/Tooltip';
import CloseIcon from '@mui/icons-material/Close';
import InfoIcon from '@mui/icons-material/Info';
import { RootState } from './rootReducer';
import { Trans, t } from '@lingui/macro';
import { i18n } from '@lingui/core';
import { setMenubarHeight } from './styleSlice';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import I18nProvider from 'B/I18nProvider';
import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import MenuIcon from '@mui/icons-material/Menu';
import { Visibility, VisibilityOff, KeyboardArrowDown } from '@mui/icons-material';
import UserAvatar from '../Zeiterfassung/components/UserAvatar';

const appBarStyles = {
  appBarName: {
    fontWeight: 'bold',
    fontSize: '1.25rem',
    fontFamily: 'Arial, sans-serif',
    color: '#000 !important',
    display: 'flex',
    alignItems: 'center',
    gap: '0.5rem',
    textDecoration: 'none',
  },
  tightIconBtn: {
    padding: 0,
    marginLeft: 8,
  },
  colorDefault: {
    backgroundColor: '#eee',
  },
};

const navIndicatorColor = 'var(--Google-Blau, rgba(0,153,255,1))';
const defaultIconStyle: React.CSSProperties = {
  height: '2.1rem',
  width: 'auto',
  maxWidth: '2.4rem',
  objectFit: 'contain',
};

const mobileBreakpoint = 1200;

type PermissionKey =
  | 'showMonitor'
  | 'showCalendar'
  | 'showDataview'
  | 'showConfig'
  | 'showUseredit'
  | 'showSystem'
  | 'showMobileConfig'
  | 'showContacts'
  | 'showDownload'
  | 'showBhb'
  | 'showLoRaWan'
  | 'showZeiterfassung'
  | 'showMap';

type UserAuth = Partial<
  Record<PermissionKey, boolean> & {
    vorname: string;
    name: string;
    photoUrl: string | null;
  }
>;

type NavItemConfig = {
  path: string;
  icon: string;
  title: string;
  alt: string;
  permission: PermissionKey;
  label?: string;
  iconStyle?: React.CSSProperties;
};

const NavContainer = styled.nav`
  display: flex;
  align-items: center;
  gap: 0.3rem;
  flex-wrap: wrap;

  @media (max-width: ${mobileBreakpoint}px) {
    display: none;
  }
`;

const NavItem = styled.a<{ $active?: boolean }>`
  width: 3.75rem;
  height: 3.75rem;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  border-radius: 0.75rem;
  text-decoration: none;
  color: ${({ $active }) => ($active ? '#111827' : '#6b7280')};
  transition:
    color 0.2s ease,
    transform 0.2s ease;
  font-size: 0;

  &:hover {
    transform: scale(1.04);
  }

  &::after {
    content: '';
    position: absolute;
    left: 22%;
    right: 22%;
    bottom: 0.3rem;
    height: 3px;
    border-radius: 999px;
    background-color: ${navIndicatorColor};
    opacity: ${({ $active }) => ($active ? 1 : 0)};
    transform: ${({ $active }) => ($active ? 'scaleX(1)' : 'scaleX(0.6)')};
    transition:
      opacity 0.2s ease,
      transform 0.2s ease;
  }
`;

type BerStatus = {
  orange: boolean;
  red: boolean;
  totalUsed: number;
  licenseLimit: number;
};

const getTabLabel = (path: string) => {
  switch (path) {
    case '/monitor':
      return i18n._(t`Monitor`);
    case '/lorawan':
      return 'LoRaWan';
    case '/calendar':
      return i18n._(t`Kalender`);
    case '/stats':
      return i18n._(t`Datenansicht`);
    case '/config':
      return i18n._(t`Konfiguration`);
    case '/useradmin':
      return i18n._(t`Benutzerverwaltung`);
    case '/system':
      return i18n._(t`System Einstellungen`);
    case '/mobile':
      return i18n._(t`Mobilgeräte`);
    case '/contacts':
      return i18n._(t`Adressen`);
    case '/download':
      return i18n._(t`Download`);
    case '/bhb':
      return i18n._(t`Dokumente`);
    case '/zeiterfassung':
      return i18n._(t`Zeiterfassung`);
    default:
      return '';
  }
};

export default function MenuBar() {
  const d = useDispatch();
  const auth = useSelector((state: RootState) => state.auth, shallowEqual);
  const userAuth: UserAuth = ((window as any)?.userAuth ?? {}) as UserAuth;
  const userFirstName = (userAuth?.vorname ?? '').trim();
  const userLastName = (userAuth?.name ?? '').trim();
  const userDisplayName =
    [userFirstName, userLastName].filter(Boolean).join(' ').trim() || 'Tasko';
  const userPhotoUrl = (userAuth as any)?.photoUrl ?? null;
  const authPermissions = auth as Partial<Record<PermissionKey, boolean>>;
  const globalPermissions = userAuth as Partial<Record<PermissionKey, boolean>>;
  const hasPermission = (permission: PermissionKey) =>
    Boolean(authPermissions?.[permission] ?? globalPermissions?.[permission]);

   const currentPath = window.location.pathname;
  // const [activeTab, setActiveTab] = useState(window.location.pathname);

//-- CMS prototype fix menubar not showing active tab for contacts subpages, should still work for config and system 

  // Check if we're on sub-routes that should highlight parent tab
  const isConfig = currentPath === '/config' || currentPath.startsWith('/config/');
  const isSystem = currentPath === '/system' || currentPath.startsWith('/system/');
  const isContacts = currentPath === '/contacts' || currentPath.startsWith('/contacts/');
  
  // Helper function to get the base path for matching nav items
  const getBasePath = (path: string) => {
    if (isContacts) return '/contacts';
    if (isConfig) return '/config';
    if (isSystem) return '/system';
    return path;
  };
  
  const [activeTab, setActiveTab] = useState(getBasePath(currentPath));
  const [tabLabel, setTabLabel] = useState(getTabLabel(getBasePath(currentPath)));


  // const [tabLabel, setTabLabel] = useState(getTabLabel(currentPath));
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const mobileMenuRef = useRef<HTMLDivElement | null>(null);

  // aktueller Node-Typ wenn config ausgewählt ist
  const [nodeType, setNodeType] = useState<string | null>(
    (window as any).currentConfigSelection?.type ?? null,
  );

  // --- NEU: BerStatus (Lizenz-/Datenpunktstatus) ---
  const [berStatus, setBerStatus] = useState<BerStatus | null>(null);
  const [showRedModal, setShowRedModal] = useState(false);
  const [showOrangeModal, setShowOrangeModal] = useState(false);

  useEffect(() => {
    const handler = (ev: Event) => {
      const detail = (ev as CustomEvent)?.detail as
        | { type?: string }
        | undefined;
      if (detail?.type) setNodeType(detail.type);
    };
    window.addEventListener('config:nodetype', handler);
    return () => window.removeEventListener('config:nodetype', handler);
  }, []);

  useEffect(() => {
    let isMounted = true;
    const fetchStatus = async () => {
      try {
        const res = await fetch('/getBerStatus', {
          credentials: 'same-origin',
        });
        if (!res.ok) return;
        const data = (await res.json()) as Partial<BerStatus>;
        if (isMounted) {
          setBerStatus({
            orange: !!data.orange,
            red: !!data.red,
            totalUsed: Number(data.totalUsed ?? 0),
            licenseLimit: Number(data.licenseLimit ?? 0),
          });
        }
      } catch (e) {}
    };

    fetchStatus();
    const interval = window.setInterval(fetchStatus, 60_000 * 5); // alle 5 Minuten
    return () => {
      isMounted = false;
      window.clearInterval(interval);
    };
  }, []);

  const helpTopicMap: Record<string, string> = {
    '/home': '1.20',
    '/monitor': '10.0',
    '/calendar': '8.0',
    '/stats': '3.0',
    '/config': '2.0',
    '/useradmin': '5.0',
    '/system': '6.0',
    '/mobile': '7.0',
    '/contacts': '12.0',
    '/download': '9.0',
    '/bhb': '50.1',
    '/lorawan': '6.8',
    '/zeiterfassung': '11.0',
  };

  const typeHelpTopicMap: Record<string, string> = {
    GRP: '2.2',
    pdf: '2.20',
    mob: '2.20',
    xls: '2.20',
    DEX: '2.21',
    INF: '2.40',
    WTG: '2.5',
    MWT: '2.6',
    VBG: '2.7',
    RWG: '2.75',
    BEM: '2.78',
    STT: '2.79',
    STR: '2.8',
    MLD: '2.81',
    BST: '2.9',
    LGC: '2.91',
    DYN: '2.92',
    CST: '2.93',
    MIP: '2.93',
  };

   //CMS prototype: shifted above
  // const isConfig =
  //   currentPath === '/config' || currentPath.startsWith('/config/');
  // const isSystem =
  //   currentPath === '/system' || currentPath.startsWith('/system/');

  const topicId = isConfig
    ? (nodeType && typeHelpTopicMap[nodeType]) || '2.1'
    : helpTopicMap[currentPath] || '1.20';

  const menubar = React.useCallback(
    (node) => {
      if (node === null) return;
      d(setMenubarHeight(node.clientHeight));
    },
    [d],
  );

  const handleTabChange = (path, label) => {
    setActiveTab(path);
    setTabLabel(label);
    setMobileMenuOpen(false);
  };

  const toggleMobileMenu = () => {
    setMobileMenuOpen(!mobileMenuOpen);
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        mobileMenuRef.current &&
        !mobileMenuRef.current.contains(event.target as Node)
      ) {
        setMobileMenuOpen(false);
      }
    };

    if (mobileMenuOpen) {
      document.addEventListener('click', handleClickOutside, true);
    }

    return () => {
      document.removeEventListener('click', handleClickOutside, true);
    };
  }, [mobileMenuOpen]);

  const navItems: NavItemConfig[] = [
    {
      path: '/monitor',
      icon: '/icon8/dash128.png',
      title: i18n._(t`Aufgaben Monitor`),
      alt: 'Monitor',
      permission: 'showMonitor',
    },
    {
      path: '/calendar',
      icon: '/icon8/calendar128.png',
      title: i18n._(t`Kalender`),
      alt: 'Kalender',
      permission: 'showCalendar',
    },
    {
      path: '/stats',
      icon: '/icon8/daten128.png',
      title: i18n._(t`Datenansicht`),
      alt: 'Datenansicht',
      permission: 'showDataview',
    },
    {
      path: '/config',
      icon: '/icon8/config128.png',
      title: i18n._(t`Konfiguration`),
      alt: 'Konfiguration',
      permission: 'showConfig',
    },
    {
      path: '/useradmin',
      icon: '/icon8/user128.png',
      title: i18n._(t`Benutzerverwaltung`),
      alt: 'Benutzerverwaltung',
      permission: 'showUseredit',
    },
    {
      path: '/system',
      icon: '/icon8/system128.png',
      title: i18n._(t`System Einstellungen`),
      alt: 'System Einstellungen',
      permission: 'showSystem',
    },
    {
      path: '/mobile',
      icon: '/icon8/mobile128.png',
      title: i18n._(t`Mobilgeräte`),
      alt: 'Mobilgeräte',
      permission: 'showMobileConfig',
    },
    {
      path: '/contacts',
      icon: '/icon8/contact128.png',
      title: i18n._(t`Adressen`),
      alt: 'Adressen',
      permission: 'showContacts',
    },
    {
      path: '/download',
      icon: '/icon8/folder128.png',
      title: i18n._(t`Download`),
      alt: 'Download',
      permission: 'showDownload',
    },
    {
      path: '/bhb',
      icon: '/icon8/bhb128.png',
      title: i18n._(t`Dokumente`),
      alt: 'Dokumente',
      permission: 'showBhb',
    },
    {
      path: '/lorawan',
      icon: '/icon8/lora128.png',
      title: 'LoRaWan',
      alt: 'LoRaWan',
      permission: 'showLoRaWan',
      label: 'LoRaWan',
    },
    {
      path: '/zeiterfassung',
      icon: '/icon8/Zeiterfassung.png',
      title: i18n._(t`Zeiterfassung`),
      alt: 'Zeiterfassung',
      permission: 'showZeiterfassung',
    },
  ];

  const limitIcon =
    isConfig || isSystem
      ? berStatus?.red
        ? {
            src: '/icon8/reachedLimit.png',
            title: 'Datenpunktlimit erreicht',
            onClick: () => setShowRedModal(true),
          }
        : berStatus?.orange
          ? {
              src: '/icon8/lesslimit.png',
              title: 'Datenpunktlimit fast erreicht',
              onClick: () => setShowOrangeModal(true),
            }
          : null
      : null;

  return (
    <>
      <AppBar
        style={{ height: '64px', padding: '0.5rem 1rem' }}
        ref={menubar}
        position='static'
        elevation={0}
        sx={appBarStyles.colorDefault}
        data-menubar-root='true'
      >
        <Toolbar variant='dense' disableGutters>
          {/* Home Button */}
          <IconButton
            edge='start'
            color='inherit'
            aria-label='home'
            href={'/home'}
            disableRipple
            disableFocusRipple
            style={{ backgroundColor: 'transparent' }}
            size='large'
          >
            <img
              src='/icon8/user/Home.svg'
              alt='Home'
              style={{ width: '24px', height: '24px' }}
            />
            <div style={{ marginLeft: '1rem' }}></div>
            <Box component='span' sx={appBarStyles.appBarName}>
              {userDisplayName}
            </Box>
          </IconButton>

          <NavContainer>
            {navItems
              .filter((item) => hasPermission(item.permission))
              .map((item) => {
                const label = item.label ?? getTabLabel(item.path);
                const isActive = activeTab === item.path;
                const iconStyle = {
                  ...defaultIconStyle,
                  ...(item.iconStyle ?? {}),
                };
                return (
                  <NavItem
                    key={item.path}
                    href={item.path}
                    $active={isActive}
                    onClick={() => handleTabChange(item.path, label)}
                  >
                    <img
                      src={item.icon}
                      title={item.title}
                      alt={item.alt}
                      style={iconStyle}
                    />
                  </NavItem>
                );
              })}
          </NavContainer>

          {/* Mobile Menu Button */}
          <div style={{ position: 'relative' }} ref={mobileMenuRef}>
            <MobileMenuButton
              aria-label='menu'
              onClick={toggleMobileMenu}
              size='large'
            >
              <MenuIcon />
            </MobileMenuButton>

            {mobileMenuOpen && (
              <MobileNavMenu>
                {navItems
                  .filter((item) => hasPermission(item.permission))
                  .map((item, index) => {
                    const label = item.label ?? getTabLabel(item.path);
                    const isActive = activeTab === item.path;
                    return (
                      <React.Fragment key={item.path}>
                        <a
                          className={`nav-menu-item ${isActive ? 'active' : ''}`}
                          href={item.path}
                          onClick={() => handleTabChange(item.path, label)}
                        >
                          <img src={item.icon} alt={item.alt} />
                          <span>{label}</span>
                        </a>
                        {index <
                          navItems.filter((i) => hasPermission(i.permission))
                            .length -
                            1 && <div className='dropdown-divider' />}
                      </React.Fragment>
                    );
                  })}
              </MobileNavMenu>
            )}
          </div>

          <div style={{ marginRight: 'auto' }}></div>

          {/* Titel + (NEU) Limit-Icon */}
          <Box component='span' sx={appBarStyles.appBarName}>
            {tabLabel}
            {limitIcon && (
              <Tooltip title={limitIcon.title}>
                <IconButton
                  sx={appBarStyles.tightIconBtn}
                  onClick={limitIcon.onClick}
                  aria-label='license-limit'
                >
                  <img
                    className='ikon statusbar_icon'
                    src={limitIcon.src}
                    alt='limit-status'
                    style={{ width: 24, height: 24 }}
                  />
                </IconButton>
              </Tooltip>
            )}
          </Box>

          <div style={{ marginLeft: 'auto' }}></div>

          <HelpButton topicId={topicId} />
          <Dropdown
            userFirstName={userFirstName}
            userLastName={userLastName}
            userDisplayName={userDisplayName}
            userPhotoUrl={userPhotoUrl}
          />
        </Toolbar>
      </AppBar>

      <Dialog open={showRedModal} onClose={() => setShowRedModal(false)}
              sx={{ '& .MuiDialog-container': { alignItems: 'flex-start' } }}>
        <DialogTitle>
          Limit erreicht
          <IconButton
              aria-label='close'
              onClick={() => setShowRedModal(false)}
              sx={{ position: 'absolute', right: 8, top: 8 }}
          >
            <CloseIcon/>
          </IconButton>
        </DialogTitle>
        <DialogContent dividers>
          <p>
            Es wurden {berStatus?.totalUsed ?? 0} von{' '}
            {berStatus?.licenseLimit ?? 0} Datenpunkten verbraucht.
          </p>
          <p>Das Datenpunktlimit wurde erreicht.</p>
        </DialogContent>
      </Dialog>

      <Dialog open={showOrangeModal} onClose={() => setShowOrangeModal(false)}
              sx={{ '& .MuiDialog-container': { alignItems: 'flex-start' } }}>
        <DialogTitle>
          Fast am Limit
          <IconButton
              aria-label='close'
              onClick={() => setShowOrangeModal(false)}
              sx={{ position: 'absolute', right: 8, top: 8 }}
          >
            <CloseIcon/>
          </IconButton>
        </DialogTitle>
        <DialogContent dividers>
          <p>
            Es wurden {berStatus?.totalUsed ?? 0} von{' '}
            {berStatus?.licenseLimit ?? 0} Datenpunkten verbraucht.
          </p>
          <p>Das Datenpunktlimit ist fast erreicht.</p>
        </DialogContent>
      </Dialog>
    </>
  );
}

const HelpButton = ({ topicId }) => {
  const handleHelpClick = () => {
    const helpLink = `/help/${encodeURIComponent(topicId)}.pdf`;
    window.open(
      helpLink,
      'Tasko Hilfe',
      [
        'height=630',
        'width=800',
        'location=no',
        'resizable=no',
        'scrollbars=yes',
        'status=no',
        'titlebar=no',
      ].join(','),
    );
  };

  return (
    <Tooltip title={i18n._(t`Hilfe`)}>
      <IconButton color='inherit' onClick={handleHelpClick} size='large'>
        <img
          src='/icon8/user/Frage_clue.svg'
          alt={i18n._(t`Hilfe`)}
          style={{ width: 24, height: 24 }}
        />
      </IconButton>
    </Tooltip>
  );
};

// Neue DropDown-Komponente
type DropdownProps = {
  userFirstName: string;
  userLastName: string;
  userDisplayName: string;
  userPhotoUrl: string | null;
};

const Dropdown = ({ userFirstName, userLastName, userDisplayName, userPhotoUrl }: DropdownProps) => {
  const userInitials = ((userFirstName[0] || '') + (userLastName[0] || '')).toUpperCase() || userDisplayName.substring(0, 2).toUpperCase();
  const [logoSrc, setLogoSrc] = useState('/imgtasko/tasko_logo.png'); // Default logo
  const { ref, isComponentVisible, setIsComponentVisible } =
    useComponentVisible(false);
  const [loginInfoEnabled, setLoginInfoEnabled] = useState(false);

  useEffect(() => {
    const checkLogoExists = async () => {
      try {
        const response = await fetch('/api/check-logo');
        const result = await response.json();

        if (result.exists) {
          setLogoSrc(`data:image/png;base64,${result.logoBase64}`);
        }
      } catch (error) {
        console.error('Error fetching logo:', error);
      }
    };

    checkLogoExists();
  }, []);


   useEffect(() => {
    const handler = () => {
      // Re-read the updated value from window.userAuth
      setLoginInfoEnabled(false);
      return;
    };
    window.addEventListener("userAuthUpdated", handler);
    return () => {
      window.removeEventListener("userAuthUpdated", handler);
    };
  }, []);


  useEffect(() => {
    const rawHideUntil = (window as any)?.userAuth?.hideRemotePopupUntil;
    if (!rawHideUntil) {
      setLoginInfoEnabled(true);
      return;
    }
    const parsed = new Date(rawHideUntil);
    if (Number.isNaN(parsed.getTime())) {
      setLoginInfoEnabled(true);
      return;
    }
    setLoginInfoEnabled(parsed <= new Date());
  }, []);

  const handleLoginInfoToggle = async () => {
    const unChecked = !loginInfoEnabled;
    setLoginInfoEnabled(unChecked);
    const csrfToken = $('meta[name="csrf-token"]').attr('content');
    const url = unChecked 
    ? '/users/showremotepopup' 
    : '/users/hideremotepopup';
    
    try {
      const res = await fetch(url, {
        method: 'POST',
        headers: {
          'X-CSRF-TOKEN': csrfToken,
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: '{}',
      });
      if (!res.ok) {
        setLoginInfoEnabled(!unChecked);
      }
    } catch (error) {
      console.error('Error toggling login info:', error);
      setLoginInfoEnabled(!unChecked);
    }
  };

  const toggleMenu = () => {
    setIsComponentVisible(!isComponentVisible);
  };

  return (
    <div>
      <I18nProvider>
        <IconButton
          onClick={toggleMenu}
          size='large'
          aria-label={userDisplayName}
          aria-haspopup='true'
          aria-expanded={isComponentVisible}
          sx={{
            display: 'flex',
            alignItems: 'center',
            gap: '4px',
            borderRadius: '24px',
            padding: '4px 8px 4px 4px',
            transition: 'transform 0.2s ease',
            '&:hover': {
              transform: 'scale(1.05)',
              backgroundColor: 'rgba(0, 0, 0, 0.04)',
            },
          }}
        >
          <UserAvatar
            photoUrl={userPhotoUrl}
            initials={userInitials}
            fullName={userDisplayName}
            sx={{
              width: 32,
              height: 32,
              fontSize: '0.8125rem',
              boxShadow: '0 0 0 2px rgba(0, 0, 0, 0.08)',
            }}
          />
          <KeyboardArrowDown
            sx={{ fontSize: 18, color: '#6c757d' }}
          />
        </IconButton>

        {isComponentVisible && (
          <StyledDropDownMenu ref={ref}>
            <div style={{ textAlign: 'center', margin: '0 15% 1rem' }}>
              <img
                src={logoSrc}
                alt='logo'
                style={{ maxHeight: 60, maxWidth: '100%' }}
              />
            </div>
            <div className='dropdown-divider' />
            <div className='dropdown-item' style={{ display: 'flex', alignItems: 'center', cursor: 'default' }}>
              <UserAvatar
                photoUrl={userPhotoUrl}
                initials={userInitials}
                fullName={userDisplayName}
                sx={{
                  width: 24,
                  height: 24,
                  fontSize: '0.6875rem',
                  marginRight: '12px',
                }}
              />
              {userFirstName || userDisplayName}
            </div>
            <div className='dropdown-divider' />
            <a className='dropdown-item' href='/users/kontact'>
              <img
                src='/icon8/user/Support.svg'
                style={{ width: 20, height: 20, marginRight: 20 }}
              />
              <Trans>Kontakt</Trans>
            </a>
            <div className='dropdown-divider' />
            <a className='dropdown-item' href='/users/changePWD'>
              <img
                src='/icon8/user/Passwort.svg'
                style={{ width: 20, height: 20, marginRight: 20 }}
              />
              <Trans>Passwort</Trans>
            </a>
            <div className='dropdown-divider' />
            <a
              className='dropdown-item'
              onClick={() => {
                (window as any).openQrPopup();
                setIsComponentVisible(false);
              }}
              style={{
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
              }}
            >
              <img
                src='/icon8/user/qrcode.svg'
                style={{ width: 20, height: 20, marginRight: 20 }}
              />
              <Trans>App verbinden</Trans>
            </a>
            <div className='dropdown-divider' />
            <label
                className='dropdown-item'
                onClick={handleLoginInfoToggle}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  cursor: 'pointer',
                  gap: 8,
                }}
              >
                <InfoIcon style={{ width: 20, height: 20, marginRight: 12 }} />

                <span style={{ flex: 1 }}>
                  <Trans>Login Info</Trans>
                </span>

                <span
                  style={{
                    width: 20,
                    height: 20,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  {loginInfoEnabled ? <Visibility /> : <VisibilityOff />}
                </span>
              </label>
            <div className='dropdown-divider' />
            <a className='dropdown-item text-danger' href='/logout'>
              <img
                src='/icon8/user/Abmelden.svg'
                style={{ width: 20, height: 20, marginRight: 20 }}
              />
              <Trans>Abmelden</Trans>
            </a>
          </StyledDropDownMenu>
        )}
      </I18nProvider>
    </div>
  );
};

const StyledDropDownMenu = styled.div`
  display: block;
  right: 0;
  left: auto;
  position: absolute;
  top: 100%;
  z-index: 1000;
  float: left;
  min-width: 220px;
  padding: 10px;
  font-size: 1rem;
  color: #212529;
  background-color: #fff;
  border-radius: 15px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  animation: dropdownFadeIn 0.15s ease-out;

  @keyframes dropdownFadeIn {
    from {
      opacity: 0;
      transform: translateY(-4px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }

  .dropdown-item {
    display: block;
    width: 100%;
    padding: 0.5rem;
    clear: both;
    font-weight: 400;
    color: #212529;
    text-align: inherit;
    background-color: transparent;
    text-decoration: none;
    transition: background-color 0.3s ease;
  }

  .dropdown-item:hover {
    background-color: #f8f9fa;
  }

  .dropdown-divider {
    height: 1px;
    margin: 0.5rem 0;
    overflow: hidden;
    background-color: #e9ecef;
  }
`;

const MobileMenuButton = styled(IconButton)`
  display: none !important;
  color: #000 !important;

  svg {
    color: inherit;
  }

  @media (max-width: ${mobileBreakpoint}px) {
    display: flex !important;
  }
`;

const MobileNavMenu = styled.div`
  display: block;
  right: -40px;
  left: auto;
  position: absolute;
  top: 100%;
  z-index: 1000;
  min-width: 280px;
  max-height: 80vh;
  overflow-y: auto;
  padding: 10px;
  font-size: 1rem;
  color: #212529;
  background-color: #fff;
  border-radius: 15px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);

  .nav-menu-item {
    display: flex;
    align-items: center;
    width: 100%;
    padding: 0.75rem;
    clear: both;
    font-weight: 400;
    color: #212529;
    text-decoration: none;
    background-color: transparent;
    border-radius: 8px;
    transition: background-color 0.3s ease;
    gap: 1rem;

    &.active {
      background-color: #e3f2fd;
      color: ${navIndicatorColor};
    }

    &:hover {
      background-color: #f8f9fa;
    }

    img {
      width: 32px;
      height: 32px;
      object-fit: contain;
    }

    span {
      font-size: 1rem;
    }
  }

  .dropdown-divider {
    height: 1px;
    margin: 0.5rem 0;
    overflow: hidden;
    background-color: #e9ecef;
  }
`;

function useComponentVisible(initialIsVisible) {
  const [isComponentVisible, setIsComponentVisible] =
    useState(initialIsVisible);
  const ref = useRef<HTMLDivElement | null>(null);

  const handleClickOutside = (event) => {
    if (ref.current && !ref.current.contains(event.target as Node)) {
      setIsComponentVisible(false);
    }
  };

  useEffect(() => {
    document.addEventListener('click', handleClickOutside, true);
    return () => {
      document.removeEventListener('click', handleClickOutside, true);
    };
  });

  return { ref, isComponentVisible, setIsComponentVisible };
}
