import React, { useState, useEffect, useMemo } from 'react';
import { useLocation } from 'react-router-dom';
import {
  ADMIN_TOKEN_KEY,
  getFaviconUrlForSite,
  getTechstackIconUrl,
  techBadgeSurfaceStyle,
} from '../api';
import './ProjectsSection.css';

function normTag(s) {
  return String(s || '').trim().toLowerCase();
}

/** 分类标签：按文案稳定哈希选色，同一标签全局颜色一致 */
const CATEGORY_TAG_PALETTE = [
  { background: 'rgba(255, 236, 230, 0.95)', color: '#6b3d38', borderColor: 'rgba(232, 137, 122, 0.45)' },
  { background: 'rgba(219, 234, 254, 0.95)', color: '#1e3a8a', borderColor: 'rgba(59, 130, 246, 0.4)' },
  { background: 'rgba(254, 243, 199, 0.95)', color: '#78350f', borderColor: 'rgba(245, 158, 11, 0.45)' },
  { background: 'rgba(243, 232, 255, 0.95)', color: '#581c87', borderColor: 'rgba(168, 85, 247, 0.4)' },
  { background: 'rgba(255, 228, 230, 0.95)', color: '#881337', borderColor: 'rgba(244, 63, 94, 0.4)' },
  { background: 'rgba(224, 242, 254, 0.95)', color: '#0c4a6e', borderColor: 'rgba(14, 165, 233, 0.4)' },
  { background: 'rgba(237, 233, 254, 0.95)', color: '#4c1d95', borderColor: 'rgba(139, 92, 246, 0.4)' },
  { background: 'rgba(254, 249, 195, 0.95)', color: '#713f12', borderColor: 'rgba(234, 179, 8, 0.45)' },
  { background: 'rgba(209, 250, 229, 0.95)', color: '#064e3b', borderColor: 'rgba(16, 185, 129, 0.4)' },
  { background: 'rgba(255, 237, 213, 0.95)', color: '#7c2d12', borderColor: 'rgba(249, 115, 22, 0.4)' },
  { background: 'rgba(224, 231, 255, 0.95)', color: '#312e81', borderColor: 'rgba(99, 102, 241, 0.4)' },
  { background: 'rgba(252, 231, 243, 0.95)', color: '#831843', borderColor: 'rgba(236, 72, 153, 0.4)' },
  { background: 'rgba(204, 251, 241, 0.95)', color: '#134e4a', borderColor: 'rgba(20, 184, 166, 0.4)' },
  { background: 'rgba(254, 240, 138, 0.75)', color: '#422006', borderColor: 'rgba(202, 138, 4, 0.45)' },
  { background: 'rgba(233, 213, 255, 0.95)', color: '#4a044e', borderColor: 'rgba(192, 38, 211, 0.35)' },
];

function hashTagString(s) {
  const str = String(s);
  let h = 2166136261;
  for (let i = 0; i < str.length; i += 1) {
    h ^= str.charCodeAt(i);
    h = Math.imul(h, 16777619);
  }
  return Math.abs(h);
}

function categoryTagStyle(tag) {
  const idx = hashTagString(tag) % CATEGORY_TAG_PALETTE.length;
  return CATEGORY_TAG_PALETTE[idx];
}

function ProjectsSection({ projects, techStackItems = [] }) {
  const location = useLocation();

  const techByNormName = useMemo(() => {
    const m = new Map();
    for (const item of techStackItems) {
      const k = normTag(item.name);
      if (k) m.set(k, item);
    }
    return m;
  }, [techStackItems]);

  const techNameSet = useMemo(() => new Set(techByNormName.keys()), [techByNormName]);

  const tagIsTech = (tag) => techNameSet.has(normTag(tag));

  const resolveTechItem = (name) => techByNormName.get(normTag(name));

  const [hoveredIndex, setHoveredIndex] = useState(null);
  const [isAdmin, setIsAdmin] = useState(() => !!sessionStorage.getItem(ADMIN_TOKEN_KEY));
  const [currentPage, setCurrentPage] = useState(0);
  const [category, setCategory] = useState('all'); // 'all', 'develop', 'deploy'
  const [itemsPerPage, setItemsPerPage] = useState(12); // 默认桌面端 3行 × 4列 = 12个项目

  useEffect(() => {
    setIsAdmin(!!sessionStorage.getItem(ADMIN_TOKEN_KEY));
  }, [location.key, location.pathname]);

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

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

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

  // 优先使用 favicon.smyhub.com，失败时 onError 会切到 project.icon 或通用图标
  const getProjectIconUrl = (link) => {
    try {
      new URL(link);
      return getFaviconUrlForSite(link);
    } catch {
      return 'https://api.iconify.design/mdi:web.svg';
    }
  };

  const handleProjectIconError = (e, project) => {
    const img = e.currentTarget;
    if (!img) return;
    const isApiUrl = img.src && img.src.includes('favicon.smyhub.com');
    if (isApiUrl && project.icon) {
      img.src = project.icon;
    } else {
      img.src = 'https://api.iconify.design/mdi:web.svg';
    }
  };

  const handleTechIconError = (e) => {
    const img = e.currentTarget;
    if (img) img.style.visibility = 'hidden';
  };

  const renderTechIcon = (name, key) => {
    const item = resolveTechItem(name);
    const iconUrl = item ? getTechstackIconUrl(item) : null;
    const paint = item?.color || '#64748b';
    if (item && iconUrl) {
      return (
        <span
          key={key}
          className="project-tech-icon"
          style={techBadgeSurfaceStyle(paint)}
          title={item.name}
        >
          <img src={iconUrl} alt="" loading="lazy" onError={handleTechIconError} />
        </span>
      );
    }
    return null;
  };

  const techNamesForProject = (project) => {
    const useLegacy = project.techTags === undefined && techNameSet.size > 0;
    return useLegacy
      ? (project.tags || []).filter((t) => tagIsTech(t))
      : project.techTags || [];
  };

  const renderTechRow = (project) => (
    <div className="project-tech-icons">
      {techNamesForProject(project).map((n, i) => renderTechIcon(n, `t-${i}`))}
    </div>
  );

  // 过滤项目
  // 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); // 切换分类时重置到第一页
  };

  const categoryTagsForProject = (project) => {
    const useLegacy = project.techTags === undefined && techNameSet.size > 0;
    if (useLegacy) {
      return (project.tags || []).filter((t) => !tagIsTech(t));
    }
    return project.tags || [];
  };

  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)}
            >
            <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>
            
            {renderTechRow(project)}
            <div className="project-tags">
              {categoryTagsForProject(project).map((tag, index) => {
                const cs = categoryTagStyle(tag);
                return (
                  <span
                    key={`c-${index}`}
                    className="project-tag project-tag--category"
                    style={{
                      background: cs.background,
                      color: cs.color,
                      borderColor: cs.borderColor,
                    }}
                  >
                    {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;
