// SERENA Hollywood — main content sections
// Hero · Stats · El proyecto (+ galería) · Unidades · Amenities · In & around

const { useState: useState_S, useEffect: useEffect_S, useRef: useRef_S } = React;

// SERENA Hollywood design-system components
const DS = window.SERENAHollywoodDesignSystem_24d468 || {};
const { Headline, SectionNumber, StatBlock, AmenityTile, CreditMark, Button, TextField, SelectField } = DS;
const DS_ASSETS = "hollywood/ds-assets/";

const TIPO_OPTIONS = [
{ id: "2amb", label: "2 ambientes · 60 a 85 m²" },
{ id: "3amb", label: "3 ambientes · 85 a 145 m²" },
{ id: "4amb", label: "4 ambientes · 130 a 187 m²" },
{ id: "cochera", label: "Cochera / bicicletero" },
{ id: "info", label: "Todavía no lo sé" }];

const WA_NUMBER = "5491131170399";
const WA_MSG = encodeURIComponent("Hola, me contacto desde la web de SERENA Hollywood. Me interesa recibir información, valores y disponibilidad del proyecto.");
const WA_URL = `https://wa.me/${WA_NUMBER}?text=${WA_MSG}`;

const LEAD_MAIL = "contacto@pbgdesarrollos.com.ar";

function leadToMailto(payload) {
  const L = {
    form: "Origen", name: "Nombre", email: "Mail", phone: "Teléfono",
    tipo: "Tipología", interest: "Tipología", message: "Mensaje" };
  const body = Object.entries(payload).
  filter(([, v]) => v).
  map(([k, v]) => `${L[k] || k}: ${v}`).
  concat([`Página: ${window.location.href}`]).join("\n");
  return `mailto:${LEAD_MAIL}?subject=${encodeURIComponent("Consulta web — SERENA Hollywood")}&body=${encodeURIComponent(body)}`;
}

async function submitLead(payload) {
  // Lidz parsea texto: mandamos el label de la tipología, no el id.
  const tipoId = payload.tipo || payload.interest;
  const tipo = (TIPO_OPTIONS.find((t) => t.id === tipoId) || {}).label || tipoId || "";
  try {
    const res = await fetch("/api/contact", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        form: payload.form,
        name: payload.name,
        email: payload.email,
        phone: payload.phone || "",
        tipo,
        message: payload.message || "",
        source_url: window.location.href
      })
    });
    if (!res.ok) throw new Error(res.status);
    return { ok: true, via: "api" };
  } catch (err) {
    console.warn("[Serena Hollywood] Fallo el envío del lead, se usa mail:", err);
    window.open(leadToMailto(payload), "_blank", "noopener");
    return { ok: true, via: "mailto" };
  }
}

async function downloadBrochure() {
  const cfg = window.SERENA_CONFIG || {};
  const url = cfg.BROCHURE_URL || "./hollywood/assets/SERENA_Hollywood_brochure.pdf";
  const filename = cfg.BROCHURE_FILENAME || "SERENA Hollywood - Brochure.pdf";
  const trigger = (href, revoke) => {
    const a = document.createElement("a");
    a.href = href;
    a.download = filename;
    a.rel = "noopener";
    a.target = "_blank";
    document.body.appendChild(a);
    a.click();
    setTimeout(() => { a.remove(); if (revoke) URL.revokeObjectURL(href); }, 4000);
  };
  try {
    const res = await fetch(url);
    if (!res.ok) throw new Error(res.status);
    const blob = await res.blob();
    trigger(URL.createObjectURL(blob), true);
  } catch (err) {
    console.warn("[Serena Hollywood] Descarga directa no disponible, abriendo el PDF:", err);
    window.open(url, "_blank", "noopener");
  }
}

/* ── HERO ────────────────────────────────────────────────────── */

function Hero() {
  const [tipo, setTipo] = useState_S("");
  const [name, setName] = useState_S("");
  const [email, setEmail] = useState_S("");
  const [sent, setSent] = useState_S(false);
  const [busy, setBusy] = useState_S(false);

  const emailValid = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email.trim());
  const valid = tipo && name.trim().length > 1 && emailValid;

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!valid || busy) return;
    setBusy(true);
    await submitLead({ form: "hero", name: name.trim(), email: email.trim(), tipo });
    setBusy(false);
    setSent(true);
    setTimeout(downloadBrochure, 400);
  };

  return (
    <section className="hero" id="top" data-screen-label="Hero">
      <div className="hero__media" style={{ backgroundImage: `url(${window.__resources.extDusk})` }} />
      <div className="hero__veil" />

      <div className="hero__inner">
        <div className="hero__col-left">
          <img className="hero__logo" src={window.__resources.serenaLogoWhite} alt="serena® Hollywood" />

          <Headline
            as="h1" size="l" tone="inverse" className="hero__headline"
            style={{ margin: "clamp(48px,14vh,132px) 0 32px" }}
            lines={[
            { text: "Todo lo que pasa, cerca.", register: "caps" },
            { text: "todo lo que importa,", register: "italic" },
            { text: "adentro.", register: "italic" }]} />

          <p className="hero__lede">
            Una esquina residencial conectada con la energía de Palermo Hollywood
            y un edificio pensado para reunir bienestar, diseño y vida cotidiana.
            <b> 50 unidades de 2, 3 y 4 ambientes</b> y tres niveles de amenities.
            Arquitectura <b>AISENSON</b>.
          </p>

          <div className="hero__loc">
            <b>Guatemala 5984</b>
            esquina Arévalo · Palermo Hollywood · Ciudad de Buenos Aires
          </div>
        </div>

        <aside className="hero__form" aria-label="Solicitar el brochure">
          {sent ?
          <div className="hero__form-success">
              <div className="hero__form-mark">
                <svg viewBox="0 0 24 24" strokeWidth="1.5" strokeLinecap="square"><path d="M4 12.5 L10 18 L20 6" /></svg>
              </div>
              <h3>Gracias, <em>{name.split(" ")[0]}</em></h3>
              <p>
                Recibimos tu pedido. El brochure debería estar descargándose;
                si no se inició, tocá el botón de abajo.
              </p>
              <button type="button" className="hero__form-wa" onClick={downloadBrochure} style={{ background: "var(--bone-50)", color: "var(--graphite-900)" }}>
                <span>Descargar brochure (PDF)</span>
                <span className="arrow">↓</span>
              </button>
              <a className="hero__form-wa" href={WA_URL} target="_blank" rel="noopener noreferrer">
                <span>Escribir por WhatsApp</span>
                <span className="arrow">→</span>
              </a>
            </div> :

          <form className="hero__form-inner" onSubmit={onSubmit} noValidate>
              <div className="hero__form-head">
                <span className="lab">Recibí el brochure</span>
                <span className="step">30 seg</span>
              </div>

              <TextField tone="inverse" label="Nombre" type="text" placeholder="Ej. María Lasarte"
            value={name} onChange={(e) => setName(e.target.value)} />

              <TextField tone="inverse" label="Correo electrónico" type="email" placeholder="nombre@correo.com"
            value={email} onChange={(e) => setEmail(e.target.value)} />

              <SelectField tone="inverse" label="Tipología de interés" placeholder="Seleccionar tipología…"
            options={TIPO_OPTIONS.map((t) => ({ value: t.id, label: t.label }))}
            value={tipo} onChange={(e) => setTipo(e.target.value)} />

              <Button variant="inverse" size="lg" fullWidth type="submit" disabled={!valid || busy} iconRight="↓">
                {busy ? "Enviando…" : "Descargar brochure"}
              </Button>

            </form>
          }
        </aside>
      </div>
    </section>);
}

/* ── STATS ───────────────────────────────────────────────────── */

const STATS = [
{ lab: "Unidades", num: "50" },
{ lab: "Metros cuadrados", num: "60–187 m²" },
{ lab: "Ambientes", num: "2, 3 & 4" },
{ lab: "Niveles de amenities", num: "3" }];

function StatsBand() {
  return (
    <section className="stats-band" data-screen-label="Stats">
      <div className="stats">
        {STATS.map((s, i) =>
        <div className="stat" key={i}>
            <StatBlock label={s.lab} value={s.num} />
          </div>
        )}
      </div>
    </section>);
}

/* ── 01. EL PROYECTO ─────────────────────────────────────────── */

function Proyecto({ onCTA }) {
  return (
    <section className="block" id="proyecto" data-screen-label="El proyecto">
      <div className="proy">
        <div className="proy__lead">
          <SectionNumber number="01" label="El proyecto" />
          <Headline size="l" style={{ marginTop: 28 }}
          lines={[{ text: "Una gran esquina", register: "caps" }, { text: "con escala de hogar", register: "italic" }]} />
        </div>

        <div className="proy__copy">
          <p>
            <b>La ciudad sucede a tu alrededor. Adentro, todo está pensado para sentirte en casa.</b>
          </p>
          <p>
            Cuarenta metros de fachada sobre dos calles, en esquina. Nueve pisos que,
            por sus horizontales, la madera y los retiros, se leen más bajos, más cerca
            y más residenciales. Locales a la calle en planta baja, cocheras por rampa
            en subsuelo y amenities distribuidos en tres niveles.
          </p>
          <p>
            Diseño inteligente, luz natural y espacios eficientes en el corazón de
            Palermo Hollywood: una forma cálida, luminosa y completa de vivir uno de
            los barrios más vibrantes de Buenos Aires.
          </p>

          <div className="proy__address-row">
            <div className="proy__addr">
              <span className="lab">Ubicación</span>
              <span className="line">Guatemala 5984, esquina Arévalo · Palermo Hollywood</span>
            </div>
            <a className="link-cta" href="#contacto" onClick={onCTA}>
              <span>Consultar disponibilidad</span>
              <span className="arrow">→</span>
            </a>
          </div>
        </div>

        <window.ProyGallery />
      </div>
    </section>);
}

/* ── 02. UNIDADES ────────────────────────────────────────────── */

const TIPOS = [
{ n: "01.", amb: "2 ambientes", m: "60 a 85", desc: "Distribución eficiente, pensada para el día a día." },
{ n: "02.", amb: "3 ambientes", m: "85 a 145", desc: "Más espacio para cada momento de la vida en casa." },
{ n: "03.", amb: "4 ambientes", m: "130 a 187", desc: "La tipología más completa del edificio." }];

const SPECS = [
{ k: "Carpinterías", v: "Piso a techo, DVH" },
{ k: "Climatización", v: "Piso radiante" },
{ k: "Cocina", v: "Independiente" },
{ k: "Acceso", v: "Cerradura electrónica" }];

function Unidades({ onCTA }) {
  return (
    <section className="block shell" id="unidades" data-screen-label="Tipologías">
      <div className="inner">
        <div className="tipo__hero">
          <div className="tipo__hero-left">
            <SectionNumber number="02" label="Tipologías" />
            <Headline size="l" style={{ marginTop: 28 }}
            lines={[{ text: "La calidez", register: "caps" }, { text: "de un hogar bien pensado", register: "italic" }]} />
            <p className="copy-lede tipo__intro">
              De 2 a 4 ambientes y superficies de 60 a 187 m². Plantas eficientes,
              cocinas independientes, toilette y vestidores en la mayoría de las
              tipologías. Luz natural, ventilación cruzada y expansiones reales.
            </p>
          </div>
          <div className="tipo__hero-img" style={{ backgroundImage: `url(${window.__resources.unit2ambCrop})` }}
          role="img" aria-label="Living comedor de una unidad de 2 ambientes" />
        </div>

        <div className="tipo__list">
          {TIPOS.map((t, i) =>
          <div className="tipo__card" key={i}>
              <div className="n">{t.n}</div>
              <div className="amb">{t.amb}</div>
              <div className="meters">{t.m}<small>m²</small></div>
              <p className="desc">{t.desc}</p>
              <a className="tipo__card-cta" href="#contacto" onClick={onCTA}>
                <span>Consultar</span>
                <span className="arrow">→</span>
              </a>
            </div>
          )}
        </div>

        <div className="tipo__specs">
          {SPECS.map((s, i) =>
          <div className="tipo__spec" key={i}>
              <div className="k">{s.k}</div>
              <div className="v">{s.v}</div>
            </div>
          )}
        </div>

        <div className="tipo__fullbleed" style={{ backgroundImage: `url(${window.__resources.unitBedroom})` }}
        role="img" aria-label="Dormitorio principal con vista al barrio" />

        <div className="tipo__bottom">
          <p className="tipo__legal">
            Las medidas definitivas surgirán del replanteo de obra y de los planos de
            subdivisión en PH (Ley 13.512). Superficies referenciales, no vinculantes.
          </p>
          <Button variant="primary" size="lg" className="tipo__brochure-cta" iconRight="↓" onClick={(e) => {e.preventDefault();downloadBrochure();}}>
            Descargar brochure
          </Button>
        </div>
      </div>
    </section>);
}

/* ── 03. AMENITIES ───────────────────────────────────────────── */

const AMENITIES = [
{ lab: "Piscina descubierta", icon: "wave" },
{ lab: "Solárium", icon: "sun" },
{ lab: "Terraza verde", icon: "deck" },
{ lab: "Sector de parrillas", icon: "flame" },
{ lab: "SUM con expansión", icon: "room" },
{ lab: "Gimnasio", icon: "gym" },
{ lab: "Sala de yoga", icon: "yoga" },
{ lab: "Wellness area", icon: "leaf" },
{ lab: "Cowork", icon: "desk" },
{ lab: "Jardines y paisajismo", icon: "tree" },
{ lab: "39 cocheras por rampa", icon: "car" },
{ lab: "80 bicicleteros", icon: "bike" }];

const ICONS = {
  wave: <path d="M3 14c2 0 2-2 4.5-2S10 14 12 14s2-2 4.5-2S19 14 21 14M3 19c2 0 2-2 4.5-2S10 19 12 19s2-2 4.5-2S19 19 21 19" />,
  sun: <g><circle cx="12" cy="12" r="4" /><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M5.6 18.4 7 17M17 7l1.4-1.4" /></g>,
  deck: <g><path d="M3 18h18M5 18V8h14v10M9 8V4h6v4" /></g>,
  flame: <path d="M12 3c0 4-4 5-4 9a4 4 0 0 0 8 0c0-2-1-3-1-5 0 1-1 2-2 2 0-2 1-3-1-6Z" />,
  room: <g><rect x="3" y="6" width="18" height="13" /><path d="M3 10h18M8 6V4M16 6V4" /></g>,
  gym: <path d="M4 9v6M7 6v12M17 6v12M20 9v6M7 12h10" />,
  yoga: <g><circle cx="12" cy="5" r="2" /><path d="M12 7v5l-4 7M12 12l4 7M7 13c2 0 3-1 5-1s3 1 5 1" /></g>,
  desk: <g><rect x="3" y="6" width="14" height="9" /><path d="M3 19h18M17 9h4v6h-4M7 19v-4M13 19v-4" /></g>,
  leaf: <path d="M5 19c0-7 5-13 14-13 0 9-6 14-13 14-1-1 0-2-1-1Z" />,
  tree: <g><path d="M12 21v-5M8.5 16h7M12 3l4.5 7h-9L12 3ZM9 13.5h6L12 8l-3 5.5Z" /></g>,
  car: <g><path d="M4 17v-4l2-5h12l2 5v4M4 17h16M4 17v2h3v-2M17 17v2h3v-2" /><circle cx="7.5" cy="14.5" r="1.1" fill="currentColor" stroke="none" /><circle cx="16.5" cy="14.5" r="1.1" fill="currentColor" stroke="none" /></g>,
  bike: <g><circle cx="6" cy="17" r="3" /><circle cx="18" cy="17" r="3" /><path d="M9 17h6l-3-8h-2M14 9h3" /></g>
};

function Amenities() {
  return (
    <section className="block dark" id="amenities" data-screen-label="Amenities">
      <div className="inner">
        <div className="amen__banner" style={{ backgroundImage: `url(${window.__resources.amSolarium})` }}
        role="img" aria-label="Piscina descubierta y solárium en la terraza" />

        <SectionNumber number="03" label="Amenities" tone="inverse" />

        <div className="amen__head">
          <Headline size="l" tone="inverse" style={{ marginTop: 28 }}
          lines={[{ text: "Tres niveles de amenities", register: "caps" }, { text: "para vivir más", register: "italic" }]} />
          <p className="copy-lede">
            Bienestar en planta baja, jardín y terraza: gimnasio, sala de yoga,
            wellness area, cowork y un SUM cubierto que se abre al jardín. Arriba,
            piscina descubierta, solárium, parrillas y terraza verde sobre el barrio.
          </p>
        </div>

        <div className="amen__grid">
          {AMENITIES.map((a, i) =>
          <div className="amen__cell" key={i}>
              <svg className="icon" viewBox="0 0 24 24" strokeLinecap="round" strokeLinejoin="round">{ICONS[a.icon]}</svg>
              <div className="n">{String(i + 1).padStart(2, "0")}.</div>
              <div className="lab">{a.lab}</div>
            </div>
          )}
        </div>

        <div className="amen__gallery">
          <AmenityTile src={window.__resources.amSumGarden} alt="SUM cubierto con expansión al jardín y fogonero" eyebrow="PLANTA BAJA" title="sum con expansión y fogonero" />
          <AmenityTile src={window.__resources.amGym} alt="Gimnasio, wellness area y sala de yoga" eyebrow="PISO 1" title="gym, wellness & yoga" />
          <AmenityTile src={window.__resources.amGrill} alt="Sector de parrillas en la terraza" eyebrow="Terraza" title="parrillas, piscina y solárium" />
        </div>
      </div>
    </section>);
}

/* ── 04. IN & AROUND ─────────────────────────────────────────── */

const NEIGH_POINTS = [
"Gastronomía, cafés de especialidad y diseño a pasos",
"Calles arboladas y adoquín del corazón de Hollywood",
"Bicisenda y recorridos urbanos sobre Arévalo",
"Plaza Serrano y el Distrito Audiovisual, cerca",
"Subte D · colectivos · accesos rápidos a la ciudad"];

function Ubicacion() {
  const mapSrc = "https://maps.google.com/maps?q=Guatemala+5984,+Palermo,+Buenos+Aires,+Argentina&t=&z=16&ie=UTF8&iwloc=&output=embed";
  return (
    <section className="block" id="ubicacion" data-screen-label="Ubicación">
      <SectionNumber number="04" label="Ubicación" />
      <div className="ubi__head">
        <Headline size="l" style={{ marginTop: 28 }}
        lines={[{ text: "La ciudad alrededor,", register: "caps" }, { text: "tu mundo adentro", register: "italic" }]} />
        <p className="copy-lede">
          Palermo Hollywood en su versión más cotidiana: comercios de barrio,
          gastronomía de día, cultura urbana y calles con sombra. Todo lo que pasa,
          a la vuelta; la calma, del otro lado de la puerta.
        </p>
      </div>

      <div className="ubi__body">
        <div className="ubi__map">
          <iframe title="Mapa — Guatemala 5984, Palermo Hollywood" src={mapSrc} loading="lazy"
          referrerPolicy="no-referrer-when-downgrade" allowFullScreen />
          <a className="ubi__map-link" href="https://maps.google.com/?q=Guatemala+5984,+Palermo,+Buenos+Aires,+Argentina" target="_blank" rel="noopener noreferrer">
            <span>Abrir en Google Maps</span>
            <span className="arrow">↗</span>
          </a>
        </div>

        <div className="ubi__addr">
          <div>
            <div className="lab">Dirección</div>
            <div className="street">Guatemala 5984</div>
            <div className="city">
              Esquina Arévalo · Palermo Hollywood<br />
              Ciudad de Buenos Aires, Argentina
            </div>
          </div>
          <hr className="divider" />
          <ul className="ubi__list">
            {NEIGH_POINTS.map((p, i) =>
            <li key={i}>
                <span className="n">{String(i + 1).padStart(2, "0")}.</span>
                <span>{p}</span>
              </li>
            )}
          </ul>
        </div>
      </div>

      <div className="ubi__fullbleed" style={{ backgroundImage: `url(${window.__resources.extCrossing})` }}
      role="img" aria-label="La esquina de Guatemala y Arévalo desde el cruce" />
    </section>);
}

/* ── 05. EL EQUIPO ───────────────────────────────────────────── */

function Equipo({ onCTA }) {
  return (
    <section className="block shell" id="equipo" data-screen-label="Arquitectura">
      <div className="inner">
        <SectionNumber number="05" label="Arquitectura" />
        <div className="arq" style={{ marginTop: 40 }}>
          <div className="arq__media" style={{ backgroundImage: `url(${window.__resources.extCorner})` }}
          role="img" aria-label="Fachada en la esquina de Guatemala y Arévalo" />

          <div className="arq__body">
            <CreditMark kind="architecture" assetsBase={DS_ASSETS} style={{ margin: "0 0 8px" }} />

            <p className="copy-lede">
              AISENSON proyecta en Buenos Aires desde hace noventa años. En SERENA
              Hollywood la esquina es la protagonista: horizontales continuas, madera,
              vidrio y piedra clara que bajan la escala del edificio y lo acercan al
              ritmo del barrio.
            </p>

            <ul className="arq__list">
              <li><span className="n">01.</span><span>40 m de fachada sobre dos calles, en esquina</span></li>
              <li><span className="n">02.</span><span>Madera, vidrio, piedra clara y metales oscuros</span></li>
              <li><span className="n">03.</span><span>Luz natural y ventilación cruzada en cada unidad</span></li>
              <li><span className="n">04.</span><span>Locales a la calle y hall con conserjería</span></li>
            </ul>

            <CreditMark kind="developer" assetsBase={DS_ASSETS} style={{ margin: "4px 0 8px" }} />

            <Button variant="primary" href="#contacto" onClick={onCTA} iconRight="→" style={{ alignSelf: "flex-start" }}>
              Hablar con el equipo
            </Button>
          </div>
        </div>
      </div>
    </section>);
}

/* ── WhatsApp ────────────────────────────────────────────────── */

function WhatsAppIcon({ className }) {
  return (
    <svg className={className} viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <path d="M17.5 14.4c-.3-.15-1.77-.87-2.05-.97-.27-.1-.47-.15-.67.15-.2.3-.77.97-.94 1.17-.17.2-.35.22-.65.07-.3-.15-1.25-.46-2.39-1.47-.88-.79-1.48-1.76-1.65-2.06-.17-.3-.02-.46.13-.61.13-.13.3-.35.45-.52.15-.17.2-.3.3-.5.1-.2.05-.37-.02-.52-.07-.15-.67-1.62-.92-2.22-.24-.58-.49-.5-.67-.51l-.57-.01c-.2 0-.52.07-.79.37-.27.3-1.04 1.02-1.04 2.48 0 1.46 1.06 2.88 1.21 3.08.15.2 2.1 3.21 5.08 4.5.71.3 1.26.49 1.69.62.71.22 1.36.19 1.87.12.57-.09 1.77-.72 2.02-1.42.25-.7.25-1.3.17-1.42-.07-.12-.27-.2-.57-.35Zm-5.43 7.4h-.01a9.87 9.87 0 0 1-5.03-1.38l-.36-.21-3.74.98 1-3.64-.24-.37a9.86 9.86 0 0 1-1.52-5.26C2.18 6.42 6.6 2 12.08 2c2.65 0 5.14 1.03 7.01 2.91A9.81 9.81 0 0 1 22 11.93c0 5.46-4.42 9.87-9.93 9.87Zm8.41-18.3A11.82 11.82 0 0 0 12.08 0C5.5 0 .17 5.33.16 11.88c0 2.09.55 4.13 1.6 5.94L.06 24l6.34-1.66a11.93 11.93 0 0 0 5.68 1.44h.01c6.58 0 11.91-5.33 11.92-11.88a11.82 11.82 0 0 0-3.51-8.4Z" />
    </svg>);
}

function WhatsAppFab() {
  return (
    <a className="wa-fab" href={WA_URL} target="_blank" rel="noopener noreferrer" aria-label="Contactar por WhatsApp">
      <WhatsAppIcon />
      <span>Escribinos al WhatsApp</span>
    </a>);
}

/* ── GALERÍA ─────────────────────────────────────────────────── */

const GALLERY = [
{ src: "amHall", label: "Hall de acceso con conserjería" },
{ src: "amGym", label: "Gimnasio" },
{ src: "amWellness", label: "Wellness area y sala de yoga" },
{ src: "amSum", label: "SUM cubierto" },
{ src: "amSumGarden", label: "Expansión del SUM al jardín" },
{ src: "amSolarium", label: "Piscina descubierta y solárium" },
{ src: "amGrill", label: "Sector de parrillas en terraza" },
{ src: "unit2amb", label: "Unidad de 2 ambientes" },
{ src: "unit4amb", label: "Unidad de 4 ambientes — living comedor" },
{ src: "unit4ambB", label: "Unidad de 4 ambientes — cocina integrada" },
{ src: "unitBedroom", label: "Dormitorio principal" },
{ src: "extCorner", label: "La esquina de Guatemala y Arévalo" },
{ src: "extEntrance", label: "Acceso y locales a la calle" },
{ src: "extElevation", label: "Fachada sobre Guatemala" },
{ src: "extCrossing", label: "La esquina desde el cruce" },
{ src: "extDusk", label: "Atardecer sobre Palermo Hollywood" }];

function ProyGallery() {
  const [i, setI] = useState_S(0);
  const [zoom, setZoom] = useState_S(false);
  const total = GALLERY.length;
  const prev = () => setI((v) => (v - 1 + total) % total);
  const next = () => setI((v) => (v + 1) % total);

  useEffect_S(() => {
    const onKey = (e) => {
      if (e.key === "ArrowLeft") prev();else
      if (e.key === "ArrowRight") next();else
      if (e.key === "Escape") setZoom(false);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  useEffect_S(() => {
    document.body.style.overflow = zoom ? "hidden" : "";
    document.documentElement.classList.toggle("is-lightbox", zoom);
    return () => { document.body.style.overflow = ""; document.documentElement.classList.remove("is-lightbox"); };
  }, [zoom]);

  // Horizontal swipe support for touch devices
  const touch = useRef_S(null);
  const swiped = useRef_S(false);
  const onTouchStart = (e) => {
    const t = e.touches[0];
    touch.current = { x: t.clientX, y: t.clientY };
    swiped.current = false;
  };
  const onTouchEnd = (e) => {
    if (!touch.current) return;
    const t = e.changedTouches[0];
    const dx = t.clientX - touch.current.x;
    const dy = t.clientY - touch.current.y;
    touch.current = null;
    if (Math.abs(dx) < 40 || Math.abs(dx) < Math.abs(dy)) return;
    swiped.current = true;
    dx < 0 ? next() : prev();
  };
  const openZoom = () => { if (!swiped.current) setZoom(true); };

  const item = GALLERY[i];

  return (
    <div className="proy__gallery" data-screen-label="Galería" onTouchStart={onTouchStart} onTouchEnd={onTouchEnd}>
      <div className="proy__gallery-track">
        {GALLERY.map((g, idx) =>
        <button key={g.src} type="button"
        className={"proy__gallery-slide" + (idx === i ? " is-active" : "")}
        style={{ backgroundImage: `url(${window.__resources[g.src]})` }}
        onClick={openZoom}
        aria-label={`Ampliar: ${g.label}`} aria-hidden={idx !== i} tabIndex={idx === i ? 0 : -1} />
        )}
      </div>

      <button className="proy__gallery-arrow proy__gallery-arrow--prev" onClick={prev} aria-label="Imagen anterior" type="button">
        <svg viewBox="0 0 24 24" strokeWidth="1.5" strokeLinecap="square"><path d="M15 5 L8 12 L15 19" /></svg>
      </button>
      <button className="proy__gallery-arrow proy__gallery-arrow--next" onClick={next} aria-label="Imagen siguiente" type="button">
        <svg viewBox="0 0 24 24" strokeWidth="1.5" strokeLinecap="square"><path d="M9 5 L16 12 L9 19" /></svg>
      </button>

      <div className="proy__gallery-meta">
        <span className="proy__gallery-count">{String(i + 1).padStart(2, "0")} <span className="muted">/ {String(total).padStart(2, "0")}</span></span>
        <span className="proy__gallery-label">{item.label}</span>
      </div>

      {zoom &&
      <div className="lightbox" role="dialog" aria-modal="true" aria-label={item.label} onClick={() => { if (!swiped.current) setZoom(false); }}>
          <img className="lightbox__img" src={window.__resources[item.src]} alt={item.label} onClick={(e) => e.stopPropagation()} />

          <button className="lightbox__close" type="button" onClick={() => setZoom(false)} aria-label="Cerrar">
            <svg viewBox="0 0 24 24" strokeWidth="1.5" strokeLinecap="square"><path d="M5 5 L19 19 M19 5 L5 19" /></svg>
          </button>
          <button className="lightbox__arrow lightbox__arrow--prev" type="button" aria-label="Imagen anterior"
          onClick={(e) => { e.stopPropagation(); prev(); }}>
            <svg viewBox="0 0 24 24" strokeWidth="1.5" strokeLinecap="square"><path d="M15 5 L8 12 L15 19" /></svg>
          </button>
          <button className="lightbox__arrow lightbox__arrow--next" type="button" aria-label="Imagen siguiente"
          onClick={(e) => { e.stopPropagation(); next(); }}>
            <svg viewBox="0 0 24 24" strokeWidth="1.5" strokeLinecap="square"><path d="M9 5 L16 12 L9 19" /></svg>
          </button>

          <div className="lightbox__meta" onClick={(e) => e.stopPropagation()}>
            <span className="proy__gallery-count">{String(i + 1).padStart(2, "0")} <span className="muted">/ {String(total).padStart(2, "0")}</span></span>
            <span className="proy__gallery-label">{item.label}</span>
          </div>
        </div>
      }
    </div>);
}

Object.assign(window, {
  Hero, StatsBand, Proyecto, Unidades, Amenities, Ubicacion, Equipo,
  WhatsAppFab, WhatsAppIcon, ProyGallery,
  WA_URL, WA_NUMBER, TIPO_OPTIONS, submitLead, downloadBrochure, LEAD_MAIL
});