/* global React */

// useViewport — when width prop isn't passed (real-page mode) fall back to
// the live viewport. Sections only break to mobile under 720px.
function useResponsive(widthProp) {
  const [vw, setVw] = React.useState(() => widthProp || (typeof window !== 'undefined' ? window.innerWidth : 1440));
  React.useEffect(() => {
    if (widthProp) return;
    const onR = () => setVw(window.innerWidth);
    window.addEventListener('resize', onR);
    return () => window.removeEventListener('resize', onR);
  }, [widthProp]);
  return { width: vw, isMobile: vw < 720 };
}

// =====================================================================
// SERVICES — editorial grid, hover reveals, mono index numbers
// =====================================================================

const Services = ({ width: w }) => {
  const { width, isMobile } = useResponsive(w);
  const vivienda = [
    { n: '01', title: 'Iluminación inteligente', desc: 'Escenas que se adaptan al momento del día. Control por voz, app o un solo botón. Hasta -40% de consumo eléctrico.', descShort: 'Escenas por momento del día. Hasta -40% de consumo.', tags: ['DALI','Loxone','Casambi'] },
    { n: '02', title: 'Climatización y persianas', desc: 'Calor, frío y luz natural sincronizados por estancia. Curvas reales, consumo medido, persiana que reacciona al sol.', descShort: 'Clima y persianas sincronizados, consumo medido.', tags: ['Aerotermia','HVAC','Somfy'] },
    { n: '03', title: 'Seguridad y videovigilancia', desc: 'Cámaras IP, cerraduras inteligentes, alarma grado 2/3 y detección de movimiento con alerta al móvil.', descShort: 'Cámaras IP, alarma grado 2/3 y avisos al móvil.', tags: ['Hikvision','Ajax','CCTV'] },
    { n: '04', title: 'Audio multiroom y red', desc: 'Sonido sincronizado por estancias y WiFi profesional sin zonas muertas en toda la casa.', descShort: 'Audio sincronizado y WiFi sin zonas muertas.', tags: ['Sonos','UniFi','Mesh'] },
  ];
  const negocio = [
    { n: '05', title: 'Domótica para hostelería y retail', desc: 'Encendido por horarios, escenas por turno, control remoto del local. Loxone integrado a tu PMS o caja.', descShort: 'Horarios, escenas por turno, control remoto del local.', tags: ['Loxone','Horarios','Multi-local'] },
    { n: '06', title: 'Cámaras frigoríficas y sondas IoT', desc: 'Monitorización de temperatura 24/7 con alertas automáticas para garantizar la seguridad alimentaria.', descShort: 'Temperatura 24/7 con alertas automáticas.', tags: ['Sondas IoT','Alertas','HACCP'] },
    { n: '07', title: 'Control de accesos profesional', desc: 'Lectores biométricos, intercomunicador IP y gestión de horarios para empleados, clientes y proveedores.', descShort: 'Biometría, intercom IP y horarios por persona.', tags: ['2N','Akuvox','Biometría'] },
    { n: '08', title: 'Mantenimiento y SLA', desc: 'Soporte remoto en menos de una hora, revisiones programadas y SLA contractual para clientes activos.', descShort: 'Soporte remoto < 1 h y SLA contractual.', tags: ['SLA','Remoto','In situ'] },
  ];
  const ia = [
    { n: '09', title: 'Agente comercial Ambrosio', desc: 'Capta llamadas, agenda visitas, hace presupuestos, manda mails y WhatsApps. Tu primer punto de contacto, 24/7. Conectado a Comfortek In.', descShort: 'Atiende, presupuesta y agenda 24/7. Conectado a Comfortek In.', tags: ['Voz','WhatsApp','Email','Calendario'] },
    { n: '10', title: 'Control conversacional de la instalación', desc: 'Habla con tu casa o negocio en lenguaje natural. LLM local o cloud sobre Home Assistant / Loxone. "Modo cena", "deja la oficina lista para mañana".', descShort: 'Habla con tu casa: "modo cena", "oficina lista mañana".', tags: ['Ollama','Claude','Voice','MCP'] },
    { n: '11', title: 'Automatización predictiva', desc: 'La instalación aprende patrones de ocupación, clima y energía. Ajusta antes de que pidas, avisa antes de que falle. Mantenimiento que se adelanta.', descShort: 'Aprende patrones y se adelanta a fallos y consumo.', tags: ['Predictivo','Energía','Mantenimiento'] },
    { n: '12', title: 'Agentes a medida', desc: '¿Necesitas que la IA haga algo específico de tu negocio — reservas, facturación, atención post-venta? Diseñamos el agente con tu stack y tu lógica.', descShort: 'Agente IA hecho con tu stack y tu lógica.', tags: ['Custom','MCP','Integración'] },
  ];

  const Track = ({ label, color, items: list }) => (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: isMobile ? '0 0 18px' : '0 0 22px' }}>
        <span style={{ width: 8, height: 8, borderRadius: 2, background: color, boxShadow: `0 0 12px ${color}` }} />
        <span className="mono" style={{ fontSize: 12, letterSpacing: '0.18em', color: 'var(--text-0)', textTransform: 'uppercase' }}>{label}</span>
        <span style={{ flex: 1, height: 1, background: 'var(--line)' }} />
      </div>
      <div style={{
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)',
        borderTop: '1px solid var(--line)',
        borderLeft: isMobile ? 'none' : '1px solid var(--line)',
      }}>
        {list.map(it => {
          const visibleDesc = isMobile && it.descShort ? it.descShort : it.desc;
          const visibleTags = isMobile ? it.tags.slice(0, 3) : it.tags;
          return (
          <article key={it.n} style={{
            padding: isMobile ? '24px 20px' : '32px 28px',
            borderRight: isMobile ? 'none' : '1px solid var(--line)',
            borderBottom: '1px solid var(--line)',
            background: 'var(--bg-0)', minHeight: isMobile ? 'auto' : 240,
            display: 'flex', flexDirection: 'column',
          }}>
            <span className="numlabel" style={{ marginBottom: isMobile ? 12 : 18, color }}>{it.n}</span>
            <h3 style={{ fontSize: isMobile ? 18 : 21, fontWeight: 500, letterSpacing: '-0.02em', marginBottom: isMobile ? 8 : 10, color: 'var(--text-0)' }}>{it.title}</h3>
            <p style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--text-1)', marginBottom: 14, flex: 1, textWrap: 'pretty' }}>{visibleDesc}</p>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {visibleTags.map(t => (
                <span key={t} style={{
                  fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.08em',
                  padding: '4px 8px', border: '1px solid var(--line)', borderRadius: 999, color: 'var(--text-2)',
                }}>{t}</span>
              ))}
            </div>
          </article>
          );
        })}
      </div>
    </div>
  );

  const tabs = [
    { key: 'vivienda', label: 'Vivienda',  mobileLabel: 'Vivienda', color: '#ff6a1a', items: vivienda, fullLabel: 'Vivienda' },
    { key: 'negocio',  label: 'Negocio',   mobileLabel: 'Negocio',  color: '#19c2d6', items: negocio,  fullLabel: 'Negocio · Hostelería · Retail' },
    { key: 'ia',       label: 'IA',        mobileLabel: 'IA',       color: '#7c5cff', items: ia,       fullLabel: 'Capa IA & Agentes · Comfortek In' },
  ];
  const [activeKey, setActiveKey] = React.useState('vivienda');
  const active = tabs.find(t => t.key === activeKey) || tabs[0];

  return (
    <Section eyebrow="01 — SERVICIOS" title={<>Tres mundos,<br/><span className="serif" style={{ fontStyle: 'italic' }}>una sola integración.</span></>} isMobile={isMobile} subtitle="+50 proyectos en la Costa Brava entre vivienda, negocio y la nueva capa de agentes IA. Diseñamos cada uno con su propia lógica — no hay receta única.">
      {isMobile ? (
        <div>
          {/* Tabs Vivienda | Negocio | IA */}
          <div role="tablist" aria-label="Categorías de servicios" style={{
            display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6,
            padding: 4,
            border: '1px solid var(--line-strong)',
            borderRadius: 999,
            background: 'rgba(255,255,255,0.02)',
            marginBottom: 32,
          }}>
            {tabs.map(t => {
              const isActive = t.key === activeKey;
              return (
                <button key={t.key} type="button" role="tab" aria-selected={isActive}
                  onClick={() => setActiveKey(t.key)}
                  style={{
                    padding: '10px 12px', borderRadius: 999, cursor: 'pointer',
                    background: isActive ? `${t.color}22` : 'transparent',
                    color: isActive ? 'var(--text-0)' : 'var(--text-2)',
                    border: `1px solid ${isActive ? t.color : 'transparent'}`,
                    fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em',
                    fontWeight: 500, textTransform: 'uppercase',
                    transition: 'background .15s, color .15s, border-color .15s',
                  }}>
                  {t.mobileLabel}
                </button>
              );
            })}
          </div>
          <Track label={active.fullLabel} color={active.color} items={active.items} />
        </div>
      ) : (
        <div style={{ display: 'grid', gap: 72 }}>
          <Track label="Vivienda" color="#ff6a1a" items={vivienda} />
          <Track label="Negocio · Hostelería · Retail" color="#19c2d6" items={negocio} />
          <Track label="Capa IA & Agentes · Comfortek In" color="#7c5cff" items={ia} />
        </div>
      )}
    </Section>
  );
};

// =====================================================================
// WHY COMFORTEK
// =====================================================================

const Why = ({ width: w }) => {
  const { width, isMobile } = useResponsive(w);
  const reasons = [
    { k: 'Integración real', d: 'No instalamos productos sueltos. Diseñamos sistemas que hablan entre sí en una sola lógica.' },
    { k: 'Diseño técnico', d: 'Plano eléctrico, esquema de red, listado de cargas. Documentado antes de tirar el primer cable.' },
    { k: 'Hardware abierto', d: 'Loxone, KNX, Home Assistant. Estándares que sobreviven al fabricante de la app de moda.' },
    { k: 'Soporte como servicio', d: 'No te dejamos con el manual. Mantenimiento remoto, SLA y revisiones programadas.' },
  ];
  return (
    <Section eyebrow="02 — POR QUÉ COMFORTEK" title={<>La diferencia entre <span className="serif" style={{ fontStyle: 'italic' }}>"tener domótica"</span><br/>y que la domótica <span className="grad-text">funcione</span>.</>} isMobile={isMobile}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr',
        gap: isMobile ? 0 : 64,
        alignItems: 'start',
      }}>
        <div style={{ display: 'grid', gap: 0 }}>
          {reasons.map((r, i) => (
            <div key={r.k} style={{
              display: 'grid',
              gridTemplateColumns: '40px 1fr',
              gap: 24,
              padding: '32px 0',
              borderTop: i === 0 ? '1px solid var(--line)' : 'none',
              borderBottom: '1px solid var(--line)',
            }}>
              <span className="mono" style={{ fontSize: 12, color: 'var(--text-2)' }}>0{i+1}</span>
              <div>
                <h4 style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em', marginBottom: 8 }}>{r.k}</h4>
                <p style={{ fontSize: 15, lineHeight: 1.55, color: 'var(--text-1)', textWrap: 'pretty' }}>{r.d}</p>
              </div>
            </div>
          ))}
        </div>

        {!isMobile && <WhyVisual />}
      </div>
    </Section>
  );
};

const WhyVisual = () => (
  <div style={{ position: 'sticky', top: 80, padding: '32px 0' }}>
    <div style={{
      position: 'relative',
      aspectRatio: '4/5',
      borderRadius: 20,
      overflow: 'hidden',
      border: '1px solid var(--line)',
      background: 'linear-gradient(135deg, #0d0d14 0%, #15101c 100%)',
    }}>
      {/* simulated technical diagram */}
      <svg viewBox="0 0 400 500" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        <defs>
          <linearGradient id="wg" x1="0" x2="1" y1="0" y2="1">
            <stop offset="0" stopColor="#ff6a1a" />
            <stop offset="0.5" stopColor="#ff8a3d" />
            <stop offset="1" stopColor="#19c2d6" />
          </linearGradient>
        </defs>
        {/* floor plan */}
        <g stroke="rgba(255,255,255,0.18)" strokeWidth="1" fill="none">
          <rect x="40" y="60" width="320" height="380" />
          <line x1="40" y1="220" x2="220" y2="220" />
          <line x1="220" y1="60" x2="220" y2="440" />
          <line x1="220" y1="320" x2="360" y2="320" />
          <line x1="100" y1="220" x2="100" y2="440" />
        </g>
        {/* rooms labels */}
        <g fontFamily="Geist Mono" fontSize="9" fill="rgba(255,255,255,0.4)" letterSpacing="1">
          <text x="50" y="80">SALÓN</text>
          <text x="230" y="80">COCINA</text>
          <text x="230" y="240">DORM 1</text>
          <text x="230" y="340">BAÑO</text>
          <text x="50" y="240">PASILLO</text>
          <text x="110" y="240">DORM 2</text>
        </g>
        {/* nodes */}
        {[
          [130,140],[290,140],[290,270],[290,380],[160,330],[70,330],[140,400]
        ].map(([x,y],i) => (
          <g key={i}>
            <circle cx={x} cy={y} r="8" fill="url(#wg)" opacity="0.9" />
            <circle cx={x} cy={y} r="14" fill="none" stroke="url(#wg)" strokeWidth="0.5" opacity="0.4" />
          </g>
        ))}
        {/* connecting lines */}
        <g stroke="url(#wg)" strokeWidth="1" fill="none" opacity="0.6" strokeDasharray="2 3">
          <path d="M130 140 L290 140 L290 270 L290 380" />
          <path d="M130 140 L160 330 L70 330" />
          <path d="M160 330 L140 400" />
          <path d="M290 380 L140 400" />
        </g>
        {/* central node */}
        <circle cx="200" cy="250" r="22" fill="rgba(255,106,26,0.15)" stroke="url(#wg)" strokeWidth="1" />
        <circle cx="200" cy="250" r="6" fill="url(#wg)" />
        <text x="200" y="290" fontFamily="Geist Mono" fontSize="9" fill="rgba(255,255,255,0.5)" textAnchor="middle" letterSpacing="1">MINISERVER</text>
      </svg>
      {/* corner badge */}
      <div style={{ position: 'absolute', top: 20, left: 20 }}>
        <span className="numlabel">PLANO LÓGICO · CASA TIPO</span>
      </div>
      <div style={{ position: 'absolute', bottom: 20, left: 20, right: 20, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span className="mono" style={{ fontSize: 11, color: 'var(--text-2)' }}>v2.4 · 142 PUNTOS</span>
        <span className="mono" style={{ fontSize: 11, color: '#4ade80' }}>● ACTIVO</span>
      </div>
    </div>
  </div>
);

// =====================================================================
// PROJECTS
// =====================================================================

const Projects = ({ width: w }) => {
  const { width, isMobile } = useResponsive(w);
  const list = [
    { idx: '01', name: 'Casa de alto standing', loc: 'Lloret de Mar', type: 'Vivienda · Loxone', stack: ['Loxone','Iluminación','Clima','Persianas'], hue: 18, img: 'img/proyecto-lloret-standing.jpg', desc: 'Sistema domótico Loxone completo. Control de iluminación, clima y persianas con programación personalizada en vivienda de lujo frente al mar.' },
    { idx: '02', name: 'Restaurant Sant Elm', loc: 'Costa Brava', type: 'Hostelería · HACCP', stack: ['Sondas IoT','Alertas','Cámaras frigoríficas'], hue: 200, img: 'img/proyecto-sant-elm.jpg', desc: 'Control y monitorización de temperatura en cámaras frigoríficas con alertas automáticas para garantizar la seguridad alimentaria.' },
    { idx: '03', name: 'Casa frente al mar', loc: 'Calella de Palafrugell', type: 'Vivienda · Clima', stack: ['Climatización','Escenas','Control remoto'], hue: 14, img: 'img/proyecto-calella.jpg', desc: 'Automatización del sistema de climatización con control remoto y escenas que se ajustan a las condiciones exteriores.' },
  ];
  return (
    <Section eyebrow="03 — PROYECTOS" title={<>Proyectos reales,<br/><span className="serif" style={{ fontStyle: 'italic' }}>resultados reales.</span></>} isMobile={isMobile}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr 1fr',
        gap: 16,
      }}>
        {list.map((p,i) => (
          <article key={p.idx} style={{
            position: 'relative',
            borderRadius: 18,
            overflow: 'hidden',
            border: '1px solid var(--line)',
            background: 'var(--bg-1)',
            aspectRatio: isMobile ? '4/5' : '3/4',
          }}>
            {/* photo or simulated background */}
            {p.img
              ? <img src={p.img} alt={p.name} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center' }} />
              : <>
                <div style={{
                  position: 'absolute', inset: 0,
                  background: `linear-gradient(135deg, hsl(${p.hue} 30% 12%) 0%, hsl(${p.hue} 25% 6%) 100%)`,
                }} />
                <div style={{
                  position: 'absolute', top: '20%', right: '-10%', width: '60%', height: '60%',
                  background: `radial-gradient(circle, hsla(${p.hue}, 60%, 50%, 0.25), transparent 60%)`,
                  filter: 'blur(20px)',
                }} />
                <svg viewBox="0 0 400 500" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.35 }} preserveAspectRatio="none">
                  <line x1="0" y1="320" x2="400" y2="320" stroke="rgba(255,255,255,0.4)" strokeWidth="1"/>
                  <rect x="40" y="80" width="120" height="240" stroke="rgba(255,255,255,0.3)" fill="none"/>
                  <rect x="200" y="40" width="170" height="280" stroke="rgba(255,255,255,0.25)" fill="none"/>
                  <rect x="220" y="80" width="60" height="220" stroke="rgba(255,255,255,0.2)" fill="none"/>
                  <rect x="290" y="80" width="60" height="220" stroke="rgba(255,255,255,0.2)" fill="none"/>
                  <circle cx="100" cy="150" r="3" fill="rgba(255,180,100,0.9)" />
                  <circle cx="100" cy="150" r="14" fill="rgba(255,180,100,0.2)" />
                  <circle cx="250" cy="180" r="3" fill="rgba(255,180,100,0.9)" />
                  <circle cx="250" cy="180" r="14" fill="rgba(255,180,100,0.2)" />
                  <circle cx="320" cy="180" r="3" fill="rgba(255,180,100,0.9)" />
                  <circle cx="320" cy="180" r="14" fill="rgba(255,180,100,0.2)" />
                </svg>
              </>
            }
            <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to bottom, transparent 40%, rgba(7,7,10,0.92) 100%)' }} />

            <div style={{ position: 'absolute', top: 18, left: 18, right: 18, display: 'flex', justifyContent: 'space-between' }}>
              <span className="numlabel">{p.idx} / 12</span>
              <span className="numlabel">{p.type.toUpperCase()}</span>
            </div>

            <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: 22 }}>
              <div className="mono" style={{ fontSize: 11, color: 'var(--text-2)', marginBottom: 6, letterSpacing: '0.12em' }}>{p.loc.toUpperCase()}</div>
              <h3 style={{ fontSize: 24, fontWeight: 500, letterSpacing: '-0.025em', marginBottom: 10 }}>{p.name}</h3>
              <p style={{ fontSize: 13, lineHeight: 1.5, color: 'var(--text-1)', marginBottom: 14, textWrap: 'pretty' }}>{p.desc}</p>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {p.stack.map(s => (
                  <span key={s} style={{
                    fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.06em',
                    padding: '3px 8px', borderRadius: 999,
                    background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.1)',
                    color: 'var(--text-1)',
                  }}>{s}</span>
                ))}
              </div>
            </div>
          </article>
        ))}
      </div>
    </Section>
  );
};

// =====================================================================
// BRANDS — marquee/grid
// =====================================================================

const Brands = ({ width: w }) => {
  const { width, isMobile } = useResponsive(w);
  const brands = ['LOXONE','KNX','HOME ASSISTANT','HIKVISION','SONOS','SOMFY','DAIKIN','AJAX','SHELLY','GIRA','DALI','ZIGBEE'];
  return (
    <Section eyebrow="04 — TECNOLOGÍAS" title={<>Trabajamos con lo<br/><span className="serif" style={{ fontStyle: 'italic' }}>que de verdad</span> aguanta.</>} isMobile={isMobile} subtitle="Sistemas estándar, abiertos y con soporte a largo plazo. Nunca tecnología cerrada que mañana no exista.">
      <div style={{
        display: 'grid',
        gridTemplateColumns: isMobile ? 'repeat(2,1fr)' : 'repeat(6,1fr)',
        borderTop: '1px solid var(--line)',
        borderLeft: '1px solid var(--line)',
      }}>
        {brands.map((b,i) => (
          <div key={b} style={{
            borderRight: '1px solid var(--line)',
            borderBottom: '1px solid var(--line)',
            padding: isMobile ? '28px 16px' : '36px 24px',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            minHeight: isMobile ? 90 : 120,
            position: 'relative',
            transition: 'background 0.3s',
          }}>
            <span style={{
              fontFamily: 'var(--font-sans)',
              fontSize: isMobile ? 14 : 17,
              fontWeight: 500,
              letterSpacing: b.length > 8 ? '0.04em' : '0.08em',
              color: 'var(--text-1)',
            }}>{b}</span>
          </div>
        ))}
      </div>
    </Section>
  );
};

// =====================================================================
// PROCESS
// =====================================================================

const Process = ({ width: w }) => {
  const { width, isMobile } = useResponsive(w);
  const steps = [
    { n: '01', t: 'Escuchamos', d: 'Cada proyecto empieza escuchando tus necesidades. Visita técnica gratuita y sin compromiso, en tu casa o negocio.' },
    { n: '02', t: 'Diseñamos', d: 'Solución 100% personalizada. Plano lógico, marcas y presupuesto cerrado en una sola propuesta clara.' },
    { n: '03', t: 'Instalamos', d: 'Sin obras complicadas. Equipo propio, coordinación con tu obra y te enseñamos a disfrutarla desde el primer día.' },
  ];
  return (
    <Section eyebrow="05 — PROCESO" title={<>De la idea a tu hogar inteligente<br/><span className="serif" style={{ fontStyle: 'italic' }}>en 3 pasos.</span></>} isMobile={isMobile}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)',
        gap: isMobile ? 0 : 1,
        background: 'var(--line)',
        border: '1px solid var(--line)',
        borderRadius: 16,
        overflow: 'hidden',
      }}>
        {steps.map((s,i) => (
          <div key={s.n} style={{
            background: 'var(--bg-0)',
            padding: isMobile ? '28px 24px' : '36px 28px',
            position: 'relative',
            minHeight: isMobile ? 'auto' : 220,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
              <span className="mono" style={{ fontSize: 12, color: 'var(--brand-orange)', letterSpacing: '0.12em' }}>STEP {s.n}</span>
              <span style={{ flex: 1, height: 1, background: 'var(--line)' }} />
            </div>
            <h4 style={{ fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em', marginBottom: 10 }}>{s.t}</h4>
            <p style={{ fontSize: 14, lineHeight: 1.55, color: 'var(--text-1)' }}>{s.d}</p>
          </div>
        ))}
      </div>
    </Section>
  );
};

// =====================================================================
// TESTIMONIALS
// =====================================================================

const Testimonials = ({ width: w }) => {
  const { width, isMobile } = useResponsive(w);
  const quotes = [
    { q: 'Todo perfecto, un gran profesional, aclarando siempre dudas y con tecnología a la última. Lo recomiendo.', a: 'Irene Ramírez', r: 'Cliente · Lloret de Mar' },
    { q: 'Soluciones prácticas de domótica, buen servicio y confiable. Una gran empresa.', a: 'Alejandro Espín García', r: 'Cliente · Costa Brava' },
    { q: 'Persona de confianza y gran profesional. Amable y muy recomendable.', a: 'Roberto Carriqui', r: 'Cliente · Vivienda particular' },
  ];
  return (
    <Section eyebrow="06 — CLIENTES" title={<>+50 familias ya viven<br/><span className="serif" style={{ fontStyle: 'italic' }}>en casas inteligentes.</span></>} isMobile={isMobile}>
      <div style={{
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)',
        gap: 16,
      }}>
        {quotes.map((q,i) => (
          <blockquote key={i} style={{
            padding: isMobile ? '28px 24px' : '32px 28px',
            border: '1px solid var(--line)',
            borderRadius: 18,
            background: 'var(--bg-1)',
            display: 'flex', flexDirection: 'column', gap: 24,
          }}>
            <svg width="22" height="18" viewBox="0 0 22 18" fill="none">
              <path d="M0 18V11C0 5 3 1 9 0L10 3C6.5 4 4.5 6 4 9H9V18H0ZM12 18V11C12 5 15 1 21 0L22 3C18.5 4 16.5 6 16 9H21V18H12Z" fill="url(#tq-grad)"/>
              <defs><linearGradient id="tq-grad" x1="0" y1="0" x2="22" y2="18"><stop stopColor="#ff6a1a"/><stop offset="1" stopColor="#19c2d6"/></linearGradient></defs>
            </svg>
            <p style={{ fontSize: isMobile ? 17 : 18, lineHeight: 1.5, letterSpacing: '-0.01em', color: 'var(--text-0)', flex: 1, textWrap: 'pretty' }}>{q.q}</p>
            <div>
              <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text-0)' }}>{q.a}</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--text-2)', marginTop: 2, letterSpacing: '0.08em' }}>{q.r.toUpperCase()}</div>
            </div>
          </blockquote>
        ))}
      </div>
    </Section>
  );
};

// =====================================================================
// CTA
// =====================================================================
// WORDMARK BREAK — full-bleed editorial moment. The brand name as art.
// =====================================================================

const WordmarkBreak = ({ width: w }) => {
  const { width, isMobile } = useResponsive(w);
  const fontSize = isMobile ? 92 : 280;
  return (
    <section style={{
      position: 'relative',
      padding: isMobile ? '64px 0 56px' : '120px 0 96px',
      overflow: 'hidden',
      borderTop: '1px solid var(--line)',
      borderBottom: '1px solid var(--line)',
      background: 'linear-gradient(180deg, var(--bg-0) 0%, #0a0a12 50%, var(--bg-0) 100%)',
    }}>
      {/* warm + cool ambient blobs */}
      <div style={{ position: 'absolute', top: '-30%', left: '10%', width: 700, height: 700, background: 'radial-gradient(circle, rgba(255,106,26,0.18), transparent 60%)', filter: 'blur(60px)', pointerEvents: 'none' }} />
      <div style={{ position: 'absolute', bottom: '-30%', right: '5%', width: 800, height: 800, background: 'radial-gradient(circle, rgba(25,194,214,0.14), transparent 60%)', filter: 'blur(60px)', pointerEvents: 'none' }} />

      {/* Eyebrow row */}
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: isMobile ? '0 24px 32px' : '0 56px 56px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 24, flexWrap: 'wrap', position: 'relative', zIndex: 2 }}>
        <div className="eyebrow"><span>El nombre detrás de tus instalaciones</span></div>
        <span className="mono" style={{ fontSize: 11, color: 'var(--text-2)', letterSpacing: '0.14em', textTransform: 'uppercase' }}>EST. 2024 · LLORET DE MAR</span>
      </div>

      {/* The wordmark */}
      <div style={{ position: 'relative', display: 'flex', justifyContent: 'center', padding: isMobile ? '0 8px' : '0 24px', zIndex: 2 }}>
        <h2 style={{
          fontFamily: '"Montserrat", system-ui, sans-serif',
          fontWeight: 900,
          fontSize,
          lineHeight: 0.82,
          letterSpacing: '-0.06em',
          margin: 0,
          textTransform: 'lowercase',
          display: 'flex',
          alignItems: 'center',
          whiteSpace: 'nowrap',
          background: 'linear-gradient(180deg, #ffffff 0%, #ffffff 60%, rgba(255,255,255,0.35) 100%)',
          WebkitBackgroundClip: 'text',
          backgroundClip: 'text',
          WebkitTextFillColor: 'transparent',
          color: 'transparent',
        }}>
          <span>comf</span>
          <window.BigPowerO size={fontSize * 0.78} />
          <span>rtek</span>
          <span style={{
            background: 'linear-gradient(135deg, #ff6a1a, #ff8a3d)',
            WebkitBackgroundClip: 'text',
            backgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
            marginLeft: '-0.02em',
          }}>.</span>
        </h2>
      </div>

      {/* Caption strip below */}
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: isMobile ? '40px 24px 0' : '72px 56px 0', display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr 1fr', gap: isMobile ? 24 : 56, position: 'relative', zIndex: 2 }}>
        {[
          ['comfort', 'Bienestar térmico, lumínico y acústico medible — no presunto.'],
          ['tek', 'Tecnología Loxone · KNX · Home Assistant. Estándares abiertos, no jaulas.'],
          ['.', 'El punto final. La instalación cerrada, documentada, soportada.'],
        ].map(([k, v]) => (
          <div key={k} style={{ borderTop: '1px solid var(--line)', paddingTop: 20 }}>
            <div className="serif" style={{ fontSize: isMobile ? 36 : 48, fontStyle: 'italic', color: k === '.' ? 'var(--brand-orange)' : 'var(--text-0)', lineHeight: 0.9, marginBottom: 12 }}>{k}</div>
            <p style={{ fontSize: 14, lineHeight: 1.5, color: 'var(--text-1)', textWrap: 'pretty' }}>{v}</p>
          </div>
        ))}
      </div>
    </section>
  );
};

// =====================================================================
// CTA
// =====================================================================

const CTA = ({ width: w }) => {
  const { width, isMobile } = useResponsive(w);
  return (
    <section id="ambrosio" style={{ padding: isMobile ? '96px 24px 64px' : '160px 56px 96px', position: 'relative', overflow: 'hidden' }}>
      {/* warm + cool ambient glow */}
      <div style={{
        position: 'absolute', top: '-20%', left: '20%',
        width: 700, height: 700,
        background: 'radial-gradient(ellipse, rgba(255,106,26,0.25), transparent 60%)',
        filter: 'blur(60px)', pointerEvents: 'none',
      }} />
      <div style={{
        position: 'absolute', top: '0%', right: '15%',
        width: 600, height: 600,
        background: 'radial-gradient(ellipse, rgba(25,194,214,0.18), transparent 60%)',
        filter: 'blur(60px)', pointerEvents: 'none',
      }} />

      <div style={{
        position: 'relative', maxWidth: 1180, margin: '0 auto',
        padding: isMobile ? '48px 24px' : '88px 72px',
        border: '1px solid var(--line-strong)',
        borderRadius: 28,
        background: 'linear-gradient(180deg, rgba(18,14,22,0.92), rgba(8,8,12,0.95))',
        backdropFilter: 'blur(20px)',
        overflow: 'hidden',
      }}>
        {/* gradient hairline */}
        <div style={{ position: 'absolute', top: 0, left: '15%', right: '15%', height: 1, background: 'var(--grad-brand-line)' }} />

        <div style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : '1.15fr 1fr',
          gap: isMobile ? 40 : 64,
          alignItems: 'center',
        }}>
          {/* Left — copy + CTA */}
          <div>
            <div className="eyebrow" style={{ marginBottom: 24 }}>
              <span>HABLEMOS · ATENCIÓN INMEDIATA</span>
            </div>
            <h2 style={{
              fontSize: isMobile ? 32 : 72,
              lineHeight: isMobile ? 1.05 : 0.98,
              letterSpacing: '-0.035em',
              fontWeight: 500,
              marginBottom: isMobile ? 18 : 24,
              textWrap: 'balance',
            }}>
              {isMobile ? (
                <><span className="serif" style={{ fontStyle: 'italic' }}>Hablamos</span> <span className="grad-text">por WhatsApp</span>.</>
              ) : (
                <>Cuéntanos tu proyecto.<br/><span className="serif" style={{ fontStyle: 'italic' }}>Ambrosio te atiende</span> <span className="grad-text">por WhatsApp</span>.</>
              )}
            </h2>
            <p style={{ fontSize: isMobile ? 16 : 18, lineHeight: 1.55, color: 'var(--text-1)', maxWidth: 520, marginBottom: 32, textWrap: 'pretty' }}>
              Ambrosio puede atenderte por WhatsApp. Si prefieres llamada, deja tus datos y Comfortek preparará el contacto.
            </p>

            <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', alignItems: 'center' }}>
              <a href="https://wa.me/34601920198?text=Hola%20Ambrosio%2C%20me%20gustar%C3%ADa%20informaci%C3%B3n%20sobre%20dom%C3%B3tica."
                target="_blank" rel="noopener noreferrer"
                style={{
                  display: 'inline-flex', alignItems: 'center', gap: 10,
                  padding: '16px 26px', borderRadius: 999, textDecoration: 'none',
                  background: '#25D366', color: 'white',
                  fontWeight: 600, fontSize: 16,
                  boxShadow: '0 8px 28px rgba(37,211,102,0.4)',
                }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="white"><path d="M20.52 3.48A11.93 11.93 0 0 0 12 0C5.37 0 0 5.37 0 12c0 2.11.55 4.16 1.6 5.97L0 24l6.18-1.62A11.94 11.94 0 0 0 12 24c6.63 0 12-5.37 12-12 0-3.21-1.25-6.22-3.48-8.52zM12 22c-1.85 0-3.66-.5-5.24-1.44l-.37-.22-3.87 1.02 1.03-3.77-.24-.38A9.94 9.94 0 0 1 2 12c0-5.52 4.48-10 10-10s10 4.48 10 10-4.48 10-10 10zm5.47-7.4c-.3-.15-1.77-.87-2.04-.97-.28-.1-.48-.15-.68.15-.2.3-.77.97-.94 1.17-.17.2-.35.22-.65.07-.3-.15-1.26-.46-2.4-1.48-.89-.79-1.49-1.77-1.66-2.07-.17-.3-.02-.46.13-.61.13-.13.3-.35.45-.52.15-.17.2-.3.3-.5.1-.2.05-.37-.02-.52-.08-.15-.68-1.64-.93-2.25-.24-.59-.49-.51-.68-.52h-.58c-.2 0-.52.07-.79.37s-1.04 1.02-1.04 2.48 1.07 2.88 1.22 3.08c.15.2 2.1 3.2 5.08 4.49.71.31 1.27.49 1.7.63.72.23 1.37.2 1.88.12.57-.09 1.77-.72 2.02-1.42.25-.7.25-1.3.17-1.42-.07-.12-.27-.2-.57-.35z"/></svg>
                Hablar con Ambrosio por WhatsApp
              </a>
              <button type="button" onClick={() => window.openCallbackModal && window.openCallbackModal()}
                style={{
                  display: 'inline-flex', alignItems: 'center', gap: 8,
                  padding: '14px 22px', borderRadius: 999, cursor: 'pointer',
                  background: 'transparent', color: 'var(--text-1)',
                  border: '1px solid var(--line-strong)', fontSize: 14,
                }}>
                Solicitar llamada
              </button>
            </div>

            <div style={{ marginTop: 18, display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
              <a href="tel:+34610246360" style={{ color: 'var(--text-1)', textDecoration: 'none', fontSize: 14, display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                <svg width="13" height="13" viewBox="0 0 14 14" fill="none"><path d="M12.5 9.7v2.1c0 .5-.5 1-1 1C5.7 12.5 1.5 8.3 1.5 2.5c0-.5.5-1 1-1h2.1c.5 0 .9.3 1 .8l.5 2.2c.1.4 0 .7-.3 1L4.7 6.6c1 1.8 2.6 3.4 4.4 4.4l1.1-1.1c.3-.3.6-.4 1-.3l2.2.5c.4.1.7.5.7 1z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/></svg>
                <span className="mono" style={{ letterSpacing: 0.08 }}>+34 610 246 360</span>
              </a>
              <span style={{ color: 'var(--text-3)' }}>·</span>
              <a href="mailto:info@comfortek.es" style={{ color: 'var(--text-1)', textDecoration: 'none', fontSize: 14 }}>info@comfortek.es</a>
            </div>
          </div>

          {/* Right — Ambrosio assistant card */}
          <AmbrosioCard isMobile={isMobile} />
        </div>

        {/* meta strip */}
        <div style={{ marginTop: isMobile ? 40 : 56, paddingTop: 28, borderTop: '1px solid var(--line)', display: 'flex', flexWrap: 'wrap', gap: isMobile ? 24 : 56 }}>
          {[
            ['Lloret de Mar','Girona · Costa Brava'],
            ['Visita técnica','Gratuita y sin compromiso'],
            ['Soporte 24/7','SLA con clientes activos'],
          ].map(([a,b]) => (
            <div key={a}>
              <div className="numlabel">{a.toUpperCase()}</div>
              <div style={{ fontSize: 14, color: 'var(--text-1)', marginTop: 4 }}>{b}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

const AmbrosioCard = ({ isMobile }) => {
  const allMsgs = [
    { from: 'ambrosio', text: 'Hola 👋 Soy Ambrosio. ¿Es para una vivienda o un negocio?' },
    { from: 'client',   text: 'Negocio. Un restaurante en Lloret, quiero control de clima y accesos.' },
    { from: 'ambrosio', text: 'Perfecto. ¿Cuántos metros tiene el local aproximadamente?' },
    { from: 'client',   text: 'Unos 200m², planta baja.' },
    { from: 'ambrosio', text: '¡Ideal para Loxone! ¿Te viene bien que Comfortek te llame esta semana para hacer una valoración sin compromiso?', tick: true },
  ];
  // Mobile: 3 mensajes (1 saludo + 1 cliente + 1 cierre con tick) para no comer pantalla
  const msgs = isMobile
    ? [allMsgs[0], allMsgs[1], allMsgs[4]]
    : allMsgs;
  return (
    <div style={{
      background: '#0b141a',
      border: '1px solid rgba(255,255,255,0.1)',
      borderRadius: 22,
      overflow: 'hidden',
      boxShadow: '0 30px 80px rgba(0,0,0,0.5)',
    }}>
      {/* WA header */}
      <div style={{
        background: '#1f2c34',
        padding: '12px 16px',
        display: 'flex', alignItems: 'center', gap: 10,
        borderBottom: '1px solid rgba(255,255,255,0.06)',
      }}>
        <div style={{
          width: 40, height: 40, borderRadius: '50%', flexShrink: 0,
          background: 'linear-gradient(135deg, #19c2d6, #0a8fa3)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 16, fontWeight: 700, color: 'white',
        }}>A</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: '#e9edef' }}>Ambrosio · Comfortek</div>
          <div style={{ fontSize: 11.5, color: '#00a884', display: 'flex', alignItems: 'center', gap: 4 }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#00a884', display: 'inline-block' }} />
            En línea
          </div>
        </div>
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" style={{ color: 'rgba(255,255,255,0.4)' }}><circle cx="12" cy="5" r="1.5" fill="currentColor"/><circle cx="12" cy="12" r="1.5" fill="currentColor"/><circle cx="12" cy="19" r="1.5" fill="currentColor"/></svg>
      </div>

      {/* Messages */}
      <div style={{
        padding: '12px 12px 8px',
        background: '#0b141a',
        display: 'flex', flexDirection: 'column', gap: 4,
      }}>
        <div style={{ textAlign: 'center', marginBottom: 8 }}>
          <span style={{ fontSize: 11, background: 'rgba(17,27,33,0.9)', color: '#8696a0', padding: '3px 10px', borderRadius: 999 }}>HOY</span>
        </div>
        {msgs.map((m, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: m.from === 'client' ? 'flex-end' : 'flex-start', marginBottom: 2 }}>
            <div style={{
              maxWidth: '82%', padding: '7px 10px 5px',
              borderRadius: m.from === 'client' ? '12px 12px 2px 12px' : '12px 12px 12px 2px',
              background: m.from === 'client' ? '#005c4b' : '#1f2c34',
              color: '#e9edef', fontSize: isMobile ? 12 : 13, lineHeight: 1.45,
              boxShadow: '0 1px 2px rgba(0,0,0,0.25)',
            }}>
              {m.text}
              <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 3, marginTop: 2 }}>
                <span style={{ fontSize: 10, color: 'rgba(134,150,160,0.8)' }}>
                  {['10:14','10:15','10:15','10:16','10:16'][i]}
                </span>
                {m.from === 'client' && (
                  <svg width="14" height="10" viewBox="0 0 16 11" fill="none">
                    <path d="M1 5.5L5 9.5L11 1.5" stroke={m.tick ? '#53bdeb' : '#8696a0'} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                    <path d="M6 5.5L10 9.5L15 1.5" stroke={m.tick ? '#53bdeb' : '#8696a0'} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* WA input bar */}
      <div style={{
        background: '#1f2c34', padding: '8px 12px',
        display: 'flex', alignItems: 'center', gap: 8,
        borderTop: '1px solid rgba(255,255,255,0.05)',
      }}>
        <div style={{
          flex: 1, background: '#2a3942', borderRadius: 20,
          padding: '8px 14px', fontSize: 12.5, color: '#8696a0',
        }}>Escribe un mensaje…</div>
        <a href="https://wa.me/34601920198?text=Hola%20Ambrosio%2C%20me%20gustar%C3%ADa%20informaci%C3%B3n%20sobre%20dom%C3%B3tica."
          target="_blank" rel="noopener noreferrer"
          style={{
            width: 38, height: 38, borderRadius: '50%', background: '#00a884',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            textDecoration: 'none',
          }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="white"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>
        </a>
      </div>
    </div>
  );
};
// =====================================================================
// FLOATING MOBILE CTA — Ambrosio call button
// =====================================================================

const MobileFloatingCTA = ({ width = 1440 }) => {
  const isMobile = width < 600;
  if (!isMobile) return null;
  return (
    <div style={{
      position: 'absolute', bottom: 16, left: 16, right: 16, zIndex: 50,
      pointerEvents: 'none',
    }}>
      <button type="button" className="btn-ambrosio" onClick={() => window.openCallbackModal && window.openCallbackModal()} style={{
        width: '100%', justifyContent: 'center',
        padding: '14px 20px 14px 16px', fontSize: 14,
        pointerEvents: 'auto', border: 'none', cursor: 'pointer',
        backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)',
      }}>
        <span className="pulse">
          <svg width="12" height="12" viewBox="0 0 14 14" fill="none"><path d="M12.5 9.7v2.1c0 .5-.5 1-1 1C5.7 12.5 1.5 8.3 1.5 2.5c0-.5.5-1 1-1h2.1c.5 0 .9.3 1 .8l.5 2.2c.1.4 0 .7-.3 1L4.7 6.6c1 1.8 2.6 3.4 4.4 4.4l1.1-1.1c.3-.3.6-.4 1-.3l2.2.5c.4.1.7.5.7 1z" stroke="white" strokeWidth="1.5" strokeLinejoin="round" fill="none"/></svg>
        </span>
        Recibir llamada ahora
      </button>
    </div>
  );
};

// =====================================================================
// FOOTER
// =====================================================================

const Footer = ({ width: w }) => {
  const { width, isMobile } = useResponsive(w);
  return (
    <footer style={{
      borderTop: '1px solid var(--line)',
      padding: isMobile ? '48px 24px 32px' : '64px 56px 40px',
    }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: isMobile ? '1fr' : '2fr 1fr 1fr 1fr 1fr',
          gap: isMobile ? 40 : 48,
          marginBottom: 56,
        }}>
          <div>
            <window.Logo size={32} withText tagline />
            <p style={{ marginTop: 20, fontSize: 14, lineHeight: 1.55, color: 'var(--text-1)', maxWidth: 320 }}>
              Domótica, automatización e integraciones tecnológicas. Vivienda y negocio. Lloret de Mar, Girona.
            </p>
          </div>
          {[
            { t: 'Servicios', l: [
              { name: 'Domótica integral', href: 'servicios.html' },
              { name: 'IA & Ambrosio', href: 'ia.html' },
              { name: 'Iluminación', href: 'servicios.html' },
              { name: 'Clima', href: 'servicios.html' },
              { name: 'Seguridad', href: 'servicios.html' },
              { name: 'Audio multiroom', href: 'servicios.html' },
            ] },
            { t: 'Tecnologías', l: [
              { name: 'Loxone', href: 'tecnologias.html' },
              { name: 'KNX', href: 'tecnologias.html' },
              { name: 'Home Assistant', href: 'tecnologias.html' },
              { name: 'Hikvision', href: 'tecnologias.html' },
              { name: 'Sonos', href: 'tecnologias.html' },
            ] },
            { t: 'Empresa', l: [
              { name: 'Proyectos', href: 'proyectos.html' },
              { name: 'Proceso', href: 'proceso.html' },
              { name: 'Nosotros', href: 'nosotros.html' },
              { name: 'IA', href: 'ia.html' },
              { name: 'Contacto', href: 'contacto.html' },
            ] },
            { t: 'Legal', l: [
              { name: 'Aviso legal', href: 'aviso-legal.html' },
              { name: 'Privacidad', href: 'privacidad.html' },
            ] },
          ].map(c => (
            <div key={c.t}>
              <div className="numlabel" style={{ marginBottom: 16 }}>{c.t.toUpperCase()}</div>
              <ul style={{ listStyle: 'none', display: 'grid', gap: 10 }}>
                {c.l.map(i => <li key={i.name}><a href={i.href} style={{ color: 'var(--text-1)', textDecoration: 'none', fontSize: 14 }}>{i.name}</a></li>)}
              </ul>
            </div>
          ))}
        </div>
        <div style={{
          paddingTop: 24,
          borderTop: '1px solid var(--line)',
          display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16,
          fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-2)', letterSpacing: '0.1em',
        }}>
          <span>© 2026 COMFORTEK · TODOS LOS DERECHOS RESERVADOS</span>
          <span>DESIGNED IN GIRONA · BUILT TO LAST</span>
        </div>
      </div>
    </footer>
  );
};

// =====================================================================
// SECTION wrapper
// =====================================================================

const Section = ({ eyebrow, title, subtitle, children, isMobile }) => (
  <section className="cmf-section" style={{
    maxWidth: 1280,
    margin: '0 auto',
    padding: isMobile ? '72px 24px' : '128px 56px',
  }}>
    <header className="cmf-section-header" style={{
      display: 'grid',
      gridTemplateColumns: '1fr',
      alignItems: 'end',
      gap: 24,
      marginBottom: isMobile ? 36 : 64,
    }}>
      <div>
        <div className="eyebrow" style={{ marginBottom: 20 }}>
          <span>{eyebrow}</span>
        </div>
        <h2 style={{
          fontSize: isMobile ? 36 : 64,
          lineHeight: isMobile ? 1.05 : 1,
          letterSpacing: '-0.03em',
          fontWeight: 500,
          textWrap: 'balance',
        }}>{title}</h2>
        {subtitle && (
          <p className="cmf-section-subtitle" style={{ fontSize: isMobile ? 14.5 : 16, lineHeight: 1.55, color: 'var(--text-1)', marginTop: 18, maxWidth: 560, textWrap: 'pretty' }}>{subtitle}</p>
        )}
      </div>
    </header>
    {children}
  </section>
);

// =====================================================================
// AILAYER — IA + agentes como pilar narrativo, con Ambrosio como rostro
// =====================================================================

const AILayer = () => {
  const { isMobile } = useResponsive();
  const allCapabilities = [
    { label: 'Recibir y hacer llamadas', desc: 'voz natural, 24/7' },
    { label: 'Preparar presupuestos', desc: 'desde la conversación' },
    { label: 'Enviar y recibir email', desc: 'seguimiento automático' },
    { label: 'WhatsApp bidireccional', desc: 'el canal del cliente' },
    { label: 'Base de datos viva', desc: 'Comfortek In · ficha por cliente' },
  ];
  // En mobile mostramos 4 (las 5 saturan visualmente)
  const capabilities = isMobile ? allCapabilities.slice(0, 4) : allCapabilities;

  const pillars = [
    {
      tag: 'CONTROL CONVERSACIONAL',
      name: 'Habla con la casa.',
      role: 'voz, texto, gestos',
      desc: 'LLM local o cloud integrado en Home Assistant y Loxone. "Modo cena en el salón", "deja la oficina lista para mañana", "cuánto consumió ayer la aerotermia". Sin frases mágicas memorizadas.',
      descShort: '"Modo cena", "oficina lista mañana". LLM sobre HA y Loxone.',
      kpi: ['ollama · claude · gpt', 'mcp + home assistant', 'privado u online'],
      accent: '#ff7a3d',
    },
    {
      tag: 'AUTOMATIZACIÓN PREDICTIVA',
      name: 'Aprende sola.',
      role: 'patrones reales',
      desc: 'La instalación observa ocupación, clima, energía y rutinas. Ajusta climatización antes de que llegues, baja persianas cuando va a calentar, avisa si la fotovoltaica rinde menos de lo esperado.',
      descShort: 'Ajusta clima y persianas antes de que pidas. Avisa de fallos.',
      kpi: ['clima · ocupación · energía', 'mantenimiento predictivo', 'sin nube obligada'],
      accent: '#7c5cff',
    },
    {
      tag: 'PRÓXIMOS AGENTES',
      name: 'Más en camino.',
      role: 'mantenimiento, obra, energía',
      desc: 'Ambrosio es el primero. Después llegan agentes para mantenimiento (avisa antes de que falle), para obra (coordina con instaladores) y para energía (optimiza fotovoltaica + aerotermia en tiempo real).',
      descShort: 'Llegan agentes de mantenimiento, obra y energía.',
      kpi: ['agente mantenimiento · q3', 'agente energía · q4', 'agente obra · 2026'],
      accent: '#19c2d6',
    },
  ];

  return (
    <window.Section id="ia"
      eyebrow="03 · CAPA IA · COMFORTEK IN"
      title={<>La domótica conecta tu instalación.<br/><span className="serif" style={{ fontStyle: 'italic', fontWeight: 400 }}>La IA la hace más fácil de usar.</span></>}
      subtitle={isMobile
        ? 'Ambrosio es el agente IA de Comfortek. Atiende, presupuesta y gestiona — con el respaldo técnico de Comfortek detrás.'
        : 'Comfortek tiene un agente de IA propio. Se llama Ambrosio. Atiende a tus clientes, les prepara presupuestos, gestiona sus instalaciones, manda mails y WhatsApps — y ayuda a gestionar muchas de las solicitudes habituales de un cliente, siempre con el respaldo técnico de Comfortek. Una nueva forma de dar soporte en el mundo de la integración.'}>

      {/* ============================================================ */}
      {/* AMBROSIO HERO BLOCK — portrait + capabilities                */}
      {/* ============================================================ */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'minmax(0, 1.05fr) minmax(0, 1fr)',
        gap: 0,
        border: '1px solid var(--line-strong)',
        borderRadius: 18,
        overflow: 'hidden',
        background: 'linear-gradient(135deg, rgba(25,194,214,0.05) 0%, rgba(255,122,61,0.04) 100%)',
        marginBottom: 56,
      }} className="ambrosio-block">

        {/* Portrait pane — editorial, mostly photo */}
        <div style={{
          position: 'relative',
          minHeight: 540,
          background: '#f5f5f3',
          overflow: 'hidden',
        }}>
          <img src="img/ambrosio.png" alt="Ambrosio · agente de IA de Comfortek"
            style={{
              position: 'absolute', inset: 0,
              width: '100%', height: '100%',
              objectFit: 'cover', objectPosition: 'center 28%',
              filter: 'grayscale(100%) contrast(1.05)',
            }} />

          {/* Subtle vignette into the right side so it bleeds into the dark pane */}
          <div style={{
            position: 'absolute', inset: 0,
            background: 'linear-gradient(90deg, transparent 50%, rgba(245,245,243,0) 75%, rgba(8,8,13,0.4) 100%)',
            pointerEvents: 'none',
          }} />

          {/* Top metadata strip */}
          <div style={{
            position: 'absolute', top: 20, left: 20, right: 20,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            color: '#0a0a12',
          }}>
            <div className="mono" style={{
              fontSize: 10, letterSpacing: '0.18em',
              padding: '6px 10px',
              border: '1px solid rgba(10,10,18,0.18)',
              borderRadius: 999, background: 'rgba(255,255,255,0.6)', backdropFilter: 'blur(6px)',
            }}>● EN LÍNEA · ATENDIENDO</div>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', color: 'rgba(10,10,18,0.55)' }}>
              AMBROSIO · v1.0
            </div>
          </div>

          {/* Bottom name plate */}
          <div style={{
            position: 'absolute', bottom: 0, left: 0, right: 0,
            padding: '24px 28px',
            background: 'linear-gradient(180deg, rgba(245,245,243,0) 0%, rgba(245,245,243,0.92) 60%, rgba(245,245,243,1) 100%)',
            color: '#0a0a12',
          }}>
            <div style={{ fontSize: 44, fontWeight: 500, letterSpacing: '-0.025em', lineHeight: 1, marginBottom: 4 }}>
              Ambrosio
            </div>
            <div className="serif" style={{ fontStyle: 'italic', fontSize: 16, color: 'rgba(10,10,18,0.7)' }}>
              Agente IA de Comfortek · asistencia comercial y soporte
            </div>
          </div>
        </div>

        {/* Capabilities pane */}
        <div style={{
          padding: '36px 36px 32px',
          display: 'flex', flexDirection: 'column',
          background: 'linear-gradient(180deg, rgba(255,255,255,0.02) 0%, rgba(255,255,255,0) 100%)',
        }}>
          <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.18em', color: 'var(--brand-cyan, #19c2d6)', marginBottom: 14 }}>
            CAPACIDADES REALES · NO PROMESAS
          </div>
          <h3 style={{ fontSize: 28, fontWeight: 500, letterSpacing: '-0.02em', lineHeight: 1.1, marginBottom: 14 }}>
            Trabaja como un comercial.<br/>
            <span className="serif" style={{ fontStyle: 'italic', fontWeight: 400, color: 'var(--text-1)' }}>Sin descansos. Sin olvidos.</span>
          </h3>
          <p style={{ fontSize: 14.5, lineHeight: 1.6, color: 'var(--text-1)', marginBottom: 22, textWrap: 'pretty' }}>
            {isMobile
              ? <>Conectado a <strong style={{ color: 'var(--text-0)', fontWeight: 500 }}>Comfortek In</strong>: ficha viva de cada instalación. Resuelve dudas de noche y cierra visitas el lunes.</>
              : <>Ambrosio vive conectado a <strong style={{ color: 'var(--text-0)', fontWeight: 500 }}>Comfortek In</strong> — la base de datos donde está la instalación de cada cliente. Y al estar dentro de nuestro mundo, <strong style={{ color: 'var(--text-0)', fontWeight: 500 }}>puede ayudar en muchas tareas clave del día a día</strong>: desde resolver una duda a las 3 de la mañana hasta cerrar una visita técnica el lunes.</>
            }
          </p>

          <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 0 }}>
            {capabilities.map((c, i) => (
              <li key={c.label} style={{
                display: 'grid',
                gridTemplateColumns: 'auto 1fr auto',
                alignItems: 'center', gap: 14,
                padding: '14px 0',
                borderTop: i === 0 ? '1px solid var(--line)' : 'none',
                borderBottom: '1px solid var(--line)',
              }}>
                <span className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--text-3, #5a5a6a)' }}>
                  {String(i+1).padStart(2,'0')}
                </span>
                <div>
                  <div style={{ fontSize: 14.5, fontWeight: 500, color: 'var(--text-0)', lineHeight: 1.2 }}>{c.label}</div>
                  <div style={{ fontSize: 12, color: 'var(--text-2)', marginTop: 2 }}>{c.desc}</div>
                </div>
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ color: 'var(--brand-cyan, #19c2d6)' }}>
                  <path d="M2 7L6 11L12 3" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </li>
            ))}
          </ul>

          <p style={{ fontSize: 11.5, color: 'var(--text-3, #6a6a7a)', marginTop: 14, lineHeight: 1.5, fontStyle: 'italic' }}>
            Capacidades en despliegue progresivo según instalación y servicio contratado.
          </p>

          <div style={{ marginTop: 22, display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
            <a href="https://wa.me/34601920198?text=Hola%20Ambrosio%2C%20me%20gustar%C3%ADa%20informaci%C3%B3n%20sobre%20dom%C3%B3tica."
              target="_blank" rel="noopener noreferrer"
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 9,
                padding: '12px 18px', borderRadius: 999, textDecoration: 'none',
                background: 'linear-gradient(135deg, #25D366 0%, #1ea34c 100%)',
                color: 'white', fontWeight: 600, fontSize: 13,
                boxShadow: '0 6px 22px rgba(37,211,102,0.4), inset 0 1px 0 rgba(255,255,255,0.2)',
                border: '1px solid rgba(255,255,255,0.18)',
              }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="white" aria-hidden><path d="M20.52 3.48A11.93 11.93 0 0 0 12 0C5.37 0 0 5.37 0 12c0 2.11.55 4.16 1.6 5.97L0 24l6.18-1.62A11.94 11.94 0 0 0 12 24c6.63 0 12-5.37 12-12 0-3.21-1.25-6.22-3.48-8.52zM12 22c-1.85 0-3.66-.5-5.24-1.44l-.37-.22-3.87 1.02 1.03-3.77-.24-.38A9.94 9.94 0 0 1 2 12c0-5.52 4.48-10 10-10s10 4.48 10 10-4.48 10-10 10zm5.47-7.4c-.3-.15-1.77-.87-2.04-.97-.28-.1-.48-.15-.68.15-.2.3-.77.97-.94 1.17-.17.2-.35.22-.65.07-.3-.15-1.26-.46-2.4-1.48-.89-.79-1.49-1.77-1.66-2.07-.17-.3-.02-.46.13-.61.13-.13.3-.35.45-.52.15-.17.2-.3.3-.5.1-.2.05-.37-.02-.52-.08-.15-.68-1.64-.93-2.25-.24-.59-.49-.51-.68-.52h-.58c-.2 0-.52.07-.79.37s-1.04 1.02-1.04 2.48 1.07 2.88 1.22 3.08c.15.2 2.1 3.2 5.08 4.49.71.31 1.27.49 1.7.63.72.23 1.37.2 1.88.12.57-.09 1.77-.72 2.02-1.42.25-.7.25-1.3.17-1.42-.07-.12-.27-.2-.57-.35z"/></svg>
              Hablar con Ambrosio por WhatsApp
            </a>
            <button type="button" onClick={() => window.openCallbackModal && window.openCallbackModal()}
              style={{
                padding: '10px 14px', fontSize: 12, cursor: 'pointer',
                background: 'rgba(255,106,26,0.10)', color: '#ffb085',
                border: '1px solid rgba(255,106,26,0.45)', borderRadius: 999,
                fontWeight: 500,
              }}>
              Solicitar llamada
            </button>
            <span className="mono" style={{ fontSize: 10.5, letterSpacing: '0.14em', color: 'var(--text-2)', alignSelf: 'center' }}>
              ● 24/7 · ES + CA + EN
            </span>
          </div>
        </div>
      </div>

      {/* ============================================================ */}
      {/* PILLARS — capa IA completa                                   */}
      {/* ============================================================ */}
      <div className="mono" style={{ fontSize: 11, letterSpacing: '0.18em', color: 'var(--text-2)', marginBottom: 20 }}>
        Y NO ACABA AHÍ —
      </div>
      <div className="ai-pillars" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 20 }}>
        {pillars.map((p) => (
          <article key={p.name} className="card ai-pillar" style={{
            padding: 26,
            position: 'relative',
            display: 'flex', flexDirection: 'column',
            background: 'linear-gradient(180deg, rgba(255,255,255,0.022) 0%, rgba(255,255,255,0.004) 100%)',
            overflow: 'hidden',
          }}>
            <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 2, background: p.accent, opacity: 0.7 }} />

            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', color: p.accent, marginBottom: 16 }}>{p.tag}</div>

            <h3 style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em', lineHeight: 1.1, marginBottom: 4 }}>
              {p.name}
            </h3>
            <div className="serif" style={{ fontStyle: 'italic', fontSize: 14, color: 'var(--text-2)', marginBottom: 14 }}>
              {p.role}
            </div>
            <p style={{ fontSize: 13.5, lineHeight: 1.6, color: 'var(--text-1)', marginBottom: 18, textWrap: 'pretty', flex: 1 }}>
              {isMobile && p.descShort ? p.descShort : p.desc}
            </p>

            <div style={{ borderTop: '1px solid var(--line)', paddingTop: 12, display: 'flex', flexDirection: 'column', gap: 6 }}>
              {p.kpi.map((k) => (
                <div key={k} className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', color: 'var(--text-2)', display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ width: 4, height: 4, borderRadius: 999, background: p.accent }} />
                  {k.toUpperCase()}
                </div>
              ))}
            </div>
          </article>
        ))}
      </div>

      {/* Manifesto strip */}
      <div className="ai-manifesto" style={{
        marginTop: 36,
        padding: '24px 28px',
        border: '1px solid var(--line-strong)',
        borderRadius: 14,
        background: 'linear-gradient(135deg, rgba(25,194,214,0.06) 0%, rgba(255,122,61,0.06) 100%)',
        display: 'grid',
        gridTemplateColumns: 'auto 1fr',
        gap: 24,
        alignItems: 'center',
      }}>
        <div className="mono" style={{
          fontSize: 11, letterSpacing: '0.18em', color: 'var(--text-1)',
          padding: '6px 12px', border: '1px solid var(--line-strong)', borderRadius: 999,
          whiteSpace: 'nowrap',
        }}>● COMFORTEK · IA NATIVA</div>
        <p style={{ fontSize: 15, lineHeight: 1.55, color: 'var(--text-0)', textWrap: 'pretty', margin: 0 }}>
          {isMobile
            ? <>Diseñamos la <strong>capa IA junto al cableado</strong>. LLM local o cloud, MCP para conectar todo.</>
            : <>No vendemos "asistentes inteligentes" pegados con cinta. Diseñamos la <strong>capa IA junto al cableado</strong> — con LLM local cuando hace falta privacidad, cloud cuando hace falta potencia, y MCP para conectar todo lo que tengas.</>
          }
        </p>
      </div>

      <style>{`
        @media (max-width: 840px) {
          .ambrosio-block { grid-template-columns: 1fr !important; }
          .ambrosio-block > div:first-child { min-height: 340px !important; }
          .ambrosio-block > div:last-child { padding: 28px 24px 24px !important; }
        }
        /* Mobile: pillars en scroll horizontal con snap, una visible por viewport */
        @media (max-width: 760px) {
          .ai-pillars {
            display: flex !important;
            grid-template-columns: none !important;
            gap: 14px !important;
            overflow-x: auto;
            scroll-snap-type: x mandatory;
            scroll-padding: 24px;
            padding: 4px 24px 14px;
            margin: 0 -24px;
            scrollbar-width: thin;
          }
          .ai-pillar {
            flex: 0 0 86%;
            scroll-snap-align: start;
            padding: 22px !important;
          }
          .ai-pillar h3 { font-size: 20px !important; }
          .ai-manifesto {
            grid-template-columns: 1fr !important;
            padding: 20px 22px !important;
            gap: 12px !important;
          }
        }
      `}</style>
    </window.Section>
  );
};

Object.assign(window, { Services, Why, Projects, Brands, Process, Testimonials, CTA, Footer, Section, MobileFloatingCTA, AILayer });
