import React, { useState, useEffect } from 'react';
import './ProjectsSection.css';

function ProjectsSection({ projects }) {
  const [hoveredIndex, setHoveredIndex] = useState(null);
  const [isAdmin, setIsAdmin] = useState(false);
  const [currentPage, setCurrentPage] = useState(0);
  const [category, setCategory] = useState('all'); // 'all', 'develop', 'deploy'
  const [itemsPerPage, setItemsPerPage] = useState(15); // 默认桌面端 3行 × 5列 = 15个项目

  useEffect(() => {
    // 检查 URL 参数
    const urlParams = new URLSearchParams(window.location.search);
    const token = urlParams.get('token');
    const pathname = window.location.pathname;
    
    // 检查是否为 /admin 路径且 token 正确
    if (pathname.includes('/admin') && token === 'shumengya520') {
      setIsAdmin(true);
    }

    // 根据屏幕宽度设置每页显示数量
    const updateItemsPerPage = () => {
      if (window.innerWidth <= 768) {
        setItemsPerPage(8); // 移动端：4行 × 2列 = 8个项目
      } else {
        setItemsPerPage(15); // 桌面端：3行 × 5列 = 15个项目
      }
    };

    updateItemsPerPage();
    window.addEventListener('resize', updateItemsPerPage);

    return () => window.removeEventListener('resize', updateItemsPerPage);
  }, []);

  // 优先使用 cf-favicon API，失败时 onError 会切到 project.icon 或通用图标
  const getProjectIconUrl = (link) => {
    try {
      new URL(link);
      return `https://cf-favicon.pages.dev/api/favicon?url=${encodeURIComponent(link)}`;
    } catch {
      return 'https://api.iconify.design/mdi:web.svg';
    }
  };

  const handleProjectIconError = (e, project) => {
    const isApiUrl = e.target.src && e.target.src.includes('cf-favicon.pages.dev');
    if (isApiUrl && project.icon) {
      e.target.src = project.icon;
    } else {
      e.target.src = 'https://api.iconify.design/mdi:web.svg';
    }
  };

  // 过滤项目
  // 1. 如果 show 为 false,则不显示
  // 2. 如果 admin 为 true 且不是管理员模式,则不显示
  // 3. 根据分类过滤
  const filteredProjects = projects.filter(project => {
    // 首先检查 show 字段,如果为 false 则直接不显示
    if (project.show === false) {
      return false;
    }
    
    // 然后检查 admin 权限
    if (project.admin === true && !isAdmin) {
      return false; // 隐藏需要 admin 权限的项目
    }
    
    // 根据分类过滤
    if (category === 'develop' && project.develop !== true) {
      return false; // 只显示自制项目
    }
    if (category === 'deploy' && project.develop !== false) {
      return false; // 只显示自部署项目
    }
    
    return true; // 显示其他所有项目
  });

  // 计算总页数
  const totalPages = Math.ceil(filteredProjects.length / itemsPerPage);
  
  // 获取当前页的项目
  const startIndex = currentPage * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const currentPageProjects = filteredProjects.slice(startIndex, endIndex);

  // 处理分页点击
  const handlePageClick = (pageIndex) => {
    setCurrentPage(pageIndex);
    // 滚动到项目区域顶部
    window.scrollTo({
      top: document.querySelector('.projects-section').offsetTop - 20,
      behavior: 'smooth'
    });
  };

  // 处理分类切换
  const handleCategoryChange = (newCategory) => {
    setCategory(newCategory);
    setCurrentPage(0); // 切换分类时重置到第一页
  };

  return (
    <section className="projects-section">
      <div className="section-header">
        <h2 className="section-title">
          <span className="title-icon">🎯</span>
          全部项目
        </h2>

        {/* 分类按钮 */}
        <div className="category-buttons">
          <button
            className={`category-btn ${category === 'all' ? 'active' : ''}`}
            onClick={() => handleCategoryChange('all')}
          >
            全部项目
          </button>
          <button
            className={`category-btn ${category === 'develop' ? 'active' : ''}`}
            onClick={() => handleCategoryChange('develop')}
          >
            自制项目
          </button>
          <button
            className={`category-btn ${category === 'deploy' ? 'active' : ''}`}
            onClick={() => handleCategoryChange('deploy')}
          >
            自部署项目
          </button>
        </div>
      </div>
      
      <div className="projects-grid">
        {currentPageProjects.map((project, index) => {
          const globalIndex = startIndex + index;
          return (
            <a
              key={globalIndex}
              href={project.link}
              target="_blank"
              rel="noopener noreferrer"
              className={`project-card ${hoveredIndex === globalIndex ? 'hovered' : ''}`}
              onMouseEnter={() => setHoveredIndex(globalIndex)}
              onMouseLeave={() => setHoveredIndex(null)}
            >
            {project.develop === true && (
              <div className="develop-badge" title="独立开发">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M13.7803 3.03039L20.4697 9.71982C21.0508 10.3009 21.0508 11.2451 20.4697 11.8262L11.8262 20.4697C11.2451 21.0508 10.3009 21.0508 9.71982 20.4697L3.03039 13.7803C2.44928 13.1992 2.44928 12.255 3.03039 11.6739L11.6739 3.03039C12.255 2.44928 13.1992 2.44928 13.7803 3.03039Z" fill="currentColor"/>
                  <path d="M5 20L9 16L13 20L9 24L5 20Z" fill="currentColor"/>
                </svg>
              </div>
            )}
            <div className="project-header">
              <div className="project-icon">
                <img
                  src={getProjectIconUrl(project.link)}
                  alt={project.title}
                  onError={(e) => handleProjectIconError(e, project)}
                />
              </div>
              <h3 className="project-title">{project.title}</h3>
            </div>
            
            <p className="project-description">{project.description}</p>
            
            {project.tags && project.tags.length > 0 && (
              <div className="project-tags">
                {project.tags.map((tag, index) => (
                  <span key={index} className="project-tag">{tag}</span>
                ))}
              </div>
            )}
            
            </a>
          );
        })}
      </div>
      
      {/* 分页指示器 */}
      {totalPages > 1 && (
        <div className="pagination-dots">
          {Array.from({ length: totalPages }, (_, index) => (
            <button
              key={index}
              className={`pagination-dot ${currentPage === index ? 'active' : ''}`}
              onClick={() => handlePageClick(index)}
              aria-label={`跳转到第 ${index + 1} 页`}
            />
          ))}
        </div>
      )}
    </section>
  );
}

export default ProjectsSection;
