import PropTypes from 'prop-types';
import { motion, AnimatePresence } from "framer-motion";
import { useTranslation } from "react-i18next";
import { useMemo, useState, useRef, useEffect } from 'react';
import { FiExternalLink, FiGithub, FiX, FiArrowRight, FiZap, FiCpu, FiLayers, FiSmartphone, FiCode, FiShoppingCart, FiBarChart2, FiGlobe, FiShield, FiFolder } from 'react-icons/fi';
import OptimizedImage from './OptimizedImage';
import GlassBackground from "./GlassBackground";

// Importaciones de imágenes
import image1 from "/1.webp";
import image2 from "/2.webp";
import image3 from "/3.webp";
import image4 from "/4.webp";
import image5 from "/5.webp";
import image7 from "/7.webp";
import image8 from "/8.webp";
import image9 from "/9.webp";
import image10 from "/10.webp";
import image11 from "/11.webp";
import image12 from "/12.webp";

// Categorías con iconos y colores
const categoryConfig = {
  'AI/ML': { Icon: FiCpu, textClass: 'text-violet-300 dark:text-violet-300 light:text-violet-700' },
  'IA/ML': { Icon: FiCpu, textClass: 'text-violet-300 dark:text-violet-300 light:text-violet-700' },
  'AI/Expert Systems': { Icon: FiLayers, textClass: 'text-indigo-300 dark:text-indigo-300 light:text-indigo-700' },
  'IA/Sistemas Expertos': { Icon: FiLayers, textClass: 'text-indigo-300 dark:text-indigo-300 light:text-indigo-700' },
  'Mobile/Backend': { Icon: FiSmartphone, textClass: 'text-emerald-300 dark:text-emerald-300 light:text-emerald-700' },
  'Móvil/Backend': { Icon: FiSmartphone, textClass: 'text-emerald-300 dark:text-emerald-300 light:text-emerald-700' },
  'Full Stack': { Icon: FiCode, textClass: 'text-sky-300 dark:text-sky-300 light:text-sky-700' },
  'E-commerce': { Icon: FiShoppingCart, textClass: 'text-amber-300 dark:text-amber-300 light:text-amber-700' },
  'Data Science': { Icon: FiBarChart2, textClass: 'text-pink-300 dark:text-pink-300 light:text-pink-700' },
  'Ciencia Datos': { Icon: FiBarChart2, textClass: 'text-pink-300 dark:text-pink-300 light:text-pink-700' },
  'Web App': { Icon: FiGlobe, textClass: 'text-cyan-300 dark:text-cyan-300 light:text-cyan-700' },
  'App Web': { Icon: FiGlobe, textClass: 'text-cyan-300 dark:text-cyan-300 light:text-cyan-700' },
  'Backend/Security': { Icon: FiShield, textClass: 'text-slate-300 dark:text-slate-300 light:text-slate-700' },
  'Backend/Seguridad': { Icon: FiShield, textClass: 'text-slate-300 dark:text-slate-300 light:text-slate-700' }
};

// Modal de proyecto expandido
const ProjectModal = ({ project, projectData, onClose, technologies }) => {
  const { t } = useTranslation();
  const hasResults = projectData.results && Array.isArray(projectData.results);
  const config = categoryConfig[projectData.category] || { Icon: FiFolder, textClass: 'text-adaptive' };
  const CategoryIcon = config.Icon;
  const closeButtonRef = useRef(null);
  const previouslyFocusedRef = useRef(null);

  useEffect(() => {
    const handleKeyDown = (e) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [onClose]);

  useEffect(() => {
    previouslyFocusedRef.current = document.activeElement;
    closeButtonRef.current?.focus?.();

    return () => {
      const previous = previouslyFocusedRef.current;
      if (previous && typeof previous.focus === "function") previous.focus();
    };
  }, []);

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 z-[10000] flex items-center justify-center p-4 md:p-8"
      onClick={onClose}
    >
      {/* Backdrop con blur */}
      <div className="absolute inset-0 bg-black/70 light:bg-black/35 backdrop-blur-md" aria-hidden="true" />
      
      {/* Contenido del modal */}
      <motion.div
        initial={{ scale: 0.9, y: 20, opacity: 0 }}
        animate={{ scale: 1, y: 0, opacity: 1 }}
        exit={{ scale: 0.95, y: 10, opacity: 0 }}
        transition={{ type: "spring", damping: 25, stiffness: 300 }}
        onClick={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        aria-label={projectData.title}
        className="relative w-full max-w-4xl max-h-[90vh] overflow-hidden glass border-0 rounded-3xl bg-black/75 dark:bg-black/75 light:bg-white/92 backdrop-blur-xl shadow-2xl shadow-black/40 dark:shadow-black/40 light:shadow-black/10 theme-transition"
      >
        <GlassBackground />
        {/* Botón cerrar */}
        <button
          ref={closeButtonRef}
          type="button"
          onClick={onClose}
          aria-label="Cerrar"
          className="absolute top-4 right-4 z-50 p-2 rounded-xl isolate overflow-hidden text-adaptive focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-400/30 bg-black/55 dark:bg-black/55 light:bg-white/85 backdrop-blur-xl shadow-md"
        >
          <FiX size={20} />
        </button>

        <div className="max-h-[90vh] overflow-y-auto overscroll-contain">
          {/* Imagen hero */}
          <div className="relative aspect-video w-full overflow-hidden">
            <OptimizedImage
              src={project.image}
              alt={projectData.title}
              className="absolute inset-0 w-full h-full"
              imgClassName="w-full h-full object-cover"
              sizes="(max-width: 768px) 100vw, 800px"
            />
            <div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/20 to-transparent dark:from-black/90 dark:via-black/20 light:from-white/90 light:via-white/25" />
            
            {/* Título sobre la imagen */}
            <div className="absolute bottom-0 left-0 right-0 p-6 md:p-8">
              <div className="flex items-center gap-3 mb-3">
                {projectData.category && (
                  <span className={`inline-flex items-center justify-center w-10 h-10 rounded-2xl bg-black/45 dark:bg-black/45 light:bg-white/70 backdrop-blur-md border border-white/10 light:border-black/10 ${config.textClass}`}>
                    <CategoryIcon className="w-5 h-5" />
                  </span>
                )}
                <span className="text-sm font-mono text-white/80 dark:text-white/80 light:text-slate-700">{project.year}</span>
              </div>
              <h2 className="text-2xl md:text-4xl font-bold text-white dark:text-white light:text-slate-900 mb-2">
                {projectData.title}
              </h2>
            </div>
          </div>

          {/* Contenido */}
          <div className="p-6 md:p-8 space-y-6">
            {/* Descripción */}
            <p className="text-adaptive-secondary text-lg leading-relaxed">
              {projectData.description}
            </p>

            {/* Resultados - Verde en dark mode */}
            {hasResults && (
              <div className="space-y-3">
                <h3 className="flex items-center gap-2 text-emerald-400 dark:text-emerald-400 light:text-emerald-700 font-semibold">
                  <FiZap className="text-emerald-400 dark:text-emerald-400 light:text-emerald-700" />
                  {t('projects.live.results') || 'Resultados Clave'}
                </h3>
                <div className="grid gap-2">
                  {projectData.results.map((result, idx) => (
                    <motion.div
                      key={idx}
                      initial={{ opacity: 0, x: -20 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ delay: idx * 0.1 }}
                      className="flex items-start gap-3 p-3 bg-emerald-500/10 dark:bg-emerald-500/10 light:bg-emerald-600/10 border border-emerald-500/20 dark:border-emerald-500/20 light:border-emerald-600/25 rounded-xl"
                    >
                      <span className="w-2 h-2 rounded-full bg-emerald-400 dark:bg-emerald-400 light:bg-emerald-700 mt-2 flex-shrink-0" />
                      <span className="text-emerald-200 dark:text-emerald-200 light:text-emerald-800">{result}</span>
                    </motion.div>
                  ))}
                </div>
              </div>
            )}

          {/* Tecnologías - Cyan/Azul en dark mode */}
          <div className="space-y-3">
            <h3 className="flex items-center gap-2 text-indigo-200 dark:text-indigo-200 light:text-indigo-700 font-semibold">
              <FiLayers className="text-indigo-200 dark:text-indigo-200 light:text-indigo-700" />
              {t('tech.title') || 'Tecnologías'}
            </h3>
            <div className="flex flex-wrap gap-2">
              {technologies.map((tech, idx) => (
                <motion.span
                  key={idx}
                  initial={{ opacity: 0, scale: 0.8 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{ delay: idx * 0.03 }}
                  className="px-3 py-1.5 text-sm glass-lite border border-indigo-400/25 dark:border-indigo-400/25 light:border-indigo-600/35 rounded-xl text-sky-200 dark:text-sky-200 light:text-sky-700"
                >
                  {tech}
                </motion.span>
              ))}
            </div>
          </div>

            {/* Botones de acción */}
            <div className="flex flex-wrap gap-3 pt-4 border-t border-slate-700/50">
              {project.demo && (
                <a
                  href={project.demo}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-2 px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-medium transition-all hover:scale-105"
                >
                  <FiExternalLink size={16} />
                  {t('projects.live.demo') || 'Ver Demo'}
                </a>
              )}
              {project.repo && (
                <a
                  href={project.repo}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-2 px-5 py-2.5 glass-lite border border-white/10 dark:border-white/10 light:border-black/10 rounded-xl font-medium transition-all hover:scale-105 text-adaptive"
                >
                  <FiGithub size={16} />
                  {t('projects.live.repo') || 'Código Fuente'}
                </a>
              )}
            </div>
          </div>
        </div>
      </motion.div>
    </motion.div>
  );
};

ProjectModal.propTypes = {
  project: PropTypes.object.isRequired,
  projectData: PropTypes.object.isRequired,
  onClose: PropTypes.func.isRequired,
  technologies: PropTypes.array.isRequired
};

// Tarjeta de proyecto interactiva con efectos
const ProjectCard = ({ project, displayIndex, onSelect }) => {
  const { t } = useTranslation();
  const [isHovered, setIsHovered] = useState(false);
  const cardRef = useRef(null);
  const [mousePosition, setMousePosition] = useState({ x: 50, y: 50 });

  const projectData = t(`projects.${project.i18nKey}`, { returnObjects: true });
  const category = projectData.category;
  const config = categoryConfig[category] || { Icon: FiFolder, textClass: 'text-adaptive' };
  const CategoryIcon = config.Icon;

  const handleMouseMove = (e) => {
    if (!cardRef.current) return;
    const rect = cardRef.current.getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width) * 100;
    const y = ((e.clientY - rect.top) / rect.height) * 100;
    setMousePosition({ x, y });
  };

  return (
    <motion.article
      ref={cardRef}
      initial={{ opacity: 0 }}
      whileInView={{ opacity: 1 }}
      viewport={{ once: true, margin: "-50px" }}
      transition={{ duration: 0.4, delay: displayIndex * 0.05 }}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      onMouseMove={handleMouseMove}
      onClick={() => onSelect(project)}
      className="group relative cursor-pointer"
    >
      <div
        className="glass border-0 relative isolate overflow-hidden rounded-3xl bg-black/60 dark:bg-black/60 light:bg-white/70 backdrop-blur-xl shadow-2xl shadow-black/25 dark:shadow-black/30 light:shadow-black/10 theme-transition transition-all duration-500 hover:shadow-indigo-500/15"
      >
        <GlassBackground />
        
        {/* Efecto de brillo siguiendo el mouse */}
        <div
          className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-500 pointer-events-none"
          style={{
            background: `radial-gradient(600px circle at ${mousePosition.x}% ${mousePosition.y}%, rgba(99, 102, 241, 0.09), transparent 42%)`
          }}
        />

        <div className="flex flex-col sm:flex-row">
          {/* Imagen con efectos */}
          <div className="relative w-full sm:w-64 md:w-72 flex-shrink-0 overflow-hidden">
            <div className="relative aspect-[16/10] sm:aspect-[4/3]">
              <OptimizedImage
                src={project.image}
                alt={projectData.title}
                className="absolute inset-0 w-full h-full"
                imgClassName="w-full h-full object-cover transition-all duration-700 group-hover:scale-110"
                sizes="(max-width: 640px) 100vw, 288px"
              />
              
              {/* Overlay gradiente */}
              <div className="absolute inset-0 bg-gradient-to-r from-transparent via-transparent to-black/70 dark:to-black/70 light:to-white/80 sm:block hidden" />
              <div className="absolute inset-0 bg-gradient-to-t from-black/55 dark:from-black/65 light:from-white/70 via-transparent to-transparent" />
              
              {/* Número flotante */}
              <motion.div 
                className="absolute top-3 left-3"
                animate={{ y: isHovered ? -2 : 0 }}
              >
                <span className="text-xs font-mono bg-black/50 dark:bg-black/50 light:bg-white/75 text-white/90 dark:text-white/90 light:text-slate-900 backdrop-blur-sm px-2.5 py-1 rounded-lg border border-white/10 dark:border-white/10 light:border-black/10">
                  {String(displayIndex + 1).padStart(2, '0')}
                </span>
              </motion.div>

              {/* Icono de categoría flotante con animación */}
              <motion.div 
                className={`absolute bottom-3 left-3 p-2 rounded-xl bg-black/45 dark:bg-black/45 light:bg-white/70 backdrop-blur-md border border-white/10 dark:border-white/10 light:border-black/10 ${config.textClass}`}
                animate={{ 
                  scale: isHovered ? 1.2 : 1,
                  rotate: isHovered ? [0, -10, 10, 0] : 0
                }}
                transition={{ duration: 0.4 }}
              >
                <CategoryIcon className="w-5 h-5" />
              </motion.div>
            </div>
          </div>

          {/* Contenido */}
          <div className="flex-1 p-5 flex flex-col justify-center min-w-0">
            {/* Meta info */}
            <div className="flex items-center gap-2 mb-2 text-xs">
              <span className="text-adaptive-muted font-mono">{project.year}</span>
              <span className="text-adaptive-muted">•</span>
              <span className="text-adaptive-secondary">{category}</span>
            </div>

            {/* Título */}
            <h3 className="text-lg md:text-xl font-bold text-adaptive mb-2 group-hover:text-indigo-200 dark:group-hover:text-indigo-200 light:group-hover:text-indigo-700 transition-colors duration-300 line-clamp-1">
              {projectData.title}
            </h3>

            {/* Descripción */}
            <p className="text-sm text-adaptive-secondary leading-relaxed mb-4 line-clamp-2">
              {projectData.description}
            </p>

            {/* Tags de tecnología - Cyan/Azul */}
            <div className="flex flex-wrap gap-1.5 mb-4">
              {(projectData.tech || project.technologies).slice(0, 4).map((tech, idx) => (
                <span
                  key={idx}
                  className="px-2 py-0.5 text-[10px] font-medium glass-lite border border-indigo-400/25 dark:border-indigo-400/25 light:border-indigo-600/35 rounded text-sky-200 dark:text-sky-200 light:text-sky-700"
                >
                  {tech}
                </span>
              ))}
              {(projectData.tech || project.technologies).length > 4 && (
                <span className="px-2 py-0.5 text-[10px] text-adaptive-muted">
                  +{(projectData.tech || project.technologies).length - 4}
                </span>
              )}
            </div>

            {/* CTA con animación */}
            <motion.div 
              className="flex items-center gap-2 text-sm text-indigo-200 dark:text-indigo-200 light:text-indigo-700 font-medium"
              animate={{ x: isHovered ? 5 : 0 }}
            >
              <span>{t('projects.viewDetails')}</span>
              <FiArrowRight className="transition-transform group-hover:translate-x-1" />
            </motion.div>
          </div>
        </div>

        {/* Barra de progreso decorativa animada */}
        <motion.div 
          className="absolute bottom-0 left-0 h-0.5 bg-indigo-500"
          initial={{ width: '0%' }}
          whileHover={{ width: '100%' }}
          transition={{ duration: 0.5 }}
        />
      </div>
    </motion.article>
  );
};

ProjectCard.propTypes = {
  project: PropTypes.object.isRequired,
  displayIndex: PropTypes.number.isRequired,
  onSelect: PropTypes.func.isRequired
};

// Datos de proyectos
const projectsData = [
  {
    i18nKey: "project1",
    year: 2024,
    image: image1,
    technologies: ["Python", "FastAPI", "YOLOv8", "React", "MongoDB", "WebSockets"],
    demo: "https://el-dorado-nu.vercel.app/",
    repo: "https://github.com/never130/ElDorado"
  },
  {
    i18nKey: "project2",
    year: 2025,
    image: image11,
    technologies: ["Flutter", "Express.js", "Firebase", "SMS Auth"],
    demo: null,
    repo: null
  },
  {
    i18nKey: "project3",
    year: 2024,
    image: image2,
    technologies: ["Node.js", "Express", "React", "MongoDB", "API Integration"],
    demo: "https://youtube.com/shorts/T8HjMw814Uk?feature=share",
    repo: null
  },
  {
    i18nKey: "project4",
    year: 2024,
    image: image4,
    technologies: ["React", "Node.js", "MercadoPago", "MongoDB"],
    demo: "https://tiendadelfuego2025.vercel.app",
    repo: "https://github.com/never130/tiendadelfuego2025"
  },
  {
    i18nKey: "project5",
    year: 2024,
    image: image5,
    technologies: ["Python", "Flask", "DecisionTree", "JSON", "Next.js", "Tailwind CSS"],
    demo: "https://politecnico-sistema-experto.vercel.app/",
    repo: "https://github.com/never130/Politecnico_Sistema_Experto"
  },
  {
    i18nKey: "project6",
    year: 2023,
    image: image3,
    technologies: ["React", "Weather API", "Local Storage", "Responsive Design"],
    demo: "https://miclimapp.netlify.app/#/current-location",
    repo: "https://github.com/never130/Climapp"
  },
  {
    i18nKey: "project7",
    year: 2023,
    image: image7,
    technologies: ["MongoDB", "React", "Chakra UI", "TailwindCSS", "CRUD"],
    demo: "https://proyecto1-tiendadelfuego.onrender.com/create",
    repo: "https://github.com/never130/proyecto-mern1"
  },
  {
    i18nKey: "project8",
    year: 2023,
    image: image8,
    technologies: ["Node.js", "JWT", "bcrypt", "Express", "Security"],
    demo: "https://php-login-register1.onrender.com",
    repo: "https://github.com/never130/php-login-register1"
  },
  {
    i18nKey: "project9",
    year: 2023,
    image: image9,
    technologies: ["React", "E-commerce", "Payment Integration", "MongoDB"],
    demo: "https://solomusica.netlify.app/",
    repo: "https://github.com/never130/proyecto-mern1"
  },
  {
    i18nKey: "project10",
    year: 2025,
    image: image12,
    technologies: ["React", "Vite", "TypeScript", "Tailwind", "Node.js", "Express", "MongoDB", "JWT Auth", "MercadoPago", "Cloudinary"],
    demo: "https://ecommerce-mates-bay.vercel.app/",
  },
  {
    i18nKey: "project11",
    year: 2025,
    image: image10,
    technologies: ["React 19", "Vite", "Tailwind CSS v4", "Framer Motion", "Three.js", "React Three Fiber", "Maath"],
    demo: "https://inteligencia-fueguina.vercel.app/",
    repo: null,
  },
];

const Projects = () => {
  const { t } = useTranslation();
  const [selectedProject, setSelectedProject] = useState(null);
  const [activeFilter, setActiveFilter] = useState('all');
  const scrollLockRef = useRef(null);

  const sortedProjects = useMemo(() => {
    return [...projectsData].sort((a, b) => {
      const yearDiff = (b.year ?? 0) - (a.year ?? 0);
      if (yearDiff !== 0) return yearDiff;
      return a.i18nKey.localeCompare(b.i18nKey);
    });
  }, []);

  // Extract unique categories from translated project data
  const categories = useMemo(() => {
    const cats = new Map();
    sortedProjects.forEach((project) => {
      const data = t(`projects.${project.i18nKey}`, { returnObjects: true });
      const cat = data.category;
      if (cat && !cats.has(cat)) {
        const config = categoryConfig[cat] || { Icon: FiFolder, textClass: 'text-adaptive' };
        cats.set(cat, config);
      }
    });
    return cats;
  }, [sortedProjects, t]);

  const filteredProjects = useMemo(() => {
    if (activeFilter === 'all') return sortedProjects;
    return sortedProjects.filter((project) => {
      const data = t(`projects.${project.i18nKey}`, { returnObjects: true });
      return data.category === activeFilter;
    });
  }, [sortedProjects, activeFilter, t]);

  const handleSelect = (project) => {
    setSelectedProject(project);
  };

  const handleClose = () => {
    setSelectedProject(null);
  };

  useEffect(() => {
    if (!selectedProject) return;

    const body = document.body;
    const previous = {
      overflow: body.style.overflow,
      paddingRight: body.style.paddingRight,
    };
    const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
    body.style.overflow = "hidden";
    if (scrollbarWidth > 0) body.style.paddingRight = `${scrollbarWidth}px`;
    scrollLockRef.current = previous;

    return () => {
      const prev = scrollLockRef.current;
      if (!prev) return;
      body.style.overflow = prev.overflow;
      body.style.paddingRight = prev.paddingRight;
      scrollLockRef.current = null;
    };
  }, [selectedProject]);

  const getProjectData = (project) => {
    return t(`projects.${project.i18nKey}`, { returnObjects: true });
  };

  const getTechnologies = (project) => {
    const data = getProjectData(project);
    return data.tech || project.technologies;
  };

  return (
    <>
      <section
        id="projects"
        className="section-container flex min-h-screen w-full flex-col items-center py-20 md:py-28 relative overflow-hidden"
        aria-label="Featured projects"
      >
        {/* Background decorativo sutil */}
        <div className="absolute inset-0 pointer-events-none">
          <div className="absolute top-1/4 -left-32 w-64 h-64 bg-blue-500/5 rounded-full blur-3xl" />
          <div className="absolute bottom-1/4 -right-32 w-64 h-64 bg-purple-500/5 rounded-full blur-3xl" />
        </div>

        <div className="relative w-full max-w-5xl mx-auto px-4 sm:px-6">
          {/* Header */}
          <motion.header
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ duration: 0.6 }}
            className="text-center mb-16"
          >
            {/* Badge contador */}
            <motion.div 
              className="inline-flex items-center gap-2 px-4 py-2 glass-lite border border-indigo-400/25 dark:border-indigo-400/25 light:border-indigo-600/35 rounded-full text-indigo-200 dark:text-indigo-200 light:text-indigo-700 text-sm font-medium mb-6"
              initial={{ opacity: 0, scale: 0.9 }}
              whileInView={{ opacity: 1, scale: 1 }}
              viewport={{ once: true }}
              transition={{ delay: 0.2 }}
            >
              <span className="relative flex h-2 w-2">
                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>
                <span className="relative inline-flex rounded-full h-2 w-2 bg-indigo-500"></span>
              </span>
              {filteredProjects.length} {t('projects.count') || 'Proyectos'}
            </motion.div>

            <h2 className="text-3xl sm:text-4xl md:text-5xl font-semibold text-indigo-200 dark:text-indigo-200 light:text-indigo-700 mb-4 tracking-tight">
              {t("projects.title")}
            </h2>
            <p className="text-adaptive-secondary text-base md:text-lg max-w-2xl mx-auto leading-relaxed">
              {t("projects.subtitle")}
            </p>
          </motion.header>

          {/* Category filter tabs */}
          <motion.div
            initial={{ opacity: 0, y: 15 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ delay: 0.3, duration: 0.5 }}
            className="flex flex-wrap justify-center gap-2 mb-10"
            role="tablist"
            aria-label="Filter projects by category"
          >
            <button
              role="tab"
              aria-selected={activeFilter === 'all'}
              onClick={() => setActiveFilter('all')}
              className={`px-4 py-2 rounded-xl text-sm font-medium transition-all duration-300 ${
                activeFilter === 'all'
                  ? 'bg-indigo-600 text-white shadow-lg shadow-indigo-500/25'
                  : 'glass-ultra-lite text-adaptive-secondary hover:text-adaptive border border-transparent hover:border-white/10 dark:hover:border-white/10 light:hover:border-black/10'
              }`}
            >
              {t('projects.filterAll')}
            </button>
            {[...categories.entries()].map(([cat, config]) => {
              const CatIcon = config.Icon;
              return (
                <button
                  key={cat}
                  role="tab"
                  aria-selected={activeFilter === cat}
                  onClick={() => setActiveFilter(cat)}
                  className={`inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-sm font-medium transition-all duration-300 ${
                    activeFilter === cat
                      ? 'bg-indigo-600 text-white shadow-lg shadow-indigo-500/25'
                      : 'glass-ultra-lite text-adaptive-secondary hover:text-adaptive border border-transparent hover:border-white/10 dark:hover:border-white/10 light:hover:border-black/10'
                  }`}
                >
                  <CatIcon className="w-3.5 h-3.5" />
                  {cat}
                </button>
              );
            })}
          </motion.div>

          {/* Lista de proyectos */}
          <motion.div
            key={activeFilter}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.3 }}
            className="space-y-5"
          >
            {filteredProjects.length > 0 ? (
              filteredProjects.map((project, index) => (
                <ProjectCard
                  key={project.i18nKey}
                  project={project}
                  displayIndex={index}
                  onSelect={handleSelect}
                />
              ))
            ) : (
              <p className="text-center text-adaptive-muted py-16">
                No projects in this category.
              </p>
            )}
          </motion.div>
        </div>
      </section>

      {/* Modal */}
      <AnimatePresence>
        {selectedProject && (
          <ProjectModal
            project={selectedProject}
            projectData={getProjectData(selectedProject)}
            technologies={getTechnologies(selectedProject)}
            onClose={handleClose}
          />
        )}
      </AnimatePresence>
    </>
  );
};

export default Projects;
