// sections-c.jsx — cinematic break, horizontal pinned gallery, tipologías

function CinemaBreak() {
  const haloRef   = React.useRef(null);
  const rafRef    = React.useRef(null);
  const curRef    = React.useRef({ x: 50, y: 80 });
  const tgtRef    = React.useRef({ x: 50, y: 80 });
  const activeRef = React.useRef(false);

  const lerp = (a, b, t) => a + (b - a) * t;

  const tick = () => {
    const c = curRef.current, t = tgtRef.current;
    c.x = lerp(c.x, t.x, 0.04);
    c.y = lerp(c.y, t.y, 0.04);
    if (haloRef.current) {
      haloRef.current.style.background =
        `radial-gradient(circle 520px at ${c.x.toFixed(2)}% ${c.y.toFixed(2)}%, rgba(210,140,60,0.22) 0%, rgba(184,97,44,0.08) 45%, transparent 70%)`;
    }
    const dist = Math.abs(c.x - t.x) + Math.abs(c.y - t.y);
    if (dist > 0.05) rafRef.current = requestAnimationFrame(tick);
    else activeRef.current = false;
  };

  const onMove = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    tgtRef.current = {
      x: ((e.clientX - rect.left) / rect.width)  * 100,
      y: ((e.clientY - rect.top)  / rect.height) * 100,
    };
    if (!activeRef.current) {
      activeRef.current = true;
      rafRef.current = requestAnimationFrame(tick);
    }
  };

  const onLeave = () => {
    tgtRef.current = { x: 50, y: 80 };
    if (!activeRef.current) {
      activeRef.current = true;
      rafRef.current = requestAnimationFrame(tick);
    }
  };

  // Reveal de palabras al entrar en viewport
  const innerRef  = React.useRef(null);
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    cancelAnimationFrame(rafRef.current);
  }, []);

  React.useEffect(() => {
    const el = innerRef.current;
    if (!el) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setVisible(true); obs.disconnect(); }
    }, { threshold: 0.35 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  const words = "Lo que ves hoy, lo verás siempre.".split(" ");

  return (
    <section className="cinema" id="cinema-1" onMouseMove={onMove} onMouseLeave={onLeave}>
      <div className="cinema-media" data-parallax="0.12">
        <image-slot
          id="cinema-atardecer"
          shape="rect"
          fit="cover"
          src="assets/terraza-atardecer.png"
          placeholder="Atardecer sobre la Presa Madín — imagen a sangre">
        </image-slot>
      </div>
      {/* Halo de vela */}
      <div ref={haloRef} style={{
        position: "absolute", inset: 0, zIndex: 2, pointerEvents: "none",
        background: "radial-gradient(circle 520px at 50% 80%, rgba(210,140,60,0.18) 0%, transparent 70%)",
        mixBlendMode: "screen",
      }} />
      <div className="cinema-inner" ref={innerRef}>
        <span className="cinema-eyebrow" style={{
          display: "block",
          opacity: visible ? 1 : 0,
          transform: visible ? "none" : "translateY(10px)",
          transition: "opacity 1.2s ease 0.1s, transform 1.2s ease 0.1s",
        }}>El horizonte poniente</span>
        <p className="cinema-quote" style={{ color: "#F2EDE4" }}>
          {words.map((word, i) => (
            <span
              key={i}
              style={{
                display: "inline-block",
                marginRight: "0.28em",
                opacity: visible ? 1 : 0,
                filter: visible ? "blur(0px)" : "blur(8px)",
                transform: visible ? "translateY(0)" : "translateY(16px)",
                transition: `opacity 1s cubic-bezier(0.22,1,0.36,1) ${(i * 0.12) + 0.4}s,
                             filter  1.2s cubic-bezier(0.22,1,0.36,1) ${(i * 0.12) + 0.4}s,
                             transform 1s cubic-bezier(0.22,1,0.36,1) ${(i * 0.12) + 0.4}s`,
              }}
            >{word}</span>
          ))}
        </p>
      </div>
    </section>);

}

const GALLERY_PANELS = [
{ id: "g-lobby", w: "", tall: false, n: "01", cap: "Estancia · textiles naturales", src: "assets/render-p22-2.png" },
{ id: "g-terraza", w: "hpanel-tall", tall: true, n: "02", cap: "Rincón de lectura", src: "assets/render-p4-3.png" },
{ id: "g-estancia", w: "hpanel-wide", tall: false, n: "03", cap: "Estancia & comedor", src: "assets/render-p4-2.png" },
{ id: "g-jardin", w: "", tall: false, n: "04", cap: "Terraza · vista poniente", src: "assets/render-terraza-lago.jpg" },
{ id: "g-padel", w: "hpanel-tall", tall: true, n: "05", cap: "Plaster & travertino", src: "assets/render-comedor.jpg" },
{ id: "g-noche", w: "hpanel-wide", tall: false, n: "06", cap: "Terraza al atardecer", src: "assets/galeria-terraza-atardecer.png" }];


function HGallery() {
  const secRef = React.useRef(null);
  const [vis, setVis] = React.useState(false);
  React.useEffect(() => {
    const el = secRef.current;
    if (!el) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setVis(true); obs.disconnect(); }
    }, { threshold: 0.08 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  // Parallax cursor en imágenes
  React.useEffect(() => {
    const lerp = (a, b, t) => a + (b - a) * t;
    const panels = Array.from(document.querySelectorAll('#galeria .hpanel:not(.hpanel-intro)'));
    const cleanups = [];

    panels.forEach(panel => {
      const img = panel.querySelector('image-slot');
      if (!img) return;
      let cur = { x: 0, y: 0 }, tgt = { x: 0, y: 0 }, rafId = null;

      const tick = () => {
        cur.x = lerp(cur.x, tgt.x, 0.07);
        cur.y = lerp(cur.y, tgt.y, 0.07);
        img.style.transform = `translate(${cur.x.toFixed(2)}px, ${cur.y.toFixed(2)}px)`;
        rafId = Math.abs(cur.x - tgt.x) + Math.abs(cur.y - tgt.y) > 0.01
          ? requestAnimationFrame(tick) : null;
      };

      const onMove = e => {
        const r = panel.getBoundingClientRect();
        tgt.x = ((e.clientX - r.left) / r.width  - 0.5) * 20;
        tgt.y = ((e.clientY - r.top)  / r.height - 0.5) * 14;
        if (!rafId) rafId = requestAnimationFrame(tick);
      };
      const onLeave = () => {
        tgt.x = 0; tgt.y = 0;
        if (!rafId) rafId = requestAnimationFrame(tick);
      };

      panel.addEventListener('mousemove', onMove);
      panel.addEventListener('mouseleave', onLeave);
      cleanups.push(() => {
        panel.removeEventListener('mousemove', onMove);
        panel.removeEventListener('mouseleave', onLeave);
        if (rafId) cancelAnimationFrame(rafId);
      });
    });
    return () => cleanups.forEach(fn => fn());
  }, []);

  const wStyle = (i) => {
    const d = (i * 0.1 + 0.2).toFixed(2);
    return {
      display: "inline-block", marginRight: "0.2em",
      opacity:   vis ? 1 : 0,
      filter:    vis ? "blur(0)" : "blur(7px)",
      transform: vis ? "translateY(0)" : "translateY(20px)",
      transition: [
        `opacity   1.1s cubic-bezier(0.22,1,0.36,1) ${d}s`,
        `filter    1.3s cubic-bezier(0.22,1,0.36,1) ${d}s`,
        `transform 1.1s cubic-bezier(0.22,1,0.36,1) ${d}s`,
      ].join(", "),
    };
  };

  const wStyleKey = (i) => {
    const d = (i * 0.1 + 0.2).toFixed(2);
    return {
      display: "inline-block", marginRight: "0.2em",
      opacity:      vis ? 1 : 0,
      filter:       vis ? "blur(0)" : "blur(7px)",
      transform:    vis ? "translateY(0)" : "translateY(20px)",
      letterSpacing: vis ? "-0.01em" : "0.14em",
      transition: [
        `opacity       1.1s cubic-bezier(0.22,1,0.36,1) ${d}s`,
        `filter        1.3s cubic-bezier(0.22,1,0.36,1) ${d}s`,
        `transform     1.1s cubic-bezier(0.22,1,0.36,1) ${d}s`,
        `letter-spacing 1.5s cubic-bezier(0.22,1,0.36,1) ${d}s`,
      ].join(", "),
    };
  };

  const fStyle = (d) => ({
    opacity:   vis ? 1 : 0,
    transform: vis ? "none" : "translateY(12px)",
    transition: `opacity 1s ease ${d}s, transform 1s ease ${d}s`,
  });

  return (
    <section className="hgallery" data-hscroll id="galeria" ref={secRef}>
      <div className="hgallery-sticky">
        <div className="hgallery-track">
          <div className="hpanel hpanel-intro">
            <span className="eyebrow terracota" style={fStyle(0.1)}>Galería</span>
            <h2 className="hgallery-title">
              <span style={wStyle(0)}>Recorre</span>
              <span style={wStyle(1)}>el</span>
              <span style={wStyleKey(2)}>
                <span className="mf-key" style={{ animationDelay: "-0.8s" }}>proyecto.</span>
              </span>
            </h2>
            <p className="hgallery-intro-text" style={fStyle(0.55)}>
              Cada espacio fue diseñado en función de la vista. Desliza para recorrer los
              ambientes — del lobby panorámico a la terraza que mira al agua.
            </p>
          </div>

          {GALLERY_PANELS.map((p) =>
          <div className={"hpanel " + p.w} key={p.id}>
              <div className="img-reveal">
                <image-slot
                id={p.id}
                shape="rect"
                fit="cover"
                src={p.src}
                placeholder={p.cap}>
              </image-slot>
              </div>
              <div className="hpanel-caption">
                <span>{p.n} · {p.cap}</span>
                <span>LAVISTA</span>
              </div>
            </div>
          )}
        </div>

        <div className="hgallery-hint">
          <span>Desliza</span>
          <svg width="40" height="6" viewBox="0 0 40 6" fill="none" stroke="currentColor">
            <line x1="0" y1="3" x2="38" y2="3" strokeWidth="1" />
            <path d="M33 0l5 3-5 3" strokeWidth="1" />
          </svg>
        </div>
        <div className="hgallery-progress"><span></span></div>
      </div>
    </section>);

}

const TIPO_SPACES = [
{ name: "Master bedroom", sub: "Con vestidor y baño completo", area: "19.36" },
{ name: "Estancia", sub: "Doble altura visual hacia terraza", area: "24.88" },
{ name: "Terraza con asador", sub: "Orientada al poniente", area: "27.44" },
{ name: "Recámaras 2 y 3", sub: "Con clóset y baño compartido", area: "—" },
{ name: "Cocina y comedor", sub: "Integrados, isla central", area: "—" }];


function Tipologias() {
  const [is3D, setIs3D] = React.useState(true);
  const imgRef = React.useRef(null);
  const rafRef = React.useRef(null);

  // Parallax suave en la imagen del plano
  const onMove = (e) => {
    if (!imgRef.current) return;
    const el = imgRef.current;
    const rect = el.closest(".tipo-plan-wrap").getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width - 0.5);
    const y = ((e.clientY - rect.top)  / rect.height - 0.5);
    if (rafRef.current) cancelAnimationFrame(rafRef.current);
    rafRef.current = requestAnimationFrame(() => {
      el.style.transform = `translate(${(x * 14).toFixed(2)}px, ${(y * 8).toFixed(2)}px) scale(1.04)`;
    });
  };
  const onLeave = () => {
    if (imgRef.current) imgRef.current.style.transform = "translate(0,0) scale(1)";
  };

  return (
    <section className={"tipo" + (is3D ? " tipo-dark" : "")} id="tipologias">
      {/* Header siempre en container */}
      <div className="container">
        <div className="tipo-header">
          <div>
            <span className={"eyebrow" + (is3D ? " eyebrow-light" : " terracota")}>Tipologías</span>
            <h2 className="tipo-title" style={{ marginTop: "1rem", color: is3D ? "var(--paper)" : undefined }}>
              Un solo tipo, <em>resuelto</em> al detalle.
            </h2>
          </div>
          <p style={{ color: is3D ? "rgba(242,237,228,0.65)" : "var(--ink-2)", fontSize: "1.02rem", maxWidth: "44ch" }}>
            Departamento tipo de tres recámaras más recámara de servicio. No se trata de elegir entre
            versiones recortadas, sino de una planta pensada para vivirse completa.
          </p>
        </div>

        {/* Toolbar */}
        <div className="tipo-plan-toolbar" style={{ marginBottom: "2.5rem" }}>
          <span className="tipo-plan-tag" style={{ color: is3D ? "rgba(242,237,228,0.45)" : undefined }}>
            Planta departamento tipo · 205 m² · esc. 1:75
          </span>
          <div className={"tipo-view-toggle" + (is3D ? " tipo-view-toggle-dark" : "")} role="group">
            <button className={!is3D ? "active" : ""} onClick={() => setIs3D(false)} type="button">2D</button>
            <button className={is3D  ? "active" : ""} onClick={() => setIs3D(true)}  type="button">3D</button>
          </div>
        </div>
      </div>

      {/* Plano — full bleed */}
      <div className="tipo-plan-wrap" onMouseMove={onMove} onMouseLeave={onLeave}>
        <img
          ref={imgRef}
          className={"tipo-plan-img" + (is3D ? " is-3d-render" : " is-2d-plan")}
          src={is3D ? "assets/planta-3d.jpg" : "assets/planta-tipo-clean.png"}
          alt="Planta departamento tipo LAVISTA"
        />
      </div>

      {/* Espacios y totales */}
      <div className="container">
        <div className="tipo-grid" style={{ paddingTop: "4rem" }}>
          <div>
            <div className="tipo-spaces">
              {TIPO_SPACES.map((s, i) =>
              <div className="tipo-space" key={i} style={{ color: is3D ? "var(--paper)" : undefined, borderColor: is3D ? "rgba(242,237,228,0.12)" : undefined }}>
                  <div>
                    <span className="tipo-space-name">{s.name}</span>
                    <span className="tipo-space-sub" style={{ color: is3D ? "rgba(242,237,228,0.5)" : undefined }}>{s.sub}</span>
                  </div>
                  <span className="tipo-space-area">{s.area}{s.area !== "—" && <span style={{ fontSize: "0.7em", marginLeft: 3 }}>m²</span>}</span>
                </div>
              )}
            </div>
          </div>
          <div>
            <div className="tipo-total" style={{ color: is3D ? "var(--paper)" : undefined }}>
              <span className="tipo-total-label" style={{ color: is3D ? "rgba(242,237,228,0.5)" : undefined }}>Superficie total construida</span>
              <span className="tipo-total-value bignum" data-count="205" data-suffix=" m²">205 m²</span>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

Object.assign(window, { CinemaBreak, HGallery, Tipologias });
