/* global React, window */
const { Ph, Arrow, SiteScrollCtx } = window;
const { motion, AnimatePresence, useMotionValue, useSpring, useScroll, useTransform } = window.FM || {};

const Mdiv = motion.div || "div";
const Mspan = motion.span || "span";

// Editorial 2026 home
function HomeEditorial({ go }) {
  return (
    <div>
      <EditorialHero go={go} />
      <EditorialIndex go={go} />
      <window.HomePhilosophy/>
      <window.HomeStats/>
      <window.HomeServices go={go}/>
      <window.HomeProcess/>
      <window.HomeContact go={go}/>
    </div>
  );
}

// Hero lines for text reveal
const E_LINES = [
  { parts: [{ text: "L'architecture", em: false }] },
  { parts: [{ text: "que vous", em: true }, { text: " imaginiez.", em: false }] },
];

function EditorialHero({ go }) {
  const imgUrl = window.PROJECTS[0].img;
  const imgRef = React.useRef(null);
  React.useEffect(() => {
    let rafId;
    const tick = () => {
      if (imgRef.current) {
        const y = window.scrollY;
        imgRef.current.style.transform = `scale(1.0) translateY(${y * 0.28}px)`;
      }
      rafId = requestAnimationFrame(tick);
    };
    rafId = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafId);
  }, []);
  return (
    <section className="ehero">
      {/* Parallax image with Ken Burns intro */}
      <Mdiv
        className="ehero__media"
        style={{ position: "absolute", inset: 0, overflow: "hidden" }}
        initial={false}
      >
        {/* Outer div: parallax translate via RAF */}
        <div ref={imgRef} style={{ position: "absolute", inset: "-15%", willChange: "transform" }}>
          {/* Inner div: Ken Burns scale via CSS animation */}
          <div style={{
            position: "absolute", inset: 0,
            backgroundImage: `url(${imgUrl})`,
            backgroundSize: "cover",
            backgroundPosition: "center",
            animation: "kenburns 12s cubic-bezier(0.25,1,0.5,1) forwards",
          }} />
        </div>
        {/* Gradient overlay */}
        <div style={{
          position: "absolute", inset: 0, pointerEvents: "none",
          background: "linear-gradient(180deg, rgba(0,0,0,0.55) 0%, rgba(0,0,0,0.12) 30%, rgba(0,0,0,0.12) 60%, rgba(0,0,0,0.88) 100%)"
        }} />
      </Mdiv>

      <div className="ehero__overlay">
        <div className="ehero__top">
          <Mdiv
            className="ehero__no"
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, delay: 0.2 }}
          >
            N°024 <span>—</span> Sélection 2026
          </Mdiv>
          <Mdiv
            className="ehero__cap"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.8, delay: 0.4 }}
          >
            Villa des Sources<br/>Rixensart · 320 m² · livré 2024
          </Mdiv>
        </div>

        <div>
          {/* Large title text reveal */}
          <h1 className="ehero__title" style={{ marginBottom: 32 }}>
            {E_LINES.map((line, li) => (
              <span key={li} style={{ display: "block", overflow: "hidden", lineHeight: 0.92 }}>
                <Mspan
                  style={{ display: "block" }}
                  initial={{ y: "108%" }}
                  animate={{ y: "0%" }}
                  transition={{ duration: 1.0, ease: [0.16, 1, 0.3, 1], delay: 0.35 + li * 0.14 }}
                >
                  {line.parts.map((p, pi) => p.em ? <em key={pi}>{p.text}</em> : p.text)}
                </Mspan>
              </span>
            ))}
          </h1>

          <div className="ehero__bottom">
            <Mdiv
              className="ehero__lede"
              initial={{ opacity: 0, y: 12 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.7, delay: 0.75 }}
            >
              Bureau d'architecture en Brabant Wallon et à Bruxelles. Maisons contemporaines,
              extensions, rénovations énergétiques — un travail patient, à deux générations.
            </Mdiv>
            <Mdiv
              className="ehero__meta"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ duration: 0.6, delay: 0.9 }}
            >
              <div><span className="k">Depuis</span><span className="v">1991</span></div>
              <div><span className="k">Projets</span><span className="v">120+</span></div>
              <div><span className="k">Architectes</span><span className="v">02</span></div>
            </Mdiv>
            <Mdiv
              className="ehero__cta"
              initial={{ opacity: 0, x: 16 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.6, delay: 1.0 }}
            >
              <a className="btn btn--primary" data-cursor-label="Voir →" onClick={() => go("realisations")}>Réalisations <Arrow/></a>
            </Mdiv>
          </div>
        </div>
      </div>
    </section>
  );
}

// Editorial index with spring-based hover preview (pure refs + RAF)
function EditorialIndex({ go }) {
  const [hover, setHover] = React.useState(null);
  const wrapRef = React.useRef(null);
  const rawX = React.useRef(0), rawY = React.useRef(0);
  const curX = React.useRef(0), curY = React.useRef(0);
  const vx   = React.useRef(0), vy   = React.useRef(0);

  const onMove = (e) => {
    rawX.current = Math.min(e.clientX + 28, window.innerWidth - 390);
    rawY.current = Math.max(e.clientY - 240, 60);
  };

  React.useEffect(() => {
    if (!hover) return;
    let on = true;
    const stiffness = 180, damping = 22, mass = 0.8, dt = 1/60;
    const tick = () => {
      if (!on || !wrapRef.current) return;
      const Fx = -stiffness*(curX.current-rawX.current) - damping*vx.current;
      const Fy = -stiffness*(curY.current-rawY.current) - damping*vy.current;
      vx.current += (Fx/mass)*dt; vy.current += (Fy/mass)*dt;
      curX.current += vx.current*dt; curY.current += vy.current*dt;
      wrapRef.current.style.transform = `translate(${curX.current}px,${curY.current}px)`;
      requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
    return () => { on = false; };
  }, [hover && hover.id]);

  return (
    <section
      className="eindex sec--plan"
      onMouseMove={onMove}
      onMouseLeave={() => setHover(null)}
    >
      <div className="eindex__head">
        <div>
          <div className="eyebrow" style={{ marginBottom: 18 }}>Index · 2018 — 2026</div>
          <h2><em>Œuvre</em><br/>sélectionnée.</h2>
        </div>
        <p className="body">
          Neuf projets parmi cent vingt livrés. Chaque ligne est une rencontre, un terrain,
          une contrainte transformée en geste — survolez pour découvrir l'image.
        </p>
      </div>

      <div className="eindex__list">
        {window.PROJECTS.map((p, i) => (
          <div
            key={p.id}
            className="erow"
            data-cursor-label="Voir →"
            onMouseEnter={() => setHover(p)}
            onClick={() => go("project", p.id)}
          >
            <div className="erow__no">{String(i + 1).padStart(3, "0")} /</div>
            <div className="erow__title">
              {p.title.split(" ").slice(0, -1).join(" ")} <em>{p.title.split(" ").slice(-1)}</em>
            </div>
            <div className="erow__cat">{p.cat}</div>
            <div className="erow__loc">{p.loc}</div>
            <div className="erow__year">{p.year}</div>
            <div className="erow__arrow">↗</div>
          </div>
        ))}
      </div>

      {/* Spring preview — outer div moves via RAF spring, inner animates in via CSS */}
      {hover && (
        <div
          ref={wrapRef}
          style={{ position: "fixed", top: 0, left: 0, pointerEvents: "none", zIndex: 20, willChange: "transform" }}
        >
          <div
            key={hover.id}
            className="eindex__preview"
            style={{
              width: 360, height: 460,
              backgroundImage: `url(${hover.img})`,
              backgroundSize: "cover",
              backgroundPosition: "center",
              boxShadow: "0 32px 64px -16px rgba(0,0,0,0.45)",
            }}
          />
        </div>
      )}
    </section>
  );
}

Object.assign(window, { HomeEditorial });
