const { useState, useEffect, useRef, useMemo, useLayoutEffect } = React;

/* =====================================================================
   HOOKS
   ===================================================================== */
const useScrollProgress = (ref) => {
  const [progress, setProgress] = useState(0);
  useEffect(() => {
    if (!ref.current) return;
    let raf = 0;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const el = ref.current;
        if (!el) return;
        const rect = el.getBoundingClientRect();
        const vh = window.innerHeight;
        // 0 when top hits top of viewport, 1 when bottom hits bottom
        const total = rect.height - vh;
        const p = total > 0 ? Math.min(1, Math.max(0, -rect.top / total)) : 0;
        setProgress(p);
      });
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
      cancelAnimationFrame(raf);
    };
  }, [ref]);
  return progress;
};

const useInView = (options = { threshold: 0.15 }) => {
  const ref = useRef(null);
  const [inView, setInView] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) setInView(true);
    }, options);
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return [ref, inView];
};

/* =====================================================================
   NAV
   ===================================================================== */
const Nav = () => {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 60);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  const items = ['Estudio', 'Servicios', 'Proyectos', 'Proceso', 'Contacto'];
  return (
    <nav className={`nav ${scrolled ? 'nav--scrolled' : ''}`}>
      <div className="nav__inner">
        <a href="#top" className="nav__brand">
          <span className="nav__mark" aria-hidden="true">
            <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
              <path d="M2 19 L11 3 L20 19 M6 14 L16 14" stroke="currentColor" strokeWidth="1.2" strokeLinecap="square" strokeLinejoin="miter" />
            </svg>
          </span>
          <span className="nav__wordmark">
            <span className="nav__name">CASTELLANO</span>
            <span className="nav__sub">Arquitectura · Construcción</span>
          </span>
        </a>
        <ul className="nav__links">
          {items.map((it, i) => (
            <li key={it}>
              <a href={`#${it.toLowerCase()}`}>
                <span className="nav__num">0{i + 1}</span>
                <span>{it}</span>
              </a>
            </li>
          ))}
        </ul>
        <a className="nav__cta" href="#contacto">
          Agendar reunión
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M3 11 L11 3 M5 3 H11 V9" stroke="currentColor" strokeWidth="1.2" /></svg>
        </a>
      </div>
    </nav>
  );
};

/* =====================================================================
   HERO — Sticky image-sequence scroll
   ===================================================================== */
const HERO_IMAGES = [
  {
    src: 'assets/01-terreno.png',
    label: 'TERRENO',
    sub: 'I · El sitio en su estado original',
    lede: <>Cada obra comienza por <em>leer el lugar.</em><br />La luz, el viento, la memoria del sitio antes de la primera línea.</>,
  },
  {
    src: 'assets/02-estructura.png',
    label: 'ESTRUCTURA',
    sub: 'II · Cimiento, columnas, ritmo',
    lede: <>Cimientos calculados, columnas a plomo.<br />La <em>estructura es la primera forma</em> del proyecto.</>,
  },
  {
    src: 'assets/03-construccion.png',
    label: 'CONSTRUCCIÓN',
    sub: 'III · Volumen, materia, envolvente',
    lede: <>Materia que se vuelve espacio.<br />Cantera, concreto, madera, oficio — <em>todo bajo una misma firma.</em></>,
  },
  {
    src: 'assets/04-casa.png',
    label: 'ENTREGA',
    sub: 'IV · El proyecto realizado',
    lede: <>Estudio de arquitectura y construcción en Lagos de Moreno.<br />Proyectos residenciales y empresariales <em>llave en mano.</em></>,
  },
];

const Hero = () => {
  const sectionRef = useRef(null);
  const progress = useScrollProgress(sectionRef);

  // four images mapped to four stages along progress [0..1]
  // we'll have a small "intro" buffer (0 → 0.08) where image 1 holds in place
  const stages = HERO_IMAGES.length;
  const tBuffer = 0.06;
  const tEnd = 0.94;
  const t = Math.min(1, Math.max(0, (progress - tBuffer) / (tEnd - tBuffer)));
  const stagePos = t * (stages - 1); // 0..3
  const activeIdx = Math.min(stages - 1, Math.floor(stagePos));
  const subT = stagePos - activeIdx; // 0..1 within stage

  // subtle cinematic scale: zoom from 1.08 down to 1.0 as user scrolls
  const heroScale = 1.08 - progress * 0.08;
  const heroBlur = Math.sin(subT * Math.PI) * 1.6; // peak blur mid-transition

  // overlay darkness ramps slightly to suggest evening
  const overlayOpacity = 0.18 + progress * 0.18;

  return (
    <section className="hero" ref={sectionRef} id="top" data-screen-label="01 Hero">
      <div className="hero__sticky">
        <div className="hero__images" style={{ transform: `scale(${heroScale})`, filter: `blur(${heroBlur}px)` }}>
          {HERO_IMAGES.map((img, i) => {
            // each image fades in/out around its stage index
            let op = 0;
            const d = stagePos - i;
            if (d <= -1) op = 0;
            else if (d >= 1) op = 0;
            else op = 1 - Math.abs(d);
            // soften with easing
            op = Math.pow(op, 0.7);
            return (
              <img
                key={img.src}
                src={img.src}
                alt={img.label}
                className="hero__img"
                style={{ opacity: op }}
                draggable={false}
              />
            );
          })}
          <div className="hero__vignette" style={{ opacity: overlayOpacity }} />
          <div className="hero__grain" />
        </div>

        {/* fixed editorial UI */}
        <div className="hero__ui">
          <div className="hero__top">
            <div className="hero__eyebrow">
              <span className="dot" />
              <span>LAGOS DE MORENO · JALISCO · MX</span>
            </div>
            <div className="hero__eyebrow hero__eyebrow--right">
              <span>EST. 2009</span>
              <span className="hero__bar" />
              <span>EDICIÓN MMXXVI</span>
            </div>
          </div>

          <div className="hero__center">
            <h1 className="hero__title">
              <span className="hero__line">
                <span style={{ transitionDelay: '0.05s' }}>Del</span>{' '}
                <em style={{ transitionDelay: '0.15s' }}>terreno</em>
              </span>
              <span className="hero__line">
                <span style={{ transitionDelay: '0.25s' }}>a la</span>{' '}
                <em style={{ transitionDelay: '0.35s' }}>obra terminada.</em>
              </span>
            </h1>
            <div className="hero__lede-stack">
              {HERO_IMAGES.map((img, i) => (
                <p
                  key={i}
                  className="hero__lede"
                  style={{ opacity: i === activeIdx ? 1 : 0 }}
                  aria-hidden={i !== activeIdx}
                >{img.lede}</p>
              ))}
            </div>
          </div>

          <div className="hero__bottom">
            <div className="hero__stage">
              <div className="hero__stage-meta">
                <span className="hero__stage-num">0{activeIdx + 1} / 0{stages}</span>
                <span className="hero__stage-bar"><span style={{ width: `${(stagePos / (stages - 1)) * 100}%` }} /></span>
              </div>
              <div className="hero__stage-label">
                <div className="hero__stage-title">{HERO_IMAGES[activeIdx].label}</div>
                <div className="hero__stage-sub">{HERO_IMAGES[activeIdx].sub}</div>
              </div>
            </div>
            <div className="hero__scroll">
              <span>Desplaza para construir</span>
              <span className="hero__scroll-line"><span /></span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

/* =====================================================================
   CHAPTER HEADER
   ===================================================================== */
const Chapter = ({ num, kicker, title, lede }) => {
  const [ref, inView] = useInView();
  return (
    <header className={`chapter ${inView ? 'is-in' : ''}`} ref={ref}>
      <div className="chapter__meta">
        <span className="chapter__num">{num}</span>
        <span className="chapter__line" />
        <span className="chapter__kicker">{kicker}</span>
      </div>
      <h2 className="chapter__title">{title}</h2>
      {lede && <p className="chapter__lede">{lede}</p>}
    </header>
  );
};

/* =====================================================================
   ABOUT / QUIÉNES SOMOS
   ===================================================================== */
const About = () => {
  const [ref, inView] = useInView();
  return (
    <section className="about" id="estudio" data-screen-label="02 Estudio">
      <Chapter
        num="CAP. 01"
        kicker="EL ESTUDIO"
        title={<>Una práctica entre la <em>cantera</em> y el <em>concreto</em>.</>}
      />
      <div className={`about__grid ${inView ? 'is-in' : ''}`} ref={ref}>
        <div className="about__image">
          <div className="about__image-frame">
            <img src="assets/04-casa.png" alt="Proyecto Casa El Mirador" />
            <div className="about__image-caption">
              <span>PROYECTO 047</span>
              <span>Casa El Mirador · 2024</span>
            </div>
          </div>
        </div>
        <div className="about__copy">
          <p className="about__lead">
            Diseñamos y construimos espacios que pertenecen a su lugar. Trabajamos desde Lagos de Moreno con un equipo de arquitectos, ingenieros y maestros de obra que entienden la cantera, la madera y el oficio tanto como el detalle digital.
          </p>
          <p className="about__body">
            Cada proyecto comienza con una conversación larga y termina con una llave en mano. Entre ambos extremos, nuestro estudio opera como un único organismo: una sola voz, un solo control, una sola firma.
          </p>
          <div className="about__signature">
            <div>
              <div className="about__sig-name">Ar. Mariana Castellano</div>
              <div className="about__sig-role">Directora · Arquitecta Senior</div>
            </div>
            <svg width="120" height="40" viewBox="0 0 120 40" className="about__sig-mark" fill="none">
              <path d="M4 30 C 20 8, 36 38, 52 18 S 88 6, 104 28" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" />
              <path d="M100 32 L116 22" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" />
            </svg>
          </div>
          <div className="about__credentials">
            <div><strong>17</strong><span>años de práctica</span></div>
            <div><strong>04</strong><span>premios CAMSAM</span></div>
            <div><strong>02</strong><span>oficinas (Lagos · GDL)</span></div>
          </div>
        </div>
      </div>
    </section>
  );
};

/* =====================================================================
   SERVICES
   ===================================================================== */
const SERVICES = [
  { n: '01', t: 'Arquitectura Residencial', d: 'Casas habitación únicas, diseñadas a partir del sitio, la luz y la forma de vivir del cliente.', tag: 'DISEÑO' },
  { n: '02', t: 'Construcción', d: 'Obra civil completa con cuadrillas propias, control de calidad por etapas y supervisión diaria.', tag: 'OBRA' },
  { n: '03', t: 'Remodelaciones', d: 'Intervenciones quirúrgicas sobre fincas patrimoniales y vivienda contemporánea.', tag: 'INTERVENCIÓN' },
  { n: '04', t: 'Interiorismo', d: 'Mobiliario a medida, materiales nobles, paletas trabajadas con artesanos locales.', tag: 'INTERIOR' },
  { n: '05', t: 'Supervisión de Obra', d: 'Acompañamos al cliente que ya tiene proyecto y necesita ejecución impecable.', tag: 'GESTIÓN' },
  { n: '06', t: 'Proyectos Empresariales', d: 'Oficinas, hotelería boutique, retail y espacios corporativos llave en mano.', tag: 'CORPORATIVO' },
];

const ServiceCard = ({ s, i }) => {
  const [ref, inView] = useInView({ threshold: 0.2 });
  return (
    <article
      ref={ref}
      className={`service ${inView ? 'is-in' : ''}`}
      style={{ transitionDelay: `${i * 60}ms` }}
    >
      <div className="service__head">
        <span className="service__num">{s.n}</span>
        <span className="service__tag">{s.tag}</span>
      </div>
      <h3 className="service__title">{s.t}</h3>
      <p className="service__desc">{s.d}</p>
      <div className="service__more">
        <span>Conocer alcance</span>
        <svg width="18" height="10" viewBox="0 0 18 10" fill="none">
          <path d="M1 5 H16 M12 1 L16 5 L12 9" stroke="currentColor" strokeWidth="1.2" />
        </svg>
      </div>
      <div className="service__glow" />
    </article>
  );
};

const Services = () => (
  <section className="services" id="servicios" data-screen-label="03 Servicios">
    <Chapter
      num="CAP. 02"
      kicker="QUÉ HACEMOS"
      title={<>Seis disciplinas. <em>Un solo estudio.</em></>}
      lede="Operamos como una práctica integral. Desde el primer croquis hasta la entrega de llaves, el cliente conserva un único interlocutor."
    />
    <div className="services__grid">
      {SERVICES.map((s, i) => <ServiceCard key={s.n} s={s} i={i} />)}
    </div>
  </section>
);

/* =====================================================================
   BLUEPRINT MODE — Plano → Wireframe → Render → Foto
   ===================================================================== */
const BLUEPRINT_STEPS = [
  { id: 'plano', label: 'Plano técnico' },
  { id: 'wire', label: 'Wireframe 3D' },
  { id: 'render', label: 'Render' },
  { id: 'foto', label: 'Fotografía final' },
];

const BlueprintLayer = ({ step, active }) => {
  // we draw original SVG diagrams for the first three stages, then the real photo for stage 4
  const visible = step === active ? 1 : 0;
  if (step === 'foto') {
    return (
      <img
        src="assets/04-casa.png"
        alt="Foto final del proyecto"
        className="bp__layer bp__layer--photo"
        style={{ opacity: visible }}
        draggable={false}
      />
    );
  }
  if (step === 'plano') {
    return (
      <svg className="bp__layer" viewBox="0 0 1000 600" style={{ opacity: visible }}>
        <defs>
          <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
            <path d="M40 0 H0 V40" fill="none" stroke="rgba(198,169,114,0.18)" strokeWidth="0.5" />
          </pattern>
          <pattern id="gridLg" width="200" height="200" patternUnits="userSpaceOnUse">
            <path d="M200 0 H0 V200" fill="none" stroke="rgba(198,169,114,0.32)" strokeWidth="0.7" />
          </pattern>
        </defs>
        <rect width="1000" height="600" fill="url(#grid)" />
        <rect width="1000" height="600" fill="url(#gridLg)" />
        {/* floor plan */}
        <g stroke="#C6A972" strokeWidth="1.6" fill="none">
          <rect x="180" y="160" width="640" height="300" />
          <line x1="180" y1="280" x2="820" y2="280" />
          <line x1="460" y1="160" x2="460" y2="460" />
          <line x1="640" y1="280" x2="640" y2="460" />
          <line x1="180" y1="380" x2="460" y2="380" />
          {/* door arcs */}
          <path d="M 360 280 A 40 40 0 0 1 400 320" />
          <path d="M 600 380 A 30 30 0 0 1 630 410" />
          {/* window marks */}
          <line x1="220" y1="160" x2="280" y2="160" strokeWidth="3" />
          <line x1="540" y1="160" x2="600" y2="160" strokeWidth="3" />
          <line x1="700" y1="460" x2="780" y2="460" strokeWidth="3" />
          {/* dimensions */}
          <g stroke="rgba(198,169,114,0.55)" strokeWidth="0.8">
            <line x1="180" y1="120" x2="820" y2="120" />
            <line x1="180" y1="112" x2="180" y2="128" />
            <line x1="820" y1="112" x2="820" y2="128" />
            <line x1="860" y1="160" x2="860" y2="460" />
            <line x1="852" y1="160" x2="868" y2="160" />
            <line x1="852" y1="460" x2="868" y2="460" />
          </g>
          <text x="500" y="108" fill="#C6A972" fontSize="11" fontFamily="JetBrains Mono, monospace" textAnchor="middle">18.40 m</text>
          <text x="880" y="320" fill="#C6A972" fontSize="11" fontFamily="JetBrains Mono, monospace">8.60 m</text>
          {/* rooms */}
          <text x="320" y="225" fill="rgba(245,243,239,0.6)" fontSize="10" fontFamily="JetBrains Mono, monospace">SALA · COMEDOR</text>
          <text x="540" y="225" fill="rgba(245,243,239,0.6)" fontSize="10" fontFamily="JetBrains Mono, monospace">COCINA</text>
          <text x="720" y="225" fill="rgba(245,243,239,0.6)" fontSize="10" fontFamily="JetBrains Mono, monospace">RECÁMARA 1</text>
          <text x="320" y="425" fill="rgba(245,243,239,0.6)" fontSize="10" fontFamily="JetBrains Mono, monospace">TERRAZA</text>
          <text x="540" y="425" fill="rgba(245,243,239,0.6)" fontSize="10" fontFamily="JetBrains Mono, monospace">RECÁMARA 2</text>
          <text x="720" y="425" fill="rgba(245,243,239,0.6)" fontSize="10" fontFamily="JetBrains Mono, monospace">RECÁMARA 3</text>
        </g>
        <g fontFamily="JetBrains Mono, monospace" fontSize="10" fill="rgba(198,169,114,0.7)">
          <text x="40" y="40">PLANO ARQUITECTÓNICO · NIVEL 01</text>
          <text x="40" y="56">CASA EL MIRADOR — 047</text>
          <text x="960" y="40" textAnchor="end">ESC 1:75</text>
          <text x="960" y="56" textAnchor="end">REV. C</text>
        </g>
      </svg>
    );
  }
  if (step === 'wire') {
    return (
      <svg className="bp__layer" viewBox="0 0 1000 600" style={{ opacity: visible }}>
        {/* isometric / axon wireframe house */}
        <g stroke="#C6A972" strokeWidth="1.2" fill="none" strokeLinejoin="miter">
          {/* ground plane */}
          <path d="M 120 460 L 520 540 L 920 460 L 520 380 Z" stroke="rgba(198,169,114,0.4)" />
          {/* main volume */}
          <path d="M 240 420 L 520 480 L 800 420 L 520 360 Z" />
          <path d="M 240 420 L 240 280 L 520 220 L 520 360" />
          <path d="M 520 220 L 800 280 L 800 420" />
          <path d="M 520 360 L 520 480" />
          {/* roof slab projection */}
          <path d="M 200 270 L 520 200 L 840 270 L 840 290 L 520 220 L 200 290 Z" stroke="rgba(198,169,114,0.7)" />
          {/* secondary volume */}
          <path d="M 540 380 L 700 410 L 700 470 L 540 440 Z" />
          <path d="M 540 380 L 540 320 L 700 350 L 700 410" />
          <path d="M 540 320 L 700 350" />
          {/* windows */}
          <g stroke="rgba(198,169,114,0.55)">
            <path d="M 280 380 L 380 400 L 380 340 L 280 320 Z" />
            <path d="M 600 280 L 720 300 L 720 250 L 600 235 Z" />
          </g>
          {/* hidden dashed edges */}
          <g strokeDasharray="3 4" stroke="rgba(198,169,114,0.35)">
            <path d="M 240 280 L 800 280" />
            <path d="M 240 420 L 800 420" />
          </g>
        </g>
        <g fontFamily="JetBrains Mono, monospace" fontSize="10" fill="rgba(198,169,114,0.7)">
          <text x="40" y="40">AXONOMETRÍA · VOLUMETRÍA</text>
          <text x="40" y="56">CASA EL MIRADOR — 047</text>
          <text x="960" y="40" textAnchor="end">VIEW NW</text>
          <text x="960" y="56" textAnchor="end">REV. C</text>
        </g>
      </svg>
    );
  }
  if (step === 'render') {
    // photo with strong wash + scan to feel like a render
    return (
      <div className="bp__layer bp__render" style={{ opacity: visible }}>
        <img src="assets/04-casa.png" alt="Render" draggable={false} />
        <div className="bp__render-wash" />
        <div className="bp__render-scan" />
      </div>
    );
  }
  return null;
};

const Blueprint = () => {
  const [active, setActive] = useState('plano');
  const idx = BLUEPRINT_STEPS.findIndex(s => s.id === active);
  // auto-advance
  useEffect(() => {
    const id = setInterval(() => {
      setActive(prev => {
        const i = BLUEPRINT_STEPS.findIndex(s => s.id === prev);
        return BLUEPRINT_STEPS[(i + 1) % BLUEPRINT_STEPS.length].id;
      });
    }, 4200);
    return () => clearInterval(id);
  }, []);
  return (
    <section className="bp" id="blueprint" data-screen-label="04 Blueprint">
      <Chapter
        num="CAP. 03"
        kicker="BLUEPRINT MODE"
        title={<>Del <em>plano</em> al <em>habitar</em>.</>}
        lede="Cuatro lecturas del mismo proyecto. Cada capa es un momento del método."
      />
      <div className="bp__stage">
        <div className="bp__frame">
          {BLUEPRINT_STEPS.map(s => (
            <BlueprintLayer key={s.id} step={s.id} active={active} />
          ))}
          <div className="bp__crosshair">
            <span className="bp__corner bp__corner--tl" />
            <span className="bp__corner bp__corner--tr" />
            <span className="bp__corner bp__corner--bl" />
            <span className="bp__corner bp__corner--br" />
            <div className="bp__readout">
              <span>FASE {String(idx + 1).padStart(2, '0')}</span>
              <span>{BLUEPRINT_STEPS[idx].label.toUpperCase()}</span>
            </div>
          </div>
        </div>
        <div className="bp__tabs">
          {BLUEPRINT_STEPS.map((s, i) => (
            <button
              key={s.id}
              onClick={() => setActive(s.id)}
              className={`bp__tab ${active === s.id ? 'is-active' : ''}`}
            >
              <span className="bp__tab-num">0{i + 1}</span>
              <span className="bp__tab-label">{s.label}</span>
              <span className="bp__tab-bar"><span style={{ width: active === s.id ? '100%' : '0%' }} /></span>
            </button>
          ))}
        </div>
      </div>
    </section>
  );
};

/* =====================================================================
   PROJECTS — Masonry editorial gallery
   ===================================================================== */
const PROJECTS = [
  { id: 'p1', title: 'Casa El Mirador', tag: 'Residencial', year: '2024', loc: 'Lagos de Moreno', img: 'assets/04-casa.png', size: 'tall' },
  { id: 'p2', title: 'Hacienda San Felipe', tag: 'Patrimonio · Remodelación', year: '2023', loc: 'San Juan de los Lagos', img: 'assets/03-construccion.png', size: 'wide' },
  { id: 'p3', title: 'Oficinas Cantera', tag: 'Empresarial', year: '2023', loc: 'Guadalajara', img: 'assets/02-estructura.png', size: 'sq' },
  { id: 'p4', title: 'Terreno Cerro Alto', tag: 'Masterplan', year: '2025', loc: 'Encarnación de Díaz', img: 'assets/01-terreno.png', size: 'sq' },
  { id: 'p5', title: 'Casa Pórtico', tag: 'Residencial', year: '2022', loc: 'Lagos de Moreno', img: 'assets/04-casa.png', size: 'wide' },
  { id: 'p6', title: 'Hotel Boutique La Ribera', tag: 'Hotelería', year: '2025', loc: 'Tequila', img: 'assets/03-construccion.png', size: 'tall' },
];

const ProjectCard = ({ p, i }) => {
  const [ref, inView] = useInView({ threshold: 0.1 });
  return (
    <a
      ref={ref}
      className={`project project--${p.size} ${inView ? 'is-in' : ''}`}
      style={{ transitionDelay: `${(i % 3) * 80}ms` }}
      href={`#${p.id}`}
    >
      <div className="project__media">
        <img src={p.img} alt={p.title} draggable={false} />
      </div>
      <div className="project__meta">
        <div className="project__tag">{p.tag} · {p.year}</div>
        <h3 className="project__title">{p.title}</h3>
        <div className="project__loc">{p.loc}</div>
      </div>
      <div className="project__view">
        <span>Ver obra</span>
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M3 11 L11 3 M5 3 H11 V9" stroke="currentColor" strokeWidth="1.2" /></svg>
      </div>
    </a>
  );
};

const Projects = () => (
  <section className="projects" id="proyectos" data-screen-label="05 Proyectos">
    <Chapter
      num="CAP. 04"
      kicker="OBRA SELECCIONADA"
      title={<>Una década de <em>encargos.</em></>}
      lede="Una selección de proyectos residenciales, patrimoniales y empresariales entre Jalisco y el Bajío."
    />
    <div className="projects__grid">
      {PROJECTS.map((p, i) => <ProjectCard key={p.id} p={p} i={i} />)}
    </div>
    <div className="projects__foot">
      <a href="#archive" className="link-arrow">
        Ver archivo completo
        <svg width="22" height="10" viewBox="0 0 22 10" fill="none"><path d="M1 5 H20 M16 1 L20 5 L16 9" stroke="currentColor" strokeWidth="1.2" /></svg>
      </a>
    </div>
  </section>
);

/* =====================================================================
   PROCESS TIMELINE
   ===================================================================== */
const PROCESS = [
  { n: '01', t: 'Idea', d: 'Conversación, sitio, intuición. El proyecto se imagina antes de existir.' },
  { n: '02', t: 'Diseño', d: 'Anteproyecto, materiales, luz. Tres revisiones a fondo con el cliente.' },
  { n: '03', t: 'Planeación', d: 'Ingenierías, costos cerrados, calendario de obra, permisos.' },
  { n: '04', t: 'Construcción', d: 'Cuadrillas propias. Reporte semanal. Visitas a obra agendadas.' },
  { n: '05', t: 'Entrega', d: 'Llave en mano, mobiliario instalado, garantía estructural y seguimiento.' },
];

const Process = () => {
  const ref = useRef(null);
  const progress = useScrollProgress(ref);
  const filled = Math.min(1, Math.max(0, (progress - 0.15) / 0.65));
  return (
    <section className="proc" ref={ref} id="proceso" data-screen-label="06 Proceso">
      <Chapter
        num="CAP. 05"
        kicker="DEL CONCEPTO A LA REALIDAD"
        title={<>Cinco pasos, <em>una sola firma.</em></>}
      />
      <div className="proc__timeline">
        <div className="proc__track">
          <div className="proc__fill" style={{ height: `${filled * 100}%` }} />
        </div>
        {PROCESS.map((p, i) => {
          const stepProg = filled * PROCESS.length;
          const active = stepProg > i + 0.2;
          return (
            <div key={p.n} className={`proc__step ${active ? 'is-active' : ''}`}>
              <div className="proc__dot"><span /></div>
              <div className="proc__body">
                <div className="proc__num">{p.n}</div>
                <h3 className="proc__title">{p.t}</h3>
                <p className="proc__desc">{p.d}</p>
              </div>
              <div className="proc__rule" />
            </div>
          );
        })}
      </div>
    </section>
  );
};

/* =====================================================================
   STATS — animated counters
   ===================================================================== */
const STATS = [
  { v: 142, suffix: '', label: 'Proyectos entregados', sub: '2009 — 2026' },
  { v: 17, suffix: '', label: 'Años de práctica', sub: 'Lagos · Guadalajara' },
  { v: 98, suffix: '%', label: 'Clientes que vuelven', sub: 'Segundo encargo o referido' },
  { v: 38600, suffix: ' m²', label: 'Metros construidos', sub: 'Residencial + corporativo' },
];

const Counter = ({ v, suffix, target }) => {
  const [val, setVal] = useState(0);
  useEffect(() => {
    if (!target) return;
    const start = performance.now();
    const dur = 1800;
    let raf;
    const tick = (t) => {
      const k = Math.min(1, (t - start) / dur);
      const eased = 1 - Math.pow(1 - k, 3);
      setVal(Math.round(v * eased));
      if (k < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, v]);
  return <span>{val.toLocaleString('es-MX')}{suffix}</span>;
};

const Stats = () => {
  const [ref, inView] = useInView({ threshold: 0.3 });
  return (
    <section className="stats" ref={ref} data-screen-label="07 Estadísticas">
      <div className="stats__inner">
        <div className="stats__head">
          <span className="chapter__num">CAP. 06</span>
          <span className="chapter__line" />
          <span className="chapter__kicker">EN NÚMEROS</span>
        </div>
        <div className="stats__grid">
          {STATS.map((s, i) => (
            <div key={i} className={`stat ${inView ? 'is-in' : ''}`} style={{ transitionDelay: `${i * 90}ms` }}>
              <div className="stat__value">
                {inView ? <Counter v={s.v} suffix={s.suffix} target={inView} /> : <span>0{s.suffix}</span>}
              </div>
              <div className="stat__label">{s.label}</div>
              <div className="stat__sub">{s.sub}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

/* =====================================================================
   TESTIMONIALS
   ===================================================================== */
const TESTIMONIALS = [
  {
    q: 'No nos entregaron una casa. Nos entregaron un lugar para envejecer juntos. La diferencia es enorme y se siente en cada esquina.',
    a: 'Elena & Rodrigo M.',
    r: 'Casa El Mirador · Residencial',
  },
  {
    q: 'Tomaron una hacienda del XVIII que se nos caía encima y la convirtieron en oficinas funcionales sin perder un solo arco original.',
    a: 'Ignacio Vázquez',
    r: 'Director · Grupo VVC',
  },
  {
    q: 'Es el único estudio con el que he trabajado donde el presupuesto inicial fue el presupuesto final. Y eso, en construcción, no existe.',
    a: 'Patricia Olvera',
    r: 'Hotelería boutique',
  },
];

const Testimonials = () => (
  <section className="test" data-screen-label="08 Testimonios">
    <Chapter
      num="CAP. 07"
      kicker="CLIENTES"
      title={<>Lo que dicen quienes <em>ya viven</em> en nuestra obra.</>}
    />
    <div className="test__grid">
      {TESTIMONIALS.map((t, i) => {
        const [ref, inView] = useInView({ threshold: 0.2 });
        return (
          <figure key={i} ref={ref} className={`test__card ${inView ? 'is-in' : ''}`} style={{ transitionDelay: `${i * 100}ms` }}>
            <svg className="test__quote" width="34" height="26" viewBox="0 0 34 26" fill="none">
              <path d="M0 26 V14 C0 6 6 0 14 0 V6 C10 6 8 8 8 14 H14 V26 H0 Z M20 26 V14 C20 6 26 0 34 0 V6 C30 6 28 8 28 14 H34 V26 H20 Z" fill="currentColor" />
            </svg>
            <blockquote className="test__q">{t.q}</blockquote>
            <figcaption className="test__a">
              <span className="test__name">{t.a}</span>
              <span className="test__role">{t.r}</span>
            </figcaption>
          </figure>
        );
      })}
    </div>
  </section>
);

/* =====================================================================
   CTA
   ===================================================================== */
const CTA = () => {
  const [ref, inView] = useInView({ threshold: 0.25 });
  return (
    <section className="cta" id="contacto" ref={ref} data-screen-label="09 CTA">
      <div className={`cta__inner ${inView ? 'is-in' : ''}`}>
        <div className="cta__eyebrow">
          <span className="dot" />
          <span>CONVERSEMOS</span>
        </div>
        <h2 className="cta__title">
          <span>Transformemos su</span>
          <span><em>proyecto</em> en realidad.</span>
        </h2>
        <p className="cta__lede">
          Recibimos un número limitado de encargos al año. Cada proyecto comienza con una conversación de 60 minutos, sin costo, en nuestro estudio o en el sitio.
        </p>
        <div className="cta__actions">
          <a href="#agendar" className="btn btn--primary">
            <span>Agendar reunión</span>
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M3 13 L13 3 M6 3 H13 V10" stroke="currentColor" strokeWidth="1.4" /></svg>
          </a>
          <a href="#cotizar" className="btn btn--ghost">
            <span>Solicitar cotización</span>
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M3 13 L13 3 M6 3 H13 V10" stroke="currentColor" strokeWidth="1.4" /></svg>
          </a>
        </div>
        <div className="cta__contact">
          <div>
            <span className="cta__contact-label">Estudio Lagos</span>
            <span className="cta__contact-value">Calle Hidalgo 214, Centro Histórico<br />Lagos de Moreno, Jalisco · 47400</span>
          </div>
          <div>
            <span className="cta__contact-label">Correo directo</span>
            <span className="cta__contact-value">estudio@castellano-arq.mx<br />+52 474 ··· ····</span>
          </div>
          <div>
            <span className="cta__contact-label">Horario</span>
            <span className="cta__contact-value">Lun — Vie · 09:00 — 18:00<br />Sáb · cita previa</span>
          </div>
        </div>
      </div>
    </section>
  );
};

/* =====================================================================
   FOOTER
   ===================================================================== */
const Footer = () => (
  <footer className="footer">
    <div className="footer__inner">
      <div className="footer__brand">
        <div className="footer__mark">
          <svg width="34" height="34" viewBox="0 0 22 22" fill="none">
            <path d="M2 19 L11 3 L20 19 M6 14 L16 14" stroke="currentColor" strokeWidth="1.2" />
          </svg>
        </div>
        <div className="footer__name">CASTELLANO</div>
        <div className="footer__tag">Arquitectura · Construcción · Proyectos empresariales</div>
      </div>
      <div className="footer__cols">
        <div>
          <div className="footer__col-h">Estudio</div>
          <ul><li><a href="#">Nosotros</a></li><li><a href="#">Equipo</a></li><li><a href="#">Prensa</a></li><li><a href="#">Premios</a></li></ul>
        </div>
        <div>
          <div className="footer__col-h">Disciplinas</div>
          <ul><li><a href="#">Residencial</a></li><li><a href="#">Construcción</a></li><li><a href="#">Empresarial</a></li><li><a href="#">Interiorismo</a></li></ul>
        </div>
        <div>
          <div className="footer__col-h">Contacto</div>
          <ul><li><a href="#">Lagos de Moreno</a></li><li><a href="#">Guadalajara</a></li><li><a href="#">Instagram</a></li><li><a href="#">LinkedIn</a></li></ul>
        </div>
      </div>
    </div>
    <div className="footer__rule" />
    <div className="footer__legal">
      <span>© MMXXVI Castellano Estudio de Arquitectura. Todos los proyectos pertenecen a sus respectivos clientes.</span>
      <span>Hecho en Lagos de Moreno, Jalisco · MX</span>
    </div>
  </footer>
);

/* =====================================================================
   APP
   ===================================================================== */
const App = () => (
  <>
    <Nav />
    <main>
      <Hero />
      <About />
      <Services />
      <Blueprint />
      <Projects />
      <Process />
      <Stats />
      <Testimonials />
      <CTA />
    </main>
    <Footer />
  </>
);

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
