// ============ PROJECTS GRID + MODAL ============
const { useState: useStateP } = React;

function ProjectCard({ p, onOpen }) {
  const ref = React.useRef(null);
  const onMove = (e) => {
    const el = ref.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const px = (e.clientX - r.left) / r.width - 0.5;
    const py = (e.clientY - r.top) / r.height - 0.5;
    el.style.transform = `perspective(900px) rotateX(${-py * 4}deg) rotateY(${px * 6}deg) translateZ(0)`;
  };
  const onLeave = () => { if (ref.current) ref.current.style.transform = ''; };

  return (
    <div ref={ref} className={`proj-card glass ${p.featured ? 'featured' : ''}`}
         onMouseMove={onMove} onMouseLeave={onLeave} onClick={() => onOpen(p)} role="button" tabIndex={0}
         onKeyDown={(e) => e.key === 'Enter' && onOpen(p)}>
      <div className={`proj-thumb ${p.img ? '' : 'generative'}`}>
        <div className="browser-bar">
          <span className="dot" style={{background:'#ff5f57'}} />
          <span className="dot" style={{background:'#febc2e'}} />
          <span className="dot" style={{background:'#28c840'}} />
          <span className="url">{p.id}.angelo.dev</span>
        </div>
        {p.img
          ? <img src={p.img} alt={p.name} loading="lazy" />
          : <window.ProjectCover p={p} />}
      </div>
      <div className="proj-body">
        <div className="row1">
          <h3>{p.name}</h3>
          <span className="type">{p.type}</span>
        </div>
        <p>{p.desc}</p>
        <div className="proj-tags">
          {p.stack.map((s, i) => <span key={i} className="proj-tag">{s}</span>)}
        </div>
      </div>
    </div>
  );
}

function ProjectModal({ p, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [onClose]);
  return (
    <div className="modal-bd" onClick={onClose} role="dialog" aria-modal="true">
      <div className="modal glass-strong" onClick={(e) => e.stopPropagation()} style={{position:'relative'}}>
        <button className="modal-close" onClick={onClose} aria-label="Cerrar">✕</button>
        <span className="kicker">{p.type}</span>
        <h3>{p.name}</h3>
        <p style={{color:'var(--muted)', fontSize:16, maxWidth:640}}>{p.desc}</p>
        <div className="metric-row">
          {p.metrics.map((m, i) => (
            <div key={i} className="metric">
              <div className="k">{m.k}</div>
              <div className="v">{m.v}</div>
            </div>
          ))}
        </div>
        {p.img && <div style={{margin:'20px 0', borderRadius:12, overflow:'hidden', border:'1px solid var(--border)'}}>
          <img src={p.img} alt={p.name} style={{width:'100%', display:'block'}} />
        </div>}
        <div style={{marginTop: 18}}>
          <div className="kicker" style={{color:'var(--muted)'}}>STACK</div>
          <div className="proj-tags" style={{marginTop: 10}}>
            {p.stack.map((s, i) => <span key={i} className="proj-tag">{s}</span>)}
          </div>
        </div>
        <div style={{marginTop: 24, display:'flex', gap: 10, flexWrap:'wrap'}}>
          {p.link ? (
            <a href={p.link} target="_blank" rel="noopener" className="btn btn-primary">{p.linkLabel || 'Visitar'}</a>
          ) : null}
          <button className="btn btn-ghost" onClick={onClose}>Cerrar</button>
        </div>
      </div>
    </div>
  );
}

function Projects() {
  const { t } = window.useLang();
  const ref = window.useReveal();
  const [filter, setFilter] = useStateP('Todos');
  const [open, setOpen] = useStateP(null);

  const map = { 'Todos': null, 'All': null, 'IA': 'IA', 'AI': 'IA', 'Robótica': 'Robótica', 'Robotics': 'Robótica', 'Web': 'Web', 'Académico': 'Académico', 'Academic': 'Académico' };
  const list = window.PROJECTS.filter(p => {
    const m = map[filter];
    return !m || p.cats.includes(m);
  });

  return (
    <section id="projects" ref={ref}>
      <div className="container">
        <div className="fade-up">
          <span className="kicker">{t.projects.kicker}</span>
          <h2 className="section-title">{t.projects.h2}</h2>
        </div>
        <div className="filter-row fade-up d1">
          {t.projects.filters.map(f => (
            <button key={f} className={`chip ${filter === f ? 'active' : ''}`} onClick={() => setFilter(f)}>{f}</button>
          ))}
        </div>
        <div className="proj-grid">
          {list.map(p => (
            <div key={p.id} className="fade-up" style={{gridColumn: p.featured ? 'span 3' : 'span 2'}}>
              <ProjectCard p={p} onOpen={setOpen} />
            </div>
          ))}
        </div>
      </div>
      {open && <ProjectModal p={open} onClose={() => setOpen(null)} />}
    </section>
  );
}
window.Projects = Projects;
