/* projects.jsx — Dedicated Projects page */

const ProjectsPage = ({ setPage }) => {
  const [active, setActive] = React.useState(null); // project id for detail modal/inline
  const project = active ? PROJECTS.find(p => p.id === active) : null;

  return (
    <main className="proj-page">
      {/* Hero */}
      <section className="proj-page-hero">
        <div className="container">
          <span className="eyebrow">Proyectos realizados</span>
          <h1>
            Obras que respaldan<br/>
            <span className="hl">cada palabra.</span>
          </h1>
          <p className="lede" style={{maxWidth: '58ch', marginTop: 16}}>
            Una selección de proyectos desarrollados por Aclimatar en distintos
            sectores e industrias — desde edificios corporativos hasta centros de
            cómputos, instituciones sanitarias y propiedad horizontal premium.
          </p>
          <div className="proj-page-stats">
            <div>
              <div className="num">+100</div>
              <div className="lbl">obras ejecutadas</div>
            </div>
            <div className="hairline-v" />
            <div>
              <div className="num">35</div>
              <div className="lbl">años de respaldo técnico</div>
            </div>
            <div className="hairline-v" />
            <div>
              <div className="num">5</div>
              <div className="lbl">sectores cubiertos</div>
            </div>
          </div>
        </div>
      </section>

      {/* Filter chips */}
      <ProjectsFilter />

      {/* Full list */}
      <section className="section-tight proj-list">
        <div className="container">
          {PROJECTS.map((p, i) => (
            <ProjectRow key={p.id} p={p} index={i} flip={i % 2 === 1} onOpen={() => setActive(p.id)} />
          ))}
        </div>
      </section>

      {/* Detail overlay */}
      {project && <ProjectDetail p={project} onClose={() => setActive(null)} />}
    </main>
  );
};

const ProjectsFilter = () => {
  const tags = ['Todos', 'Corporativo', 'Sanitario', 'Centro de Cómputos', 'Propiedad Horizontal', 'Industrial'];
  const [active, setActive] = React.useState('Todos');
  return (
    <section className="proj-filter">
      <div className="container">
        <div className="proj-filter-row">
          {tags.map(t => (
            <button key={t}
                    className={"proj-chip " + (active === t ? 'is-active' : '')}
                    onClick={() => setActive(t)}>
              {t}
            </button>
          ))}
        </div>
      </div>
    </section>
  );
};

const ProjectRow = ({ p, index, flip, onOpen }) => {
  const photoCount = (p.images && p.images.length) || (p.img ? 1 : 0);
  return (
    <article className={"proj-row " + (flip ? 'proj-row-flip' : '')}>
      <div className="proj-row-visual" onClick={onOpen}>
        <ProjImage p={p} className="proj-row-img" />
        {photoCount > 1 && (
          <div className="proj-row-gallery-badge">
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2">
              <rect x="3" y="3" width="14" height="14" rx="1"/><path d="M21 7v12a2 2 0 0 1-2 2H7"/>
            </svg>
            {photoCount} fotos
          </div>
        )}
      </div>
      <div className="proj-row-meta">
        <span className="pill pill-soft">{p.tag}</span>
        <h2>{p.t}</h2>
        <p className="lede" style={{fontSize: 16}}>{p.desc}</p>
        <div className="proj-row-specs">
          {extractSpecs(p).map((s, i) => (
            <div key={i} className="proj-spec">
              <div className="proj-spec-l">{s.l}</div>
              <div className="proj-spec-v">{s.v}</div>
            </div>
          ))}
        </div>
        <button className="btn btn-secondary" onClick={onOpen}>
          Ver detalles del proyecto
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
        </button>
      </div>
    </article>
  );
};

/* Pull a few key technical specs from each project's text */
function extractSpecs(p) {
  const specs = {
    'banco-ciudad': [
      { l: 'Tipo', v: 'Edificio corporativo' },
      { l: 'Tecnología', v: 'Chiller + UTAs + SMMS Toshiba VRF' },
      { l: 'Áreas críticas', v: 'Salas de servidores' },
    ],
    'banco-galicia': [
      { l: 'Tipo', v: 'Centro de cómputos' },
      { l: 'Equipo principal', v: 'Chiller Carrier AquaForce' },
      { l: 'Complejidad', v: 'Operativo de izaje urbano' },
    ],
    'clinica-bazterrica': [
      { l: 'Tipo', v: 'Edificio sanitario' },
      { l: 'Sistema', v: 'Enfriamiento central por agua' },
      { l: 'Alcance', v: 'Chiller + UTAs + montaje en altura' },
    ],
    'altos-del-rio': [
      { l: 'Tipo', v: 'Propiedad horizontal' },
      { l: 'Tecnología', v: 'SMMS Toshiba VRF' },
      { l: 'Ubicación equipos', v: 'Terraza' },
    ],
    'quartier-lacroze': [
      { l: 'Tipo', v: 'Propiedad horizontal premium' },
      { l: 'Climatización', v: 'Daikin VRV IV · R410A (terraza)' },
      { l: 'Agua caliente', v: 'Calderas + circuito primario/secundario' },
      { l: 'Intercambio', v: 'Placas de calor · hierro negro / acero inox.' },
      { l: 'Extras', v: 'Tanque acumulador, expansión y pileta climatizada' },
    ],
  };
  return specs[p.id] || [];
}

/* Detail overlay — opens a fixed panel with full description + gallery */
const ProjectDetail = ({ p, onClose }) => {
  const images = p.images && p.images.length ? p.images : (p.img ? [p.img] : []);
  const [activeIdx, setActiveIdx] = React.useState(0);
  const hasGallery = images.length > 1;

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (hasGallery) {
        if (e.key === 'ArrowRight') setActiveIdx(i => (i + 1) % images.length);
        if (e.key === 'ArrowLeft') setActiveIdx(i => (i - 1 + images.length) % images.length);
      }
    };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [onClose, hasGallery, images.length]);

  return (
    <div className="proj-detail-overlay" onClick={onClose}>
      <div className={"proj-detail " + (hasGallery ? 'proj-detail-gallery' : '')}
           onClick={(e) => e.stopPropagation()}>
        <button className="proj-detail-x" onClick={onClose} aria-label="Cerrar">
          <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 6l12 12M18 6L6 18"/></svg>
        </button>

        {/* Main image area */}
        <div className="proj-detail-stage">
          <ProjImage p={p} className="proj-detail-img" index={activeIdx} />
          {hasGallery && (
            <>
              <button className="proj-detail-nav proj-detail-prev"
                      onClick={() => setActiveIdx(i => (i - 1 + images.length) % images.length)}
                      aria-label="Anterior">
                <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2"><path d="M15 18l-6-6 6-6"/></svg>
              </button>
              <button className="proj-detail-nav proj-detail-next"
                      onClick={() => setActiveIdx(i => (i + 1) % images.length)}
                      aria-label="Siguiente">
                <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 6l6 6-6 6"/></svg>
              </button>
              <div className="proj-detail-counter">{activeIdx + 1} / {images.length}</div>
            </>
          )}
        </div>

        {/* Right side — text + specs + thumbs */}
        <div className="proj-detail-body">
          <span className="pill pill-soft">{p.tag}</span>
          <h2>{p.t}</h2>
          <p className="proj-detail-desc">{p.desc}</p>
          <div className="proj-detail-specs">
            {extractSpecs(p).map((s, i) => (
              <div key={i} className="proj-detail-spec">
                <div className="proj-spec-l">{s.l}</div>
                <div className="proj-spec-v">{s.v}</div>
              </div>
            ))}
          </div>
          {hasGallery && (
            <div className="proj-detail-thumbs">
              <div className="proj-detail-thumbs-lbl">
                Galería · {images.length} fotos
              </div>
              <div className="proj-detail-thumbs-row">
                {images.map((src, i) => (
                  <button key={i}
                          className={"proj-detail-thumb " + (i === activeIdx ? 'is-active' : '')}
                          onClick={() => setActiveIdx(i)}
                          aria-label={"Foto " + (i + 1)}>
                    <img src={src} alt="" loading="lazy" />
                  </button>
                ))}
              </div>
            </div>
          )}
          <div className="proj-detail-actions">
            <button className="btn btn-primary">Solicitar proyecto similar</button>
            <button className="btn btn-ghost" onClick={onClose}>Volver</button>
          </div>
        </div>
      </div>
    </div>
  );
};

window.ProjectsPage = ProjectsPage;
