import React, { useState, useEffect } from 'react';
import './Header.css';
import logo from '../assets/logo.png';
import { useUser } from '../context/UserContext';
import { BookOpen } from '@icon-park/react';  // 导入图标组件

const Header = () => {
  const [currentPath, setCurrentPath] = useState(window.location.pathname);
  const { user } = useUser();

  const navLinks = [
    { to: '/friend-moments', label: '好友动态' },
    { to: '/forum', label: '论坛' },
    { to: '/interest-groups', label: '兴趣小组' },
    { to: '/seed-list', label: '种子列表' },
    { to: '/publish-seed', label: '发布种子' },
  ];

  useEffect(() => {
    const handleLocationChange = () => {
      setCurrentPath(window.location.pathname);
    };
    window.addEventListener('popstate', handleLocationChange);
    return () => {
      window.removeEventListener('popstate', handleLocationChange);
    };
  }, []);

  const isActive = (path) => currentPath.startsWith(path);

  const handleLinkClick = (to) => {
    window.history.pushState({}, '', to);
    setCurrentPath(to);
  };

  return (
    <div className="main-page">
      <header className="header">
        <div className="logo-and-name">
          <img src={logo} alt="网站 logo" className="logo" />
          <span className="site-name">Echo</span>
        </div>
        <div className="user-and-message" style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          {/* 新手指南图标，放在头像左边 */}
        <button
          className="guide-button"
          onClick={() => handleLinkClick('/new-user-guide')}
          title="新手指南"
        >
          <BookOpen theme="outline" size="20" fill="#fff" />
          <span style={{ marginLeft: '6px' }}>新手指南</span>
        </button>


          <a href="/user/profile">
            <img
              src={user?.avatarUrl}
              alt="用户头像"
              className="user-avatar"
            />
          </a>
          <span
            className="message-center"
            onClick={() => handleLinkClick('/messages')}
            style={{ cursor: 'pointer' }}
          >
            消息
          </span>
        </div>
      </header>

      <nav className="nav">
        {navLinks.map(({ to, label }) => (
          <a
            key={to}
            href={to}
            onClick={(e) => {
              e.preventDefault();
              handleLinkClick(to);
            }}
            className={`nav-item ${isActive(to) ? 'active' : ''}`}
          >
            {label}
          </a>
        ))}
      </nav>
    </div>
  );
};

export default Header;
