/* Edward West Luxury Homes — single-file React app
   Hash routing: #/  #/portfolio  #/project/:slug  #/process  #/contact
*/

const { useState, useEffect, useRef, useMemo, useCallback } = React;
const D = window.EW_DATA;

/* ── History router ──────────────────────────────────────────────────────── */
function parsePath() {
  const path = location.pathname.replace(/^\/+|\/+$/g, "");
  const parts = path.split("/").filter(Boolean);
  if (parts.length === 0) return { name: "home" };
  if (parts[0] === "portfolio") return { name: "portfolio" };
  if (parts[0] === "process") return { name: "process" };
  if (parts[0] === "contact") return { name: "contact" };
  if (parts[0] === "project" && parts[1]) return { name: "project", slug: parts[1] };
  return { name: "home" };
}
function useRoute() {
  const [route, setRoute] = useState(parsePath());
  useEffect(() => {
    const onPop = () => { setRoute(parsePath()); window.scrollTo({ top: 0, behavior: "instant" }); };
    window.addEventListener("popstate", onPop);
    window.addEventListener("ew:navigate", onPop);
    return () => { window.removeEventListener("popstate", onPop); window.removeEventListener("ew:navigate", onPop); };
  }, []);
  return route;
}
function navigate(to) {
  history.pushState({}, "", to);
  window.dispatchEvent(new Event("ew:navigate"));
}
const Link = ({ to, children, className = "", ...rest }) => (
  <a
    href={to}
    className={className}
    onClick={(e) => {
      if (e.metaKey || e.ctrlKey || e.shiftKey || e.button === 1) return;
      e.preventDefault();
      navigate(to);
    }}
    {...rest}
  >{children}</a>
);

/* ── Per-route head (title, description, og:image) ───────────────────────── */
function setHead(route) {
  const map = {
    home:      { t: "Edward West Luxury Homes — Custom Home Builder, Kelowna BC", d: "Custom luxury homes in the Okanagan. Licensed BC residential builder. Quietly crafted homes built to last.", img: "/media/hero/hero-poster.jpg" },
    portfolio: { t: "Portfolio — Edward West Luxury Homes", d: "Eleven luxury custom homes built across the Okanagan: Kelowna, Lake Country, West Kelowna, Naramata.", img: "/media/projects/418-sarsons/cover.jpg" },
    process:   { t: "Process — Edward West Luxury Homes", d: "How we build a luxury home end to end: discovery, design, pre-construction, build, handover. Travelers 2-5-10 warranty.", img: "/media/projects/418-sarsons/cover.jpg" },
    contact:   { t: "Contact — Edward West Luxury Homes", d: "Begin a custom home project with Edward West. Sebastian Motora, licensed BC builder, Kelowna.", img: "/media/projects/418-sarsons/cover.jpg" }
  };
  let info = map[route.name];
  if (route.name === "project" && D && D.portfolio) {
    const p = D.portfolio.find(x => x.slug === route.slug);
    if (p) info = { t: `${p.name} — Edward West Luxury Homes`, d: `${p.name}, ${p.location}, ${p.year}. Custom luxury home by Edward West, licensed BC builder.`, img: p.cover };
  }
  if (!info) info = map.home;
  document.title = info.t;
  const setMeta = (sel, attr, val) => {
    let el = document.head.querySelector(sel);
    if (!el) { el = document.createElement("meta"); document.head.appendChild(el); el.setAttribute(sel.match(/\[([^=]+)="([^"]+)"\]/)[1], sel.match(/\[([^=]+)="([^"]+)"\]/)[2]); }
    el.setAttribute(attr, val);
  };
  setMeta('meta[name="description"]', "content", info.d);
  setMeta('meta[property="og:title"]', "content", info.t);
  setMeta('meta[property="og:description"]', "content", info.d);
  setMeta('meta[property="og:image"]', "content", info.img);
  let canon = document.head.querySelector('link[rel="canonical"]');
  if (!canon) { canon = document.createElement("link"); canon.rel = "canonical"; document.head.appendChild(canon); }
  canon.href = `https://edward-west.com${location.pathname}`;
}

/* ── Reveal on scroll ────────────────────────────────────────────────────── */
function Reveal({ children, as: Tag = "div", delay = 0, className = "", style, ...rest }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(
      ([e]) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } },
      { rootMargin: "0px 0px -10% 0px", threshold: 0.1 }
    );
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  const merged = { transitionDelay: `${delay}ms`, ...(style || {}) };
  return <Tag ref={ref} className={`reveal ${seen ? "in" : ""} ${className}`} style={merged} {...rest}>{children}</Tag>;
}

/* ── Magnetic wrapper ────────────────────────────────────────────────────── */
function Magnetic({ children, strength = 0.25 }) {
  const ref = useRef(null);
  const onMove = (e) => {
    const r = ref.current.getBoundingClientRect();
    const x = (e.clientX - (r.left + r.width / 2)) * strength;
    const y = (e.clientY - (r.top + r.height / 2)) * strength;
    ref.current.style.transform = `translate(${x}px, ${y}px)`;
  };
  const onLeave = () => { ref.current.style.transform = ""; };
  return <span ref={ref} className="magnetic" onMouseMove={onMove} onMouseLeave={onLeave}>{children}</span>;
}

/* ── Cursor dot ──────────────────────────────────────────────────────────── */
function CursorDot() {
  const ref = useRef(null);
  useEffect(() => {
    const dot = ref.current;
    let raf, x = 0, y = 0, tx = 0, ty = 0;
    const onMove = (e) => { tx = e.clientX; ty = e.clientY; dot.classList.add("show"); };
    const onLeave = () => dot.classList.remove("show");
    const tick = () => {
      x += (tx - x) * 0.18; y += (ty - y) * 0.18;
      dot.style.transform = `translate(${x}px, ${y}px) translate(-50%, -50%)`;
      raf = requestAnimationFrame(tick);
    };
    window.addEventListener("mousemove", onMove);
    document.body.addEventListener("mouseleave", onLeave);
    raf = requestAnimationFrame(tick);
    return () => { cancelAnimationFrame(raf); window.removeEventListener("mousemove", onMove); document.body.removeEventListener("mouseleave", onLeave); };
  }, []);
  return <div ref={ref} className="cursor-dot" />;
}

/* ── CTA ─────────────────────────────────────────────────────────────────── */
const CTA = ({ to, href, onClick, children }) => {
  const inner = (
    <Magnetic>
      <span className="cta-link">
        <span>{children}</span>
        <span className="arrow">→</span>
        <span className="underline" />
      </span>
    </Magnetic>
  );
  if (to) return <Link to={to}>{inner}</Link>;
  if (href) return <a href={href}>{inner}</a>;
  return <button onClick={onClick}>{inner}</button>;
};

/* ── Nav ─────────────────────────────────────────────────────────────────── */
function Nav({ active }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 80);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <nav className={`nav ${scrolled ? "scrolled" : ""}`}>
      <Link to="/" className="nav-wordmark">
        <span>Edward West</span>
        <span className="dot" />
      </Link>
      <div className="nav-links">
        <Link to="/" className={`nav-link ${active === "home" ? "active" : ""}`}>Home</Link>
        <Link to="/portfolio" className={`nav-link ${active === "portfolio" ? "active" : ""}`}>Portfolio</Link>
        <Link to="/process" className={`nav-link ${active === "process" ? "active" : ""}`}>Process</Link>
        <Link to="/contact" className={`nav-link ${active === "contact" ? "active" : ""}`}>Contact</Link>
      </div>
    </nav>
  );
}

/* ── Footer ──────────────────────────────────────────────────────────────── */
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-grid">
        <div>
          <div className="footer-wordmark">Edward West</div>
          <p className="body" style={{ color: "rgba(244,241,236,0.6)", marginTop: 16, maxWidth: "32ch" }}>
            Custom luxury homes in the Okanagan. Licensed BC residential builder, 2014–present.
          </p>
        </div>
        <div className="footer-col">
          <h4>Studio</h4>
          <ul>
            <li><Link to="/portfolio">Portfolio</Link></li>
            <li><Link to="/process">Process</Link></li>
            <li><Link to="/contact">Contact</Link></li>
          </ul>
        </div>
        <div className="footer-col">
          <h4>Visit</h4>
          <ul>
            <li>Kelowna, BC</li>
            <li>Mon–Fri · 9–5</li>
          </ul>
        </div>
        <div className="footer-col">
          <h4>Reach</h4>
          <ul>
            <li><a href="mailto:sebastian@edward-west.com">sebastian@edward-west.com</a></li>
            <li><a href="https://instagram.com/edwardwestluxuryhomes" target="_blank" rel="noopener">Instagram</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© {new Date().getFullYear()} Edward West Luxury Homes Inc.</span>
        <span>Licensed BC builder · Travelers 2-5-10 · OHAE</span>
      </div>
    </footer>
  );
}

/* ── Hero rotator ────────────────────────────────────────────────────────── */
function Hero() {
  return (
    <section className="hero">
      <div className="hero-stage">
        <video
          className="hero-video"
          src="/media/hero/hero.mp4"
          poster="/media/hero/hero-poster.jpg"
          autoPlay
          muted
          loop
          playsInline
          preload="metadata"
        />
      </div>
      <div className="hero-veil" />
      <div className="hero-grain" />
      <div className="hero-copy">
        <div>
          <h1 className="h-display">Good design is obvious. Great design is transparent.</h1>
          <div className="sub">Custom luxury homes in the Okanagan</div>
        </div>
        <div className="hero-meta">
          Kelowna · BC<br />
          Est. 2014<br />
          Licensed builder
        </div>
      </div>
      <div className="scroll-cue">
        <span>Scroll</span>
        <span className="line" />
      </div>
    </section>
  );
}

/* ── Project card ────────────────────────────────────────────────────────── */
const ProjectCard = ({ p, customAspect }) => (
  <Link to={`/project/${p.slug}`} className="proj">
    <div className="media" style={customAspect ? { aspectRatio: customAspect } : null}>
      <img src={p.cover} alt={p.name} loading="lazy" />
    </div>
    <div className="proj-label">
      <span className="proj-name">{p.name}</span>
      <span className="proj-meta">{p.year} · {p.location}</span>
    </div>
  </Link>
);

/* ── Section head ────────────────────────────────────────────────────────── */
const SectionHead = ({ num, eyebrow, title, sub, right }) => (
  <Reveal className="section-head">
    <div className="lhs">
      <div className="section-num">{num} — {eyebrow}</div>
      <h2 className="h-1" style={{ marginTop: 20 }}>{title}</h2>
      {sub && <p className="body-lg" style={{ marginTop: 24 }}>{sub}</p>}
    </div>
    {right && <div>{right}</div>}
  </Reveal>
);

/* ── Home ────────────────────────────────────────────────────────────────── */
function Home() {
  return (
    <div className="page">
      <Hero />

      <section className="shell">
        <SectionHead
          num="01" eyebrow="Recent work"
          title="Three houses, three answers."
          sub="Each project is a different brief, in a different part of the valley. The thread is restraint — and an envelope built to outlast the trend."
          right={<CTA to="/portfolio">All projects</CTA>}
        />
        <div className="grid-12">
          {D.recentWork.map((p, i) => (
            <Reveal key={p.slug} delay={i * 80} className="" style={{ gridColumn: "span 4" }}>
              <ProjectCard p={p} />
            </Reveal>
          ))}
        </div>
      </section>

      <section className="shell">
        <div className="manifesto">
          <Reveal>
            <h2 className="pull">Treated as if it were our own.</h2>
          </Reveal>
          <Reveal delay={120}>
            <p className="body-lg">
              We build a small number of houses every year. Always for the family who will live in them.
              No spec, no flips, no shortcuts in the wall assembly. Decades of experience, on every project,
              treated as if it were our own.
            </p>
          </Reveal>
        </div>
      </section>

      <section className="shell">
        <SectionHead num="02" eyebrow="Featured" title={D.featured.name} sub={D.featured.location} />
        <div className="featured">
          <Reveal>
            <div className="media">
              <img src={D.featured.image} alt={D.featured.name} loading="lazy" />
            </div>
          </Reveal>
          <div className="narrative">
            <Reveal delay={120}>
              <div className="eyebrow">{D.featured.eyebrow}</div>
              <h2 className="h-2">A modern estate built around active living.</h2>
              <p className="body-lg">{D.featured.blurb}</p>
              <div style={{ marginTop: 32 }}>
                <CTA to={`/project/${D.featured.slug}`}>Read the case study</CTA>
              </div>
            </Reveal>
          </div>
        </div>
      </section>

      <section className="shell">
        <SectionHead num="03" eyebrow="In progress" title="Currently on site." sub="Three active builds across the valley. Schedule and budget shared with the owners weekly." />
        <div className="in-progress-track">
          {D.inProgress.map((p, i) => (
            <Reveal key={p.slug} delay={i * 80} className="ip-card">
              <Link to={`/project/${p.slug}`}>
                <div className="ip-badge"><span className="dot" />In progress · {p.stage}</div>
                <div className="media"><img src={p.image} alt={p.name} loading="lazy" /></div>
                <div className="proj-label">
                  <span className="proj-name">{p.name}</span>
                  <span className="proj-meta">Delivery {p.delivery}</span>
                </div>
              </Link>
            </Reveal>
          ))}
        </div>
      </section>

      <section className="shell">
        <Reveal>
          <div className="awards">
            {D.awards.map((a, i) => (
              <div key={i} className="award">
                <div className="award-title serif">{a.title}</div>
                <div className="award-sub">{a.sub}</div>
              </div>
            ))}
          </div>
        </Reveal>
      </section>

      <section className="shell">
        <div className="conversation" style={{ backgroundImage: `url(${D.conversation})` }}>
          <div className="conversation-inner">
            <Reveal>
              <div className="eyebrow" style={{ color: "rgba(244,241,236,0.7)" }}>Begin a project</div>
              <h2 className="h-1" style={{ color: "var(--bone)" }}>Start a conversation about a house we will build for you.</h2>
              <CTA to="/contact">Start a conversation</CTA>
            </Reveal>
          </div>
        </div>
      </section>
    </div>
  );
}

/* ── Portfolio ───────────────────────────────────────────────────────────── */
function Portfolio() {
  const [year, setYear] = useState("All");
  const [type, setType] = useState("All");
  const [loc, setLoc] = useState("All");

  const years = ["All", ...new Set(D.portfolio.map(p => p.year))];
  const types = ["All", ...new Set(D.portfolio.map(p => p.type))];
  const locs  = ["All", ...new Set(D.portfolio.map(p => p.location.split(",")[0].trim()))];

  const list = D.portfolio.filter(p =>
    (year === "All" || p.year === year) &&
    (type === "All" || p.type === type) &&
    (loc === "All" || p.location.startsWith(loc))
  );

  return (
    <div className="page">
      <section className="shell portfolio-head">
        <Reveal>
          <div className="section-num">Portfolio — {D.portfolio.length} projects</div>
          <h1 className="h-display" style={{ marginTop: 24, maxWidth: "16ch" }}>Houses we have built across the valley.</h1>
        </Reveal>
      </section>

      <section className="shell" style={{ paddingTop: 0 }}>
        <div className="filter-bar">
          <div className="filter-group">
            <span className="filter-label">Year</span>
            {years.map(y => (
              <button key={y} className={`chip ${year === y ? "on" : ""}`} onClick={() => setYear(y)}>{y}</button>
            ))}
          </div>
          <div className="filter-group">
            <span className="filter-label">Type</span>
            {types.map(t => (
              <button key={t} className={`chip ${type === t ? "on" : ""}`} onClick={() => setType(t)}>{t}</button>
            ))}
          </div>
          <div className="filter-group">
            <span className="filter-label">Location</span>
            {locs.map(l => (
              <button key={l} className={`chip ${loc === l ? "on" : ""}`} onClick={() => setLoc(l)}>{l}</button>
            ))}
          </div>
        </div>

        <div className="masonry">
          {list.map((p, i) => (
            <Reveal key={p.slug} delay={(i % 4) * 60}>
              <ProjectCard p={p} customAspect={p.h ? `${1} / ${p.h}` : null} />
            </Reveal>
          ))}
        </div>
      </section>
    </div>
  );
}

/* ── Lightbox ────────────────────────────────────────────────────────────── */
function Lightbox({ images, idx, onClose, onPrev, onNext }) {
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowLeft") onPrev();
      if (e.key === "ArrowRight") onNext();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose, onPrev, onNext]);
  if (idx == null) return null;
  return (
    <div className="lightbox open" onClick={onClose}>
      <button className="lb-close cta-link" onClick={onClose}>Close <span className="arrow">×</span></button>
      <button className="lb-arrow lb-prev" onClick={(e) => { e.stopPropagation(); onPrev(); }}>←</button>
      <button className="lb-arrow lb-next" onClick={(e) => { e.stopPropagation(); onNext(); }}>→</button>
      <img src={images[idx]} alt="" onClick={(e) => e.stopPropagation()} />
      <div className="lb-count">{String(idx + 1).padStart(2, "0")} / {String(images.length).padStart(2, "0")}</div>
    </div>
  );
}

/* ── Project (case study) ────────────────────────────────────────────────── */
function Project({ slug }) {
  const project = D.portfolio.find(p => p.slug === slug);
  const isFeatured = slug === D.caseStudy.slug;
  const cs = isFeatured ? D.caseStudy : null;
  const [lb, setLb] = useState(null);

  if (!project) return <NotFound />;

  const gallery = project.gallery && project.gallery.length ? project.gallery : [project.cover];
  const stats = cs ? cs.stats : [
    { k: "Year", v: project.year },
    { k: "Type", v: project.type },
    { k: "Location", v: project.location.split(",")[0] }
  ];
  const narrative = cs ? cs.narrative : [
    `${project.name} is a ${project.type.toLowerCase()} in ${project.location}, completed in ${project.year}. The brief, the site, and the family converged on a single answer: a house that does its work quietly.`
  ];

  const next = useMemo(() => {
    const i = D.portfolio.findIndex(p => p.slug === slug);
    return D.portfolio[(i + 1) % D.portfolio.length];
  }, [slug]);

  return (
    <div className="page">
      <section className="shell" style={{ paddingBottom: 0 }}>
        <div className="case-cover">
          <div className="media-fill">
            <img src={project.cover} alt={project.name} />
          </div>
        </div>
      </section>

      <section className="shell">
        <Reveal>
          <div className="section-num">Project · {project.year}</div>
          <h1 className="h-display" style={{ marginTop: 24 }}>{project.name}</h1>
          <div className="eyebrow" style={{ marginTop: 12 }}>{project.location}</div>
        </Reveal>

        <Reveal delay={120}>
          <dl className="case-meta-strip" style={{ marginTop: 64 }}>
            {stats.map(s => (
              <div key={s.k}>
                <dt>{s.k}</dt>
                <dd>{s.v}</dd>
              </div>
            ))}
          </dl>
        </Reveal>

        <div className="case-narrative">
          <Reveal className="text">
            <p className="body-lg dropcap">{narrative[0]}</p>
            {narrative.slice(1).map((p, i) => <p key={i} className="body-lg" style={{ marginTop: 24 }}>{p}</p>)}
          </Reveal>
        </div>
      </section>

      {/* Gallery rhythm */}
      <section className="shell" style={{ paddingTop: 0 }}>
        <div className="gallery-rhythm">
          {gallery[0] && (
            <Reveal className="fullbleed">
              <div className="media" onClick={() => setLb(0)}>
                <img src={gallery[0]} alt="" loading="lazy" />
                <div className="grain" />
              </div>
            </Reveal>
          )}
          {(gallery[1] || gallery[2]) && (
            <Reveal className="two-up offset">
              {gallery[1] && (
                <div className="media" onClick={() => setLb(1)}>
                  <img src={gallery[1]} alt="" loading="lazy" />
                </div>
              )}
              {gallery[2] && (
                <div className="media" onClick={() => setLb(2)}>
                  <img src={gallery[2]} alt="" loading="lazy" />
                </div>
              )}
            </Reveal>
          )}
          {gallery[3] && (
            <Reveal className="fullbleed">
              <div className="media" onClick={() => setLb(3)}>
                <img src={gallery[3]} alt="" loading="lazy" />
                <div className="grain" />
              </div>
            </Reveal>
          )}
          {gallery.length > 4 && (
            <Reveal className="four-up">
              {gallery.slice(4, 8).map((g, i) => (
                <div key={i} className="media" onClick={() => setLb(4 + i)}>
                  <img src={g} alt="" loading="lazy" />
                </div>
              ))}
            </Reveal>
          )}
          {gallery.length > 8 && (
            <Reveal className="fullbleed">
              <div className="media" onClick={() => setLb(8)}>
                <img src={gallery[8]} alt="" loading="lazy" />
              </div>
            </Reveal>
          )}
          {gallery.length > 9 && (
            <Reveal className="four-up">
              {gallery.slice(9, 13).map((g, i) => (
                <div key={i} className="media" onClick={() => setLb(9 + i)}>
                  <img src={g} alt="" loading="lazy" />
                </div>
              ))}
            </Reveal>
          )}
          {gallery.length > 13 && (
            <Reveal className="two-up">
              {gallery.slice(13, 15).map((g, i) => (
                <div key={i} className="media" onClick={() => setLb(13 + i)}>
                  <img src={g} alt="" loading="lazy" />
                </div>
              ))}
            </Reveal>
          )}
        </div>
      </section>

      {cs && (
        <section className="shell">
          <SectionHead num="—" eyebrow="Detail" title="Materials & partners." />
          <div className="materials-grid">
            <Reveal>
              <h3 className="eyebrow">Materials</h3>
              <dl style={{ marginTop: 20 }}>
                {cs.materials.map(p => (
                  <div key={p.k} style={{ display: "grid", gridTemplateColumns: "140px 1fr", padding: "14px 0", borderTop: "1px solid var(--rule)" }}>
                    <dt className="mono">{p.k}</dt>
                    <dd className="serif" style={{ margin: 0, fontSize: 18 }}>{p.v}</dd>
                  </div>
                ))}
              </dl>
            </Reveal>
            <Reveal delay={120}>
              <h3 className="eyebrow">Partners</h3>
              <dl style={{ marginTop: 20 }}>
                {cs.partners.map(p => (
                  <div key={p.k} style={{ display: "grid", gridTemplateColumns: "140px 1fr", padding: "14px 0", borderTop: "1px solid var(--rule)" }}>
                    <dt className="mono">{p.k}</dt>
                    <dd className="serif" style={{ margin: 0, fontSize: 18 }}>{p.v}</dd>
                  </div>
                ))}
              </dl>
            </Reveal>
          </div>
        </section>
      )}

      {/* Next project */}
      <Link to={`/project/${next.slug}`}>
        <section className="shell" style={{ paddingTop: 0 }}>
          <div className="conversation" style={{ backgroundImage: `url(${next.cover})` }}>
            <div className="conversation-inner">
              <div className="eyebrow" style={{ color: "rgba(244,241,236,0.7)" }}>Next project</div>
              <h2 className="h-1" style={{ color: "var(--bone)" }}>{next.name}</h2>
              <div className="cta-link" style={{ color: "var(--bone)" }}>
                <span>{next.year} · {next.location}</span>
                <span className="arrow">→</span>
                <span className="underline" />
              </div>
            </div>
          </div>
        </section>
      </Link>

      <Lightbox
        images={gallery}
        idx={lb}
        onClose={() => setLb(null)}
        onPrev={() => setLb((i) => (i - 1 + gallery.length) % gallery.length)}
        onNext={() => setLb((i) => (i + 1) % gallery.length)}
      />
    </div>
  );
}

/* ── Process ─────────────────────────────────────────────────────────────── */
function Process() {
  return (
    <div className="page">
      <section className="shell portfolio-head">
        <Reveal>
          <div className="section-num">Process — five phases</div>
          <h1 className="h-display" style={{ marginTop: 24, maxWidth: "14ch" }}>How we build a house, end to end.</h1>
          <p className="body-lg" style={{ maxWidth: "60ch", marginTop: 32 }}>
            Every project runs through the same five phases. The difference between us and a build that goes sideways is that the schedule we hand you on day one is the schedule we keep on day six hundred.
          </p>
        </Reveal>
      </section>

      <section className="shell" style={{ paddingTop: 0 }}>
        {D.process.map((ph, i) => (
          <Reveal key={ph.num} delay={i * 60}>
            <div className="phase">
              <div className="phase-num">{ph.num}</div>
              <div>
                <div className="phase-title">{ph.title}</div>
                <div className="phase-meta">{ph.duration} · {ph.inputs}</div>
              </div>
              <div>
                <p className="body-lg">{ph.body}</p>
              </div>
            </div>
          </Reveal>
        ))}
      </section>
    </div>
  );
}

/* ── Contact ─────────────────────────────────────────────────────────────── */
function Contact() {
  const [form, setForm] = useState({ name: "", email: "", projectType: "Custom", location: "", timeline: "", budget: "$2-5M", message: "" });
  const [sent, setSent] = useState(false);
  const upd = (k) => (e) => setForm({ ...form, [k]: e.target ? e.target.value : e });

  const submit = (e) => {
    e.preventDefault();
    const subject = encodeURIComponent(`Enquiry — ${form.name || "no name"}`);
    const body = encodeURIComponent(
`Name: ${form.name}
Email: ${form.email}
Project type: ${form.projectType}
Site location: ${form.location}
Timeline: ${form.timeline}
Budget: ${form.budget}

${form.message}`
    );
    window.location.href = `mailto:sebastian@edward-west.com?subject=${subject}&body=${body}`;
    setSent(true);
  };

  return (
    <div className="page">
      <section className="shell portfolio-head">
        <Reveal>
          <div className="section-num">Contact — begin a project</div>
          <h1 className="h-display" style={{ marginTop: 24, maxWidth: "14ch" }}>Tell us about the house you want to build.</h1>
        </Reveal>
      </section>

      <section className="shell" style={{ paddingTop: 0 }}>
        <div className="contact-grid">
          <Reveal>
            <form onSubmit={submit}>
              <div className="form-row">
                <label>Name</label>
                <input value={form.name} onChange={upd("name")} placeholder="Your name" required />
              </div>
              <div className="form-row">
                <label>Email</label>
                <input type="email" value={form.email} onChange={upd("email")} placeholder="you@email.com" required />
              </div>
              <div className="form-row">
                <label>Project type</label>
                <div className="radio-set">
                  {["New build", "Custom", "Renovation", "Other"].map(t => (
                    <button key={t} type="button" className={`radio-pill ${form.projectType === t ? "on" : ""}`} onClick={() => setForm({ ...form, projectType: t })}>{t}</button>
                  ))}
                </div>
              </div>
              <div className="form-row">
                <label>Site location</label>
                <input value={form.location} onChange={upd("location")} placeholder="Lake Country, Kelowna, Naramata…" />
              </div>
              <div className="form-row">
                <label>Timeline</label>
                <input value={form.timeline} onChange={upd("timeline")} placeholder="When would you want to break ground?" />
              </div>
              <div className="form-row">
                <label>Budget range</label>
                <div className="radio-set">
                  {["$1-2M", "$2-5M", "$5M+", "Open"].map(b => (
                    <button key={b} type="button" className={`radio-pill ${form.budget === b ? "on" : ""}`} onClick={() => setForm({ ...form, budget: b })}>{b}</button>
                  ))}
                </div>
              </div>
              <div className="form-row">
                <label>Tell us about the house</label>
                <textarea rows={5} value={form.message} onChange={upd("message")} placeholder="The site, the family, the way you want to live in it." />
              </div>
              <button type="submit" className="submit-btn">
                {sent ? "Opening your email…" : "Send the brief"}
                <span className="arrow">→</span>
              </button>
            </form>
          </Reveal>

          <Reveal delay={120} className="contact-side">
            <div className="eyebrow">What happens next</div>
            <div className="next-steps">
              {[
                ["01", "We read your brief and respond within two business days."],
                ["02", "If we're the right builder for the project, we book a 45-minute call."],
                ["03", "If both sides want to keep going, we walk the site together — no fee."],
                ["04", "We send a written proposal and a target schedule before any line is drawn."]
              ].map(([n, t]) => (
                <div key={n} className="next-step">
                  <span className="n">{n}</span>
                  <span className="body">{t}</span>
                </div>
              ))}
            </div>

            <div className="quote">
              "Built like they are our own — because for thirteen months at a time, they are."
            </div>

            <div className="eyebrow" style={{ marginTop: 32 }}>Direct</div>
            <h3>Sebastian Motora</h3>
            <p className="body" style={{ marginTop: 4 }}>
              <a href="mailto:sebastian@edward-west.com">sebastian@edward-west.com</a><br />
              Kelowna, BC
            </p>
          </Reveal>
        </div>
      </section>
    </div>
  );
}

function NotFound() {
  return (
    <div className="page shell" style={{ minHeight: "70vh", display: "flex", flexDirection: "column", justifyContent: "center", paddingTop: 200 }}>
      <div className="section-num">404</div>
      <h1 className="h-1" style={{ marginTop: 24 }}>That page is not built yet.</h1>
      <div style={{ marginTop: 32 }}><CTA to="/">Back home</CTA></div>
    </div>
  );
}

/* ── App ─────────────────────────────────────────────────────────────────── */
function App() {
  const route = useRoute();
  useEffect(() => { setHead(route); }, [route]);
  let body;
  switch (route.name) {
    case "portfolio": body = <Portfolio />; break;
    case "project":   body = <Project slug={route.slug} />; break;
    case "process":   body = <Process />; break;
    case "contact":   body = <Contact />; break;
    default:          body = <Home />;
  }
  return (
    <>
      <CursorDot />
      <Nav active={route.name} />
      {body}
      <Footer />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("app")).render(<App />);
