
const WHY_ITEMS = [
  { icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z', title: 'Respuesta en menos de 2 horas', desc: 'Coordinación ágil y atención inmediata para emergencias y solicitudes urgentes.' },
  { icon: 'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z', title: 'Personal certificado y uniformado', desc: 'Técnicos especializados con experiencia comprobada, uniformados e identificados.' },
  { icon: 'M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4', title: 'Bitácoras y evidencia digital', desc: 'Reportes fotográficos de cada intervención para total transparencia operativa.' },
  { icon: 'M13 10V3L4 14h7v7l9-11h-7z', title: 'Tecnología aplicada en campo', desc: 'Herramientas modernas, diagnósticos digitales y soluciones de vanguardia.' },
  { icon: 'M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-2 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4', title: 'Especialistas en condominios y hoteles', desc: 'Conocemos a fondo la operación de desarrollos residenciales y hospitalidad.' },
  { icon: 'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z', title: 'Presupuestos claros y transparentes', desc: 'Cotizaciones detalladas, sin sorpresas ni costos ocultos. Todo por escrito.' },
  { icon: 'M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3', title: 'Un proveedor para todo', desc: 'Once especialidades bajo un solo contrato. Coordinación y comunicación simplificada.' },
  { icon: 'M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z', title: 'Empresa formal S.A. de C.V.', desc: 'RFC, contratos profesionales y garantías escritas en cada proyecto.' },
];

const TLWhy = () => {
  const [visible, setVisible] = React.useState(false);
  const ref = React.useRef();
  React.useEffect(() => {
    const obs = new IntersectionObserver(([e]) => { if (e.isIntersecting) setVisible(true); }, { threshold: 0.08 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);

  return (
    <section ref={ref} style={{ background: '#F5F5F7', padding: '100px 40px' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto' }}>
        {/* Header */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80, alignItems: 'end', marginBottom: 64 }}>
          <div style={{ opacity: visible ? 1 : 0, transform: visible ? 'none' : 'translateY(20px)', transition: 'all 0.7s ease' }}>
            <div style={{ fontFamily: 'Inter, sans-serif', fontWeight: 600, fontSize: 12, color: '#6E6E73', letterSpacing: 2, textTransform: 'uppercase', marginBottom: 20 }}>¿Por qué Torre Land?</div>
            <h2 style={{ fontFamily: 'Inter, sans-serif', fontWeight: 800, fontSize: 'clamp(32px, 4vw, 52px)', color: '#1D1D1F', letterSpacing: -2, margin: 0, lineHeight: 1.08 }}>
              La diferencia<br/>que se ve<br/>y se siente.
            </h2>
          </div>
          <div style={{ opacity: visible ? 1 : 0, transform: visible ? 'none' : 'translateY(20px)', transition: 'all 0.7s ease 0.1s' }}>
            <p style={{ fontFamily: 'Inter, sans-serif', fontSize: 18, color: '#6E6E73', lineHeight: 1.7, margin: '0 0 28px', letterSpacing: -0.2 }}>
              No solo ejecutamos — documentamos, reportamos y garantizamos. Cada proyecto se trata con el rigor de los mejores desarrollos del país.
            </p>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, background: '#fff', border: '1px solid #E5E5EA', borderRadius: 100, padding: '12px 20px' }}>
              <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#34C759' }} />
              <span style={{ fontFamily: 'Inter, sans-serif', fontSize: 13, color: '#1D1D1F', fontWeight: 600 }}>+200 proyectos entregados</span>
            </div>
          </div>
        </div>

        {/* Grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
          {WHY_ITEMS.map((item, i) => (
            <div key={item.title} style={{
              opacity: visible ? 1 : 0,
              transform: visible ? 'none' : 'translateY(20px)',
              transition: `all 0.6s cubic-bezier(0.16,1,0.3,1) ${0.08 + i * 0.06}s`,
              background: '#fff', borderRadius: 20, padding: 24,
              border: '1px solid #E5E5EA',
            }}>
              <div style={{ width: 40, height: 40, borderRadius: 12, background: '#F5F5F7', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 }}>
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#1D1D1F" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                  <path d={item.icon}/>
                </svg>
              </div>
              <div style={{ fontFamily: 'Inter, sans-serif', fontWeight: 700, fontSize: 14, color: '#1D1D1F', marginBottom: 8, lineHeight: 1.35 }}>{item.title}</div>
              <div style={{ fontFamily: 'Inter, sans-serif', fontWeight: 400, fontSize: 13, color: '#9E9EA3', lineHeight: 1.65 }}>{item.desc}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

// Portfolio
const PORTFOLIO_ITEMS = [
  { cat: 'Construcción', img: null, title: 'Remodelación Torre Residencial', loc: 'Cancún, Q. Roo', tags: ['Remodelación','Acabados','Supervisión'] },
  { cat: 'Albercas', img: null, title: 'Mantenimiento Integral Alberca Hotelera', loc: 'Cancún, Q. Roo', tags: ['Alberca','Hotel','Sanitización'] },
  { cat: 'Paneles Solares', img: null, title: 'Sistema Solar Residencial 15kW', loc: 'Cancún, Q. Roo', tags: ['Solar','Energía','Ahorro'] },
  { cat: 'RFID', img: null, title: 'Sistema de Acceso RFID Boutique Hotel', loc: 'Cancún, Q. Roo', tags: ['RFID','Hotel','Tecnología'] },
  { cat: 'Mantenimiento', img: null, title: 'Programa Anual Condominio Privado', loc: 'Cancún, Q. Roo', tags: ['Condominio','Preventivo','Integral'] },
  { cat: 'Jardines', img: null, title: 'Área Verde Desarrollo Residencial', loc: 'Cancún, Q. Roo', tags: ['Jardinería','Diseño','Riego'] },
  { cat: 'Pintura', img: null, title: 'Pintura Aérea Edificio Corporativo', loc: 'Cancún, Q. Roo', tags: ['Pintura','Aérea','Fachada'] },
  { cat: 'Impermeabilizado', img: null, title: 'Impermeabilización Azotea Condominio', loc: 'Cancún, Q. Roo', tags: ['Impermeabilizado','Azotea','Preventivo'] },
];

const CATS = ['Todos','Construcción','Albercas','Paneles Solares','RFID','Mantenimiento','Jardines','Pintura','Impermeabilizado'];
const colors = { 'Construcción': ['#F0F0F0','#3D3D3F'], 'Pintura': ['#FFF0F0','#B91C1C'], 'Impermeabilizado': ['#F0F8FF','#1D4ED8'], 'Albercas': ['#EBF8FF','#0369A1'], 'Paneles Solares': ['#FEFCE8','#A16207'], 'RFID': ['#F5F3FF','#6D28D9'], 'Mantenimiento': ['#F0FDF4','#166534'], 'Jardines': ['#F0FDF4','#15803D'] };

const TLPortfolio = () => {
  const [active, setActive] = React.useState('Todos');
  const [modal, setModal] = React.useState(null); // { title, loc, images, idx }
  const filtered = active === 'Todos' ? PORTFOLIO_ITEMS : PORTFOLIO_ITEMS.filter(p => p.cat === active);
  const scrollTo = (id) => { const el = document.getElementById(id); if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' }); };

  return (
    <section id="portafolio" style={{ background: '#fff', padding: '100px 40px' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto' }}>
        <div style={{ textAlign: 'center', marginBottom: 48 }}>
          <div style={{ fontFamily: 'Inter, sans-serif', fontWeight: 600, fontSize: 12, color: '#6E6E73', letterSpacing: 2, textTransform: 'uppercase', marginBottom: 16 }}>Proyectos Realizados</div>
          <h2 style={{ fontFamily: 'Inter, sans-serif', fontWeight: 800, fontSize: 'clamp(32px, 4vw, 52px)', color: '#1D1D1F', letterSpacing: -2, margin: '0 0 20px', lineHeight: 1.08 }}>Nuestro portafolio.</h2>
          <p style={{ fontFamily: 'Inter, sans-serif', fontSize: 17, color: '#6E6E73', maxWidth: 480, margin: '0 auto', lineHeight: 1.7, letterSpacing: -0.1 }}>Resultados tangibles que hablan por sí solos. Cada proyecto, una historia de confianza.</p>
        </div>

        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, justifyContent: 'center', marginBottom: 48 }}>
          {CATS.map(c => (
            <button key={c} onClick={() => setActive(c)} style={{
              background: active === c ? '#1D1D1F' : '#F5F5F7',
              color: active === c ? '#fff' : '#6E6E73',
              border: 'none', cursor: 'pointer',
              fontFamily: 'Inter, sans-serif', fontWeight: 500, fontSize: 13,
              padding: '8px 20px', borderRadius: 100, transition: 'all 0.2s',
            }}>
              {c}
            </button>
          ))}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 20 }}>
          {filtered.map((p) => {
            const [bg, tc] = colors[p.cat] || ['#F5F5F7','#1D1D1F'];
            return (
              <div key={p.title} style={{ borderRadius: 20, overflow: 'hidden', border: '1px solid #E5E5EA', transition: 'all 0.3s', cursor: 'pointer' }}
              onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 20px 60px rgba(0,0,0,0.08)'; e.currentTarget.style.transform = 'translateY(-4px)'; }}
              onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}
              >
                <div style={{ height: 200, background: p.img ? '#111' : `linear-gradient(145deg, ${bg}, #f8f8f8)`, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', overflow: 'hidden' }}>
                  {p.img
                    ? <img src={p.img} alt={p.title} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                    : <div style={{ textAlign: 'center' }}>
                        <div style={{ fontFamily: 'monospace', fontSize: 11, color: tc, opacity: 0.4, letterSpacing: 1 }}>[ imagen del proyecto ]</div>
                      </div>
                  }
                  <div style={{ position: 'absolute', top: 16, left: 16, background: 'rgba(255,255,255,0.92)', backdropFilter: 'blur(8px)', borderRadius: 100, padding: '4px 14px', fontFamily: 'Inter, sans-serif', fontWeight: 600, fontSize: 11, color: tc }}>
                    {p.cat}
                  </div>
                </div>
                <div style={{ padding: 24, background: '#fff' }}>
                  <div style={{ fontFamily: 'Inter, sans-serif', fontWeight: 700, fontSize: 16, color: '#1D1D1F', marginBottom: 8 }}>{p.title}</div>
                  <div style={{ fontFamily: 'Inter, sans-serif', fontSize: 13, color: '#9E9EA3', marginBottom: 16, display: 'flex', alignItems: 'center', gap: 4 }}>
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/></svg>
                    {p.loc}
                  </div>
                  <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 20 }}>
                    {p.tags.map(t => (
                      <span key={t} style={{ background: '#F5F5F7', borderRadius: 6, padding: '3px 10px', fontFamily: 'Inter, sans-serif', fontSize: 11, color: '#6E6E73', fontWeight: 500 }}>{t}</span>
                    ))}
                  </div>
                  <button onClick={(e) => {
                    e.stopPropagation();
                    if (p.images && p.images.length) {
                      setModal({ title: p.title, loc: p.loc, images: p.images, idx: 0 });
                    } else {
                      scrollTo('contacto');
                    }
                  }} style={{
                    background: 'none', border: '1px solid #E5E5EA', cursor: 'pointer',
                    fontFamily: 'Inter, sans-serif', fontWeight: 600, fontSize: 13, color: '#1D1D1F',
                    padding: '10px 20px', borderRadius: 10, width: '100%', transition: 'all 0.2s',
                  }}
                  onMouseEnter={e => { e.target.style.background = '#1D1D1F'; e.target.style.color = '#fff'; e.target.style.borderColor = '#1D1D1F'; }}
                  onMouseLeave={e => { e.target.style.background = 'none'; e.target.style.color = '#1D1D1F'; e.target.style.borderColor = '#E5E5EA'; }}
                  >
                    {p.images && p.images.length ? 'Ver fotos →' : 'Contactar asesor →'}
                  </button>
                </div>
              </div>
            );
          })}
        {modal && (
          <div onClick={() => setModal(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)', zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
            <div onClick={(e) => e.stopPropagation()} style={{ width: 'min(980px, 96vw)', background: '#fff', borderRadius: 18, overflow: 'hidden', boxShadow: '0 30px 90px rgba(0,0,0,0.25)' }}>
              <div style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderBottom: '1px solid #E5E5EA' }}>
                <div>
                  <div style={{ fontFamily: 'Inter, sans-serif', fontWeight: 800, fontSize: 14, color: '#1D1D1F' }}>{modal.title}</div>
                  <div style={{ fontFamily: 'Inter, sans-serif', fontSize: 12, color: '#6E6E73' }}>{modal.loc}</div>
                </div>
                <button onClick={() => setModal(null)} style={{ border: 'none', background: '#F5F5F7', borderRadius: 10, padding: '8px 10px', cursor: 'pointer', fontFamily: 'Inter, sans-serif', fontWeight: 700 }}>Cerrar</button>
              </div>
              <div style={{ position: 'relative', background: '#111' }}>
                <img src={modal.images[modal.idx]} alt={modal.title} style={{ width: '100%', height: 'min(70vh, 640px)', objectFit: 'contain', display: 'block' }} />
                {modal.images.length > 1 && (
                  <>
                    <button onClick={() => setModal({ ...modal, idx: (modal.idx - 1 + modal.images.length) % modal.images.length })} style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', border: 'none', background: 'rgba(255,255,255,0.85)', borderRadius: 999, width: 44, height: 44, cursor: 'pointer', fontSize: 18, fontWeight: 900 }}>‹</button>
                    <button onClick={() => setModal({ ...modal, idx: (modal.idx + 1) % modal.images.length })} style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', border: 'none', background: 'rgba(255,255,255,0.85)', borderRadius: 999, width: 44, height: 44, cursor: 'pointer', fontSize: 18, fontWeight: 900 }}>›</button>
                  </>
                )}
              </div>
              <div style={{ padding: 12, display: 'flex', gap: 8, flexWrap: 'wrap', justifyContent: 'center', background: '#fff' }}>
                {modal.images.map((src, i) => (
                  <button key={src} onClick={() => setModal({ ...modal, idx: i })} style={{ border: i == modal.idx ? '2px solid #1D1D1F' : '1px solid #E5E5EA', padding: 0, background: 'none', borderRadius: 10, overflow: 'hidden', cursor: 'pointer' }}>
                    <img src={src} alt={modal.title + ' ' + (i+1)} style={{ width: 96, height: 64, objectFit: 'cover', display: 'block' }} />
                  </button>
                ))}
              </div>
            </div>
          </div>
        )}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { TLWhy, TLPortfolio });
