// frontend/src/components/Header.tsx
'use client';
import React, {
  useEffect,
  useState,
  useCallback,
  useRef,
  CSSProperties,
} from 'react';
import ReactDOM from 'react-dom/client';
import LoginModal from './modal/Login';
import RegisterModal from './modal/Reg';
import ProfileModal from './modal/Profile';
import SettingsModal from './modal/Settings';

interface User {
  login: string;
  avatar: string;
}

/* helpers */
const readCookie = (n: string) => {
  const value = document.cookie
    .split('; ')
    .find((c) => c.startsWith(`${n}=`))
    ?.split('=')[1];
  
  // Декодируем URL-кодированное значение
  if (value) {
    try {
      return decodeURIComponent(value);
    } catch {
      return value;
    }
  }
  
  return null;
}

/* palette */
const ACCENT = 'rgb(240,140,50)';

/* static styles */
const stHeader: CSSProperties = {
  position: 'fixed',
  top: 0,
  left: 0,
  width: '100%',
  height: 56, // Увеличено для лучшей видимости
  background: 'linear-gradient(to bottom, #111111, #000000)',
  color: '#fff',
  padding: '0 20px',
  zIndex: 1000,
  display: 'flex',
  alignItems: 'center',
  boxShadow: '0 2px 15px rgba(0,0,0,0.5)',
};

const stLink: CSSProperties = {
  color: ACCENT,
  textDecoration: 'none',
  fontSize: 14,
  fontWeight: 'bold',
  transition: 'all .3s',
  padding: '5px 10px',
  borderRadius: 8,
  position: 'relative',
};

// Улучшенный стиль аватара пользователя
const stAvatarBase: CSSProperties = {
  marginLeft: 'auto',
  marginRight: 10,
  display: 'flex',
  alignItems: 'center',
  position: 'relative',
  cursor: 'pointer',
  borderRadius: 24,
  border: 0,
  padding: '6px 12px',
  userSelect: 'none',
  transition: 'all 0.3s',
  background: 'linear-gradient(145deg, #ff7f27, #ff5500)',
  boxShadow: '0 2px 10px rgba(255,127,39,0.4)',
};

// Улучшенный стиль меню пользователя
const stMenu: CSSProperties = {
  position: 'absolute',
  top: 46,
  right: 0,
  background: 'linear-gradient(145deg, #0a0a0a, #1a1a1a)',
  border: '1px solid #ff7f27',
  borderRadius: 12,
  padding: 6,
  boxShadow: '0 8px 20px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,127,39,0.2)',
  zIndex: 1000,
  minWidth: 160,
  animation: 'menuAppear 0.25s forwards',
  transformOrigin: 'top right',
};

// Улучшенный стиль кнопок меню
const stBtn: CSSProperties = {
  display: 'block',
  width: '100%',
  padding: '10px 16px',
  background: 'transparent',
  border: 0,
  textAlign: 'left',
  fontSize: 14,
  fontWeight: 'bold',
  color: ACCENT,
  cursor: 'pointer',
  transition: 'all 0.2s',
  borderRadius: 8,
  margin: '2px 0',
};

// Стили для анимаций
const styles = `
@keyframes menuAppear {
  from {
    opacity: 0;
    transform: scale(0.95);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes buttonGlow {
  0% {
    box-shadow: 0 2px 10px rgba(255,127,39,0.3);
  }
  50% {
    box-shadow: 0 2px 15px rgba(255,127,39,0.6);
  }
  100% {
    box-shadow: 0 2px 10px rgba(255,127,39,0.3);
  }
}

@keyframes linkPulse {
  0% {
    text-shadow: 0 0 3px rgba(255,127,39,0);
  }
  50% {
    text-shadow: 0 0 8px rgba(255,127,39,0.5);
  }
  100% {
    text-shadow: 0 0 3px rgba(255,127,39,0);
  }
}

@keyframes avatarGlow {
  0% {
    box-shadow: 0 2px 10px rgba(255,127,39,0.4);
  }
  50% {
    box-shadow: 0 2px 20px rgba(255,127,39,0.7);
  }
  100% {
    box-shadow: 0 2px 10px rgba(255,127,39,0.4);
  }
}
`;

// Улучшенный компонент кнопки меню
const MenuButton = ({ label, onClick }: { label: string; onClick?: () => void }) => {
  const [h, setH] = useState(false);
  return (
    <button
      style={{ 
        ...stBtn, 
        background: h ? 'rgba(255,127,39,0.15)' : 'transparent',
        transform: h ? 'translateX(5px)' : 'translateX(0)',
      }}
      onMouseEnter={() => setH(true)}
      onMouseLeave={() => setH(false)}
      onMouseDown={() => setH(false)}
      onMouseUp={() => setH(true)}
      onClick={onClick}
    >
      {label}
    </button>
  );
};

// Улучшенный компонент меню пользователя
function UserMenu({
  user,
  onLogout,
  onProfile,
  onSettings,
}: {
  user: User;
  onLogout: () => void;
  onProfile: () => void;
  onSettings: () => void;
}) {
  const [open, setOpen] = useState(false);
  const [tone, setTone] = useState<'idle' | 'hover' | 'active'>('idle');
  const ref = useRef<HTMLDivElement>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    const close = (e: globalThis.MouseEvent) =>
      ref.current && !ref.current.contains(e.target as Node) && setOpen(false);
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, []);

  const startHide = () => (timer.current = setTimeout(() => setOpen(false), 300));
  const stopHide = () => {
    if (timer.current) clearTimeout(timer.current);
  };

  const avatarStyle: CSSProperties = {
    height: 36, 
    width: 36, 
    borderRadius: '50%',
    border: '2px solid #000',
    objectFit: 'cover',
    boxShadow: '0 2px 5px rgba(0,0,0,0.3)',
    transition: 'transform 0.2s',
    transform: open ? 'scale(1.1)' : 'scale(1)',
  };

  const bg = tone === 'active' 
    ? 'linear-gradient(145deg, #e96c00, #cc5e00)'
    : tone === 'hover' 
      ? 'linear-gradient(145deg, #ff7f27, #e96c00)'
      : 'linear-gradient(145deg, #ff7f27, #ff5500)';

  const boxShadow = tone === 'hover' || open
    ? '0 4px 15px rgba(255,127,39,0.5)'
    : '0 2px 10px rgba(255,127,39,0.4)';

  return (
    <div
      ref={ref}
      style={{ 
        ...stAvatarBase, 
        background: bg,
        boxShadow: boxShadow,
        animation: tone === 'hover' ? 'avatarGlow 2s infinite' : 'none',
        transform: tone === 'hover' ? 'translateY(-1px)' : 'translateY(0)'
      }}
      onClick={() => setOpen((v) => !v)}
      onMouseEnter={() => setTone('hover')}
      onMouseLeave={() => setTone('idle')}
      onMouseDown={() => setTone('active')}
      onMouseUp={() => setTone('hover')}
    >
      <img src={user.avatar} alt="" style={avatarStyle} />
      <span style={{ 
        marginLeft: 12, 
        color: '#000', 
        fontWeight: 'bold',
        fontSize: 15,
        letterSpacing: '0.5px',
      }}>
        {user.login}
      </span>

      {open && (
        <div style={stMenu} onMouseEnter={stopHide} onMouseLeave={startHide}>
          <MenuButton label="Профиль" onClick={onProfile} />
          <MenuButton label="Настройки" onClick={onSettings} />
          <div style={{
            height: 1,
            background: 'linear-gradient(to right, transparent, rgba(255,127,39,0.5), transparent)',
            margin: '6px 0',
          }}></div>
          <MenuButton label="Выход" onClick={onLogout} />
        </div>
      )}
    </div>
  );
}

export default function Header() {
  const [user, setUser] = useState<User | null>(null);
  const [ready, setReady] = useState(false);

  /* cookies → state */
  useEffect(() => {
    const login = readCookie('login');
    const avatar = readCookie('avatar');
    if (login && avatar)
      setUser({
        login,
        avatar: avatar.replace(/\\\\/g, '/').replace(/"/g, ''),
      });
    setReady(true);
  }, []);

  /* live updates (аватар, логин) */
  useEffect(() => {
    const f = (e: Event) =>
      setUser((u) => (u ? { ...u, ...(e as CustomEvent).detail } : u));
    window.addEventListener('user-update', f);
    return () => window.removeEventListener('user-update', f);
  }, []);

  /* -------- modal helpers -------- */
const openPortal = (cmp: React.ReactElement) => {
    const host = document.createElement('div');
    document.body.appendChild(host);
    const root = ReactDOM.createRoot(host);
    const close = () => {
        root.unmount();
        host.remove();
    };
    root.render(cmp);
    return close;
};

  const openLoginModal = useCallback(() => {
    const close = openPortal(
      <LoginModal
        onSuccess={(u) => {
          setUser(u);
          window.dispatchEvent(new CustomEvent('user-update', { detail: u }));
        }}
        onClose={() => close()}
        onRegisterClick={() => {
          close(); // Закрываем окно логина
          openRegisterModal(); // Открываем окно регистрации
        }}
      />,
    );
    return close;
  }, []);

  const openRegisterModal = useCallback(() => {
    const close = openPortal(
      <RegisterModal
        onSuccess={(u) => {
          setUser(u);
          window.dispatchEvent(new CustomEvent('user-update', { detail: u }));
        }}
        onClose={() => close()}
        onLoginClick={() => {
          close(); // Закрываем окно регистрации
          openLoginModal(); // Открываем окно логина
        }}
      />,
    );
    return close;
  }, []);

  const openSettingsModal = useCallback(() => {
    if (!user) return;
    
    // Получаем id из cookie (removed unused userId variable)
      
    const close = openPortal(
      <SettingsModal
        user={{ login: user.login, full_name: '', avatar: user.avatar, email: '' }}
        onClose={() => close()}
        onUpdate={(patch) => setUser((u) => (u ? { ...u, ...patch } : u))}
      />,
    );
    return close; // Важно вернуть функцию закрытия!
  }, [user]);

  const openProfileModal = useCallback(() => {
    if (!user) return;
    
    // Получаем id из cookie
    // Removed unused userId variable assignment
      
    const close = openPortal(
      <ProfileModal
        user={{ login: user.login, full_name: '', avatar: user.avatar }}
        onClose={() => close()}
        onSettings={() => {
          close();
          openSettingsModal();
        }}
      />,
    );
    return close; // Важно вернуть функцию закрытия!
  }, [user, openSettingsModal]);

  const handleLogout = useCallback(async () => {
    await fetch('http://localhost:8000/logout', { method: 'POST', credentials: 'include' });
    ['login', 'avatar', 'full_name', 'email', 'id', 'JWT_token'].forEach(
      (n) => (document.cookie = `${n}=; Max-Age=0; path=/`),
    );
    setUser(null);
  }, []);

  if (!ready) return null;

  return (
    <header style={stHeader}>
      <style>{styles}</style>
      <img
        src="icon/logo.svg"
        alt="Logo"
        style={{ height: 36, marginRight: 12 }}
        onContextMenu={(e) => e.preventDefault()}
        onDragStart={(e) => e.preventDefault()}
      />

      <h1 style={{ 
        fontSize: 18, 
        margin: 0,
        fontWeight: 'bold',
        textShadow: '0 2px 10px rgba(255,127,39,0.3)',
        background: 'linear-gradient(to right, #ff7f27, #ff5500)',
        WebkitBackgroundClip: 'text',
        WebkitTextFillColor: 'transparent',
      }}>
        БИЛЕТопад
      </h1>

      <nav style={{ marginLeft: 20, display: 'flex', gap: 16 }}>
        {Object.entries({ Афиша: '/', 'О нас': '/about', Отзывы: '/feedback', Контакты: '/contacts' }).map(
          ([txt, href]) => (
            <a
              key={txt}
              href={href}
              style={stLink}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = 'rgba(255,127,39,0.1)';
                e.currentTarget.style.animation = 'linkPulse 2s infinite';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = 'transparent';
                e.currentTarget.style.animation = 'none';
              }}
              onContextMenu={(e) => e.preventDefault()}
            >
              {txt}
            </a>
          ),
        )}
      </nav>

      {user ? (
        <UserMenu
          user={user}
          onLogout={handleLogout}
          onProfile={openProfileModal}
          onSettings={openSettingsModal}
        />
      ) : (
        <button
          onClick={openLoginModal}
          style={{
            marginLeft: 'auto',
            marginRight: 10,
            background: 'linear-gradient(145deg, #ff7f27, #ff5500)', // Градиент вместо плоского цвета
            color: '#000',
            border: 0,
            borderRadius: 24,
            padding: '9px 16px',
            display: 'flex',
            alignItems: 'center',
            cursor: 'pointer',
            fontSize: 15,
            fontWeight: 'bold',
            transition: 'all 0.3s',
            boxShadow: '0 2px 10px rgba(255,127,39,0.3)',
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.background = 'linear-gradient(145deg, #ff7f27, #e96c00)';
            e.currentTarget.style.transform = 'translateY(-1px)';
            e.currentTarget.style.boxShadow = '0 4px 15px rgba(255,127,39,0.5)';
            e.currentTarget.style.animation = 'buttonGlow 2s infinite';
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.background = 'linear-gradient(145deg, #ff7f27, #ff5500)';
            e.currentTarget.style.transform = 'translateY(0)';
            e.currentTarget.style.boxShadow = '0 2px 10px rgba(255,127,39,0.3)';
            e.currentTarget.style.animation = 'none';
          }}
          onMouseDown={(e) => {
            e.currentTarget.style.background = 'linear-gradient(145deg, #e96c00, #cc5e00)';
            e.currentTarget.style.transform = 'translateY(0)';
            e.currentTarget.style.boxShadow = '0 2px 5px rgba(255,127,39,0.2)';
          }}
          onMouseUp={(e) => {
            e.currentTarget.style.background = 'linear-gradient(145deg, #ff7f27, #e96c00)';
            e.currentTarget.style.transform = 'translateY(-1px)';
            e.currentTarget.style.boxShadow = '0 4px 15px rgba(255,127,39,0.5)';
          }}
        >
          <img 
            src="icon/login.svg" 
            alt="" 
            style={{ 
              height: 24, 
              marginRight: 10, 
              filter: 'drop-shadow(0 1px 2px rgba(0,0,0,0.3))'  // Добавление тени для иконки
            }} 
          />
          Войти
        </button>
      )}
    </header>
  );
}
