// Shared building blocks for the site: brand primitives, the header and footer,
// the calligraphy intro, and the motion engine.
//
// All JSX files share ONE global scope (Babel standalone, no bundler). This file
// owns the hook destructure below; every other file uses React.useState etc.
const { useState, useEffect, useRef, useLayoutEffect } = React;

const DH_REDUCED = () => !!(window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches);

/* ------------------------------- the mark -----------------------------------
   Two layers: the letters, and the vowel strokes that sit beneath and inside
   them. One colour (Dusk) on Salt, Stone or Reed. Two colour on Dusk only.   */
const DH_MARK = {
  vb: "0 0 1002.66 776.48",
  letters: "M1002.62,148.69c-.65-13.76-4.93-73.27-51.98-113.71-57.3-49.25-144.85-42.67-196.82-4.03-62.57,46.52-97.14,156.65-61.12,228.18,3.09.36,1.27-3.33.89-5.01-.94-4.14-3.04-8.25-3.76-12.74-10.59-66.02,23.59-141.09,88.64-164.34,73.6-26.3,166.74,19.02,185.74,96.04,6.29,25.5,4.78,32.42-9.71,53.61-26.94,39.4-84.91,81.69-134,83.62-24.9.98-50.69-16.78-50.17-43.58.24-12.35,26.51-87.37-15.03-54.59-22.24,17.55-45.7,49.77-68.36,70.13-83.89,75.35-239.77,144.27-341.96,66.56-31.43-23.9-50.78-56.08-50.53-96.29,44.75-31.28,79.84,11.5,114.8,33.67,88.8,56.31,153.17,1.99,176.69-86.81,20.33-76.74-33.71-141.15-99.88-171.35C400.39-11.06,312.52-2.19,228.83,36.82c-19.15,8.92-68.98,33.33-116.17,82.21C14.43,220.75,2.35,349.97.21,393.55c-.65,10.56-.47,31.41,10.33,53.97,6.13,12.81,15.52,33.14,34.9,40.71,35.71,13.96,82.27-20.12,109.74-53.55,5.31-6.46,12.49-14.34,14.87-22.21l-18.95,19.77-.8-2.44c16.05-16.36,29.72-34.72,41.29-54.42,10.4-17.71,19.76-35.87,33.19-54.11,16.17-21.97,34-42.94,54.95-60.46,5.05-.42.8,1.79.8,2.46v36.27c0,20.35,16.64,55.45,28.33,72.24,9.53,13.69,19.71,24.8,30.66,34.08,32.98,27.93,69.3,38.39,91.93,44.51,5.76,1.56,10.5,2.65,13.46,3.3,32.84,3.55,64.31,1.26,96.1-7.4,41.1-11.19,69.75-29.78,86.24-40.7,16.54-10.95,38.18-27.33,60.49-50.81l56.89-65.92c-1.56,16.62-1.32,33.12,2.47,49.44,1.79,7.93,5.38,17.61,13.22,25.52,31.89,32.18,114.66,16,160.46-24.19,61.68-54.12,76.49-129.86,79.72-154.31,1.96-14.82,2.27-27.44,2.13-36.61h0ZM267.31,256.65c-12.83,12.07-25.31,25.83-35.97,39.87-9.25,12.17-19.98,26.75-27.95,37.32-3.9,5.17-7,12.3-11.2,17.5-11.06,13.7-22.5,26.86-36.14,38.04-2.78-.98,8.98-13.06,1.68-9.87-2.4,1.05-11.47,10.35-15.14,12.9-12.67,8.78-42.48,26.38-57.42,26.37-2.95,0-18.46-3.17-21.96-4.13-22.97-6.35-31.84-36.19-33.24-57.43-1.65-24.94,22.94-83.07,35.38-106.35C139.04,112.95,358.31,9.84,493.98,120.71c25.5,20.84,63.53,66.33,58.65,101.43-.82,5.92-3.73,6.84-8.51,9.61-82.71,47.89-160.77-115.2-238.85-36.07-17.23,17.46-14.47,37.91-23,49.54-2.05,2.79-11.55,8.24-14.95,11.43h0Z",
  strokes: ["M350.51,449.76c1.54-7.11,2.26-13.58,2.55-19.15-1.82-.29-3.32.14-5.02.73-6.03,2.1-28.09,19.61-36.32,24.68-59.72,36.76-130.28,63.2-187.36,101.15-52.02,34.59-67.56,82.37-82.86,140.51,15.97-18.63,35.65-33.48,56.18-46.85,67.97-44.26,150.82-76.57,215.73-125.54,15.06-11.36,21.02-36.73,29.72-52.8,2.67-6.08,5.43-13.71,7.39-22.74h-.01Z","M826.44,397.36c-12.26,8.15-21.57,17.13-34.4,24.96-35.23,21.5-66.1,38.48-109.88,59.93-5.33,2.61-13.97,6.81-26.46,13.11-11.64,5.88-31.49,15.79-42.28,22.02-60.87,35.14-72.98,59.13-92.04,125.58-1.32,4.59-6.01,7.41-3.32,13.14,1.13,2.42,9.28,11.9,12.31,9.89,10.08-30.75,41.99-48.68,68.21-64.53,59.15-35.76,132.86-66.35,184.88-111.87,18.82-16.47,44.42-63.27,45.38-88.18.09-2.27,1.05-4.98-2.4-4.04h0Z","M903.38,479.76c-12.25,10.19-20.54,23.7-32.1,34.69-2.73,2.59-8.16,3.32-5.01,6.49,7.02-3.92,13.74-8.83,21.19-11.93,3.79-1.58,8.65.74,11.8-4.53,1.22-.26,1.15,1.8.81,2.45-1.69,3.18-18.72,14.35-21.42,19.81l4.92,1.62-16.46,25.57,4.91-3.3c-.05.78.29,1.74,0,2.45-.47,1.17-13.73,17.28-15.57,19.06-11,10.62-33.59,23.42-47.2,31.93-60.03,37.55-136.05,72.53-190.27,116.38-15.75,12.73-27.3,39.31-10.73,56.03-9.21-3.11-15.78-14.56-18.94-23.08-6.32-17.03-3.13-30.54.81-47.78,1.89-7.52,4.84-17.01,9.59-27.51.91-2.02,8.13-18.7,20.63-33.98,17.52-21.41,39.75-35.08,67.58-50.92l215.43-113.46h.03Z","M808.09,242.64c20.68-21.28,35.13-33.61,7.46-57.72-5.02-4.38-27.73-16.91-28.59-18.37-.7-1.19-.52-2.41-.3-3.68,5.14-8.82,28.71-52.93,35.79-55.05,4.7-1.41,8.39-.26,12.59,1.57,20.22,8.79,44.89,32.25,43.57,56.11-1.41,25.59-43.44,73.36-70.52,77.16v-.02Z"],
};

// stroke bounding boxes (viewBox units) and the order they are written in:
// right to left, as Thaana is, the inner stroke first.
const DH_STROKE_BOX = [
  { x: 41.5, y: 430.52, w: 311.56, h: 267.16 },
  { x: 517.24, y: 397.18, w: 311.79, h: 269.09 },
  { x: 585.73, y: 479.75, w: 317.65, h: 296.73 },
  { x: 786.46, y: 107.19, w: 92.2, h: 135.47 },
];
const DH_STROKE_ORDER = [3, 1, 2, 0];

// a named mark is an image; an unnamed one (inside a labelled link) is decoration
function dhMarkA11y(title) {
  return title ? { role: "img", "aria-label": title } : { "aria-hidden": "true", focusable: "false" };
}

function Mark({ className = "", title = "Dheemi", twoColour = false, writable = false, idp = "mk" }) {
  // twoColour: Salt letters and Reed strokes, for Dusk backgrounds only.
  const lettersFill = twoColour ? "var(--salt)" : "currentColor";
  const strokesFill = twoColour ? "var(--reed)" : "currentColor";
  if (!writable) {
    return (
      <svg className={"mark " + className} viewBox={DH_MARK.vb} {...dhMarkA11y(title)}>
        <path d={DH_MARK.letters} fill={lettersFill} />
        {DH_MARK.strokes.map((d, i) => <path key={i} d={d} fill={strokesFill} />)}
      </svg>
    );
  }
  // writable: every part sits behind a mask whose rect the intro sweeps open.
  const L = 1002.66;
  return (
    <svg className={"mark " + className} viewBox={DH_MARK.vb} {...dhMarkA11y(title)} overflow="visible">
      <defs>
        <mask id={idp + "-l"} maskUnits="userSpaceOnUse" x="-40" y="-40" width="1090" height="860">
          <rect data-wipe="l" x={L + 20} y="-40" width="0" height="860" fill="#fff" />
        </mask>
        {DH_STROKE_BOX.map((b, i) => {
          const cx = b.x + b.w / 2, cy = b.y + b.h / 2;
          const half = Math.hypot(b.w, b.h) / 2 + 24;
          const ang = (Math.atan2(-b.h, b.w) * 180) / Math.PI;
          return (
            <mask key={i} id={idp + "-s" + i} maskUnits="userSpaceOnUse" x="-40" y="-40" width="1090" height="860">
              <g transform={`rotate(${ang.toFixed(2)} ${cx.toFixed(2)} ${cy.toFixed(2)})`}>
                <rect data-wipe={"s" + i} data-x0={(cx + half).toFixed(2)} data-x1={(cx - half).toFixed(2)} data-w1={(half * 2).toFixed(2)}
                  x={(cx + half).toFixed(2)} y={(cy - half).toFixed(2)} width="0" height={(half * 2).toFixed(2)} fill="#fff" />
              </g>
            </mask>
          );
        })}
      </defs>
      <path d={DH_MARK.letters} fill={lettersFill} mask={`url(#${idp}-l)`} />
      {DH_MARK.strokes.map((d, i) => <path key={i} d={d} fill={strokesFill} mask={`url(#${idp}-s${i})`} />)}
    </svg>
  );
}

function Wordmark({ className = "" }) {
  return <span className={"wordmark " + className}>dheemi <span>studio</span></span>;
}

// The horizontal lockup comes first. Mark, then the wordmark.
function Lockup({ href = "/", onClick }) {
  return (
    <a className="lockup" href={href} onClick={onClick} aria-label="Dheemi Studio, home">
      <Mark title="" />
      <Wordmark />
    </a>
  );
}

/* --------------------------------- images ---------------------------------- */
function Img({ src, alt = "", w, h, className = "", eager = false, style, vt }) {
  if (!src) return null;
  const st = Object.assign({}, style || {}, vt ? { viewTransitionName: vt } : null);
  return (
    <img
      src={src}
      alt={alt}
      width={w || undefined}
      height={h || undefined}
      loading={eager ? "eager" : "lazy"}
      decoding="async"
      fetchpriority={eager ? "high" : undefined}
      className={className}
      style={st}
    />
  );
}

// "Design, content and code" -> each word in a clipping box for the rise.
function Split({ text, as = "h1", className = "", id }) {
  const T = as;
  const words = String(text || "").split(/\s+/).filter(Boolean);
  return (
    <T className={className} id={id} data-split="" aria-label={text}>
      {words.map((w, i) => (
        <React.Fragment key={i}>
          <span className="w" aria-hidden="true"><span>{w}</span></span>
          {i < words.length - 1 ? " " : null}
        </React.Fragment>
      ))}
    </T>
  );
}

// Logos come in every shape. Sizing them all to one height makes square seals
// shout and long wordmarks whisper, so each is scaled by its aspect ratio
// (height falls as width grows) until they carry roughly the same weight.
function ClientLogo({ src, name }) {
  const [k, setK] = React.useState(0.8);
  const onLoad = (e) => {
    const im = e.currentTarget;
    const r = im.naturalWidth && im.naturalHeight ? im.naturalWidth / im.naturalHeight : 2;
    setK(Math.min(1, Math.max(0.42, Math.pow(r, -0.45))));
  };
  return <img src={src} alt={name} loading="lazy" decoding="async" onLoad={onLoad} style={{ height: "calc(var(--logo-h) * " + k.toFixed(3) + ")" }} />;
}

// "A website" -> "a website" inside a sentence, but "Coravida" and "MIRA" stay.
function dhSentence(str) {
  return String(str == null ? "" : str).replace(/^([A-Z])(?=[a-z])/, (m) => m.toLowerCase());
}

function StrokeList({ items, className = "" }) {
  const list = (Array.isArray(items) ? items : []).filter((x) => typeof x === "string" && x);
  if (!list.length) return null;
  return <ul className={"strokes " + className}>{list.map((t, i) => <li key={i}>{t}</li>)}</ul>;
}

/* ------------------------------ error boundary ------------------------------
   If saved content is malformed in a way the merge cannot catch, render the
   page again from the shipped content rather than leave it blank.           */
class DhBoundary extends React.Component {
  constructor(props) { super(props); this.state = { failed: false }; }
  static getDerivedStateFromError() { return { failed: true }; }
  componentDidCatch(err) { try { console.error("Rendering from shipped content:", err); } catch (e) {} }
  render() { return this.state.failed ? this.props.fallback : this.props.children; }
}

/* --------------------------------- scrolling -------------------------------- */
function dhNavH() {
  const v = getComputedStyle(document.documentElement).getPropertyValue("--nav-h");
  return parseInt(v, 10) || 72;
}

function scrollToId(id) {
  const el = document.getElementById(id);
  if (!el) return false;
  const off = id === "top" ? 0 : -(dhNavH() - 1);
  // the mobile sheet stops Lenis while open, and a stopped Lenis drops scrollTo
  if (window.__lenis) { window.__lenis.start(); window.__lenis.scrollTo(el, { offset: off, duration: 1.4 }); }
  else window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY + off, behavior: DH_REDUCED() ? "auto" : "smooth" });
  if (!el.hasAttribute("tabindex") && !/^(A|BUTTON|INPUT|SELECT|TEXTAREA)$/.test(el.tagName)) el.setAttribute("tabindex", "-1");
  try { el.focus({ preventScroll: true }); } catch (e) {}
  return true;
}

// On the home page an in-page link scrolls; elsewhere it navigates to /#id.
function dhOnHome() {
  const p = location.pathname.replace(/\/index\.html$/, "/");
  return p === "/" || p === "";
}
function dhNavClick(e, id) {
  if (!dhOnHome()) return;
  if (document.getElementById(id)) {
    e.preventDefault();
    scrollToId(id);
    try { history.replaceState(null, "", "#" + id); } catch (err) {}
  }
}

/* --------------------------------- header ----------------------------------- */
function Nav() {
  const c = window.useContent();
  const [hidden, setHidden] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  const home = dhOnHome();
  const links = (c.nav && c.nav.links) || [];

  useEffect(() => {
    let last = window.scrollY, ticking = false;
    const onScroll = () => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        const y = window.scrollY;
        setScrolled(y > 8);
        // hide while reading down, return the moment you scroll up
        if (y > 160 && y > last + 4) setHidden(true);
        else if (y < last - 4 || y <= 160) setHidden(false);
        last = y;
        ticking = false;
      });
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const menuBtn = useRef(null);
  const sheetRef = useRef(null);
  useEffect(() => {
    document.documentElement.classList.toggle("menu-open", open);
    if (window.__lenis) open ? window.__lenis.stop() : window.__lenis.start();
    const behind = [document.getElementById("main"), document.querySelector("footer.footer")].filter(Boolean);
    behind.forEach((el) => { el.inert = open; });
    if (open && sheetRef.current) {
      const first = sheetRef.current.querySelector("a");
      if (first) first.focus({ preventScroll: true });
    }
    const onKey = (e) => {
      if (e.key === "Escape" && open) { setOpen(false); if (menuBtn.current) menuBtn.current.focus(); }
    };
    window.addEventListener("keydown", onKey);
    return () => { window.removeEventListener("keydown", onKey); behind.forEach((el) => { el.inert = false; }); };
  }, [open]);

  const go = (e, id) => { setOpen(false); dhNavClick(e, id); };
  const href = (id) => (home ? "#" + id : "/#" + id);

  return (
    <React.Fragment>
      <a className="skip" href="#main">Skip to content</a>
      <header className={"nav" + (hidden && !open ? " is-hidden" : "") + (scrolled ? " is-scrolled" : "")}>
        <div className="wrap nav-in">
          <Lockup href="/" onClick={(e) => { if (home) { e.preventDefault(); setOpen(false); scrollToId("top"); } }} />
          <nav className="nav-links" aria-label="Main">
            {links.map((l) => (
              <a key={l.id} href={href(l.id)} onClick={(e) => go(e, l.id)}>{l.label}</a>
            ))}
            <a className="btn" href={href("contact")} onClick={(e) => go(e, "contact")}>{c.nav.cta}</a>
          </nav>
          <button ref={menuBtn} className="nav-menu-btn" aria-expanded={open} aria-controls="sheet" onClick={() => setOpen((v) => !v)}>
            {open ? "Close" : "Menu"}
          </button>
        </div>
      </header>
      <div id="sheet" ref={sheetRef} className={"sheet" + (open ? " is-open" : "")} aria-hidden={!open} inert={open ? undefined : ""}>
        <nav className="sheet-links" aria-label="Menu">
          {links.map((l) => (
            <a key={l.id} href={href(l.id)} onClick={(e) => go(e, l.id)} tabIndex={open ? 0 : -1}><span>{l.label}</span></a>
          ))}
        </nav>
        <div className="sheet-foot">
          <a className="t-label" href={"mailto:" + c.contact.email} tabIndex={open ? 0 : -1}>{c.contact.email}</a>
          <span className="t-cap">{c.footer.address}</span>
        </div>
      </div>
    </React.Fragment>
  );
}

/* --------------------------------- footer ----------------------------------- */
function Footer() {
  const c = window.useContent();
  const f = c.footer || {};
  const home = dhOnHome();
  const links = (c.nav && c.nav.links) || [];
  return (
    <footer className="footer inverse" aria-label="Footer">
      <div className="wrap">
        <div className="footer-top footer-cols">
          <div>
            <h3>Write to us</h3>
            <a className="footer-mail link" href={"mailto:" + c.contact.email}>{c.contact.email}</a>
          </div>
          <div>
            <h3>Studio</h3>
            <ul>
              {links.map((l) => (
                <li key={l.id}><a href={home ? "#" + l.id : "/#" + l.id} onClick={(e) => dhNavClick(e, l.id)}>{l.label}</a></li>
              ))}
            </ul>
          </div>
          <div>
            <h3>Elsewhere</h3>
            <ul>
              {(f.social || []).filter((s) => s && s.href).map((s) => (
                <li key={s.href}><a href={s.href} target="_blank" rel="noopener noreferrer">{s.label}</a></li>
              ))}
              <li className="muted">{f.address}</li>
            </ul>
          </div>
        </div>
        <div className="footer-word" aria-hidden="true"><Wordmark /></div>
        <div className="footer-base t-cap">
          <span>{f.copyright}</span>
          <a href="#top" onClick={(e) => { if (home) { e.preventDefault(); scrollToId("top"); } }}>Back to top</a>
        </div>
      </div>
    </footer>
  );
}

/* --------------------------------- intro ------------------------------------
   The mark writes itself, then settles into its place in the header. Once per
   tab session, never with reduced motion, and a click skips it.             */
function Intro({ onDone }) {
  const skip = (() => {
    try { return DH_REDUCED() || !window.gsap || sessionStorage.getItem("dh_intro") === "1"; } catch (e) { return true; }
  })();
  const [gone, setGone] = useState(skip);
  const ref = useRef(null);

  useLayoutEffect(() => {
    if (skip) { onDone && onDone(); return; }
    try { sessionStorage.setItem("dh_intro", "1"); } catch (e) {}
    const g = window.gsap;
    const root = ref.current;
    const svg = root.querySelector("svg");
    const bg = root.querySelector(".intro-bg");
    let finished = false;
    const finish = () => {
      if (finished) return;
      finished = true;
      document.documentElement.classList.remove("intro-on");
      setGone(true);
      onDone && onDone();
    };
    document.documentElement.classList.add("intro-on");
    const tl = g.timeline({ defaults: { ease: "power2.inOut" }, onComplete: finish });
    const lRect = svg.querySelector('[data-wipe="l"]');
    tl.to(lRect, { attr: { x: -20, width: 1042.66 }, duration: 1.05 }, 0.15);
    DH_STROKE_ORDER.forEach((i, k) => {
      const r = svg.querySelector('[data-wipe="s' + i + '"]');
      tl.to(r, { attr: { x: r.getAttribute("data-x1"), width: r.getAttribute("data-w1") }, duration: 0.34, ease: "power1.inOut" }, 0.95 + k * 0.13);
    });
    // hand over to the header mark
    tl.add(() => {
      const target = document.querySelector(".nav .lockup .mark");
      if (!target) return;
      const a = svg.getBoundingClientRect(), b = target.getBoundingClientRect();
      const s = b.height / a.height;
      g.to(svg, {
        x: b.left + b.width / 2 - (a.left + a.width / 2),
        y: b.top + b.height / 2 - (a.top + a.height / 2),
        scale: s, duration: 0.9, ease: "expo.inOut",
      });
    }, "+=0.28");
    tl.to(bg, { opacity: 0, duration: 0.7, ease: "power2.inOut" }, "<0.32");
    tl.to(svg, { opacity: 0, duration: 0.2 }, ">-0.05");
    const failsafe = setTimeout(finish, 5000);
    const skipNow = () => { tl.progress(1); finish(); };
    root.addEventListener("click", skipNow);
    return () => { clearTimeout(failsafe); root.removeEventListener("click", skipNow); tl.kill(); };
  }, []);

  if (gone) return null;
  return (
    <div className="intro" ref={ref} aria-hidden="true">
      <div className="intro-bg" />
      <Mark writable idp="intro" title="" />
    </div>
  );
}

/* --------------------------------- motion -----------------------------------
   GSAP + ScrollTrigger + Lenis and nothing else. One vocabulary, applied by
   element type:
     [data-split]   display headlines, words rise out of their own masks
     [data-r]       copy and captions settle 18px with a fade
     .js-zoom img   images ease from 1.12 to 1 as they cross the screen
     .reel-frame    the hero reel grows to full width as you scroll
     .inline-img    the statement opens a gap in the sentence for the work
   Everything is gated on prefers-reduced-motion: CSS cannot stop GSAP writes. */
const DH_DESKTOP = "(min-width: 900px) and (prefers-reduced-motion: no-preference)";
const DH_MOTION = "(prefers-reduced-motion: no-preference)";

function dhRevealSplit(el, delay) {
  const g = window.gsap;
  if (!g || el.__dhSplit) return;
  el.__dhSplit = true;
  g.set(el, { opacity: 1 });
  if (DH_REDUCED()) return;
  const spans = el.querySelectorAll(".w > span");
  g.fromTo(spans, { yPercent: 108 }, { yPercent: 0, duration: 1.15, ease: "expo.out", stagger: 0.045, delay: delay || 0, clearProps: "transform" });
}

function dhBindReveals(scope) {
  const g = window.gsap, ST = window.ScrollTrigger;
  if (!g || !ST) return;
  const root = scope || document;
  const reduce = DH_REDUCED();

  root.querySelectorAll("[data-split]").forEach((el) => {
    if (el.__dhSplit || el.__dhSplitBound) return;
    if (reduce) { g.set(el, { opacity: 1 }); el.__dhSplit = true; return; }
    el.__dhSplitBound = true;
    ST.create({ trigger: el, start: "top 88%", once: true, onEnter: () => dhRevealSplit(el, 0) });
  });

  const fresh = Array.from(root.querySelectorAll("[data-r]")).filter((el) => !el.__dhR);
  fresh.forEach((el) => { el.__dhR = true; });
  if (reduce) { g.set(fresh, { opacity: 1 }); return; }
  ST.batch(fresh, {
    start: "top 90%",
    once: true,
    onEnter: (batch) => g.fromTo(batch, { opacity: 0, y: 18 }, { opacity: 1, y: 0, duration: 0.9, ease: "power3.out", stagger: 0.08, overwrite: true, clearProps: "transform" }),
  });
}

function dhBindScrubs() {
  const g = window.gsap, ST = window.ScrollTrigger;
  if (!g || !ST || DH_REDUCED()) return;
  const mm = g.matchMedia();

  mm.add(DH_MOTION, () => {
    // images settle inside their frames
    document.querySelectorAll(".js-zoom").forEach((frame) => {
      if (frame.__dhZoom) return;
      const img = frame.querySelector("img");
      if (!img) return;
      frame.__dhZoom = true;
      g.fromTo(img, { scale: 1.12 }, {
        scale: 1, ease: "none",
        scrollTrigger: { trigger: frame, start: "top bottom", end: "center 45%", scrub: 0.6 },
      });
    });

    // the statement opens a gap in the sentence
    document.querySelectorAll(".inline-img").forEach((el) => {
      if (el.__dhGap) return;
      el.__dhGap = true;
      g.fromTo(el, { width: "0em", marginRight: "0em" }, {
        width: "2.1em", marginRight: "0.26em", ease: "none",
        scrollTrigger: { trigger: el.closest("section") || el, start: "top 75%", end: "top 25%", scrub: 0.8 },
      });
    });

    // the footer wordmark rises into the page
    document.querySelectorAll(".footer-word .wordmark").forEach((el) => {
      if (el.__dhWord) return;
      el.__dhWord = true;
      g.fromTo(el, { yPercent: 55 }, {
        yPercent: 0, ease: "none",
        scrollTrigger: { trigger: el.parentNode, start: "top bottom", end: "bottom bottom", scrub: 0.6 },
      });
    });
    return () => {
      document.querySelectorAll(".js-zoom, .inline-img, .footer-word .wordmark").forEach((el) => {
        el.__dhZoom = false; el.__dhGap = false; el.__dhWord = false;
      });
    };
  });

  mm.add(DH_DESKTOP, () => {
    // the hero reel grows from inset to full width as it rises
    const frame = document.querySelector(".reel-frame");
    if (frame && !frame.__dhReel) {
      frame.__dhReel = true;
      g.fromTo(frame, { scale: 0.86 }, {
        scale: 1, ease: "none",
        scrollTrigger: { trigger: frame, start: "top 92%", end: "top 18%", scrub: 0.7 },
      });
    }
    return () => { if (frame) frame.__dhReel = false; };
  });
}

function dhStartLenis() {
  const g = window.gsap, ST = window.ScrollTrigger, L = window.Lenis;
  if (window.__lenis || !L || DH_REDUCED()) return;
  try {
    const lenis = new L({ lerp: 0.1, smoothWheel: true, wheelMultiplier: 1, syncTouch: false });
    window.__lenis = lenis;
    if (document.documentElement.classList.contains("intro-on") || document.documentElement.classList.contains("menu-open")) lenis.stop();
    if (g && ST) {
      lenis.on("scroll", ST.update);
      g.ticker.add((t) => lenis.raf(t * 1000));
      g.ticker.lagSmoothing(0);
    } else {
      const raf = (t) => { lenis.raf(t); requestAnimationFrame(raf); };
      requestAnimationFrame(raf);
    }
  } catch (e) {}
}

function bootMotion() {
  if (window.__motionBooted) { dhRefreshMotion(); return; }
  window.__motionBooted = true;
  const g = window.gsap, ST = window.ScrollTrigger;
  if (!g || !ST) { document.documentElement.classList.remove("anim-ready"); return; }
  if (ST) g.registerPlugin(ST);
  dhStartLenis();

  // headlines already on screen play straight away, in reading order
  let d = 0;
  document.querySelectorAll("[data-split]").forEach((el) => {
    const r = el.getBoundingClientRect();
    if (r.top < window.innerHeight * 0.95 && r.bottom > 0) { dhRevealSplit(el, d); d += 0.12; }
  });

  dhBindReveals();
  dhBindScrubs();

  // a hash in the URL (arriving from another page) lands on its section
  if (location.hash && location.hash.length > 1) {
    const id = decodeURIComponent(location.hash.slice(1));
    setTimeout(() => scrollToId(id), 60);
  }

  if (document.fonts && document.fonts.ready) document.fonts.ready.then(() => ST && ST.refresh());
  if (document.readyState === "complete") ST.refresh();
  else window.addEventListener("load", () => ST.refresh());

  // React mounts new elements after boot (the sent letter, a project row that
  // arrives late). A [data-r] or [data-split] nobody binds stays pre-hidden by
  // html.anim-ready, so bind anything new as soon as it lands.
  if ("MutationObserver" in window) {
    let queued = false;
    new MutationObserver((list) => {
      if (queued) return;
      const added = list.some((m) => Array.from(m.addedNodes).some((n) => n.nodeType === 1 &&
        (n.matches("[data-r], [data-split]") || n.querySelector("[data-r], [data-split]"))));
      if (!added) return;
      queued = true;
      requestAnimationFrame(() => {
        queued = false;
        try {
          document.querySelectorAll("[data-split]").forEach((el) => {
            if (el.__dhSplit || el.__dhSplitBound) return;
            const r = el.getBoundingClientRect();
            if (r.top < window.innerHeight && r.bottom > 0) dhRevealSplit(el, 0);
          });
          dhBindReveals();
        } catch (e) {}
      });
    }).observe(document.getElementById("root") || document.body, { childList: true, subtree: true });
  }
}

// content can land after boot: bind whatever is new and re-measure
function dhRefreshMotion() {
  try { dhBindReveals(); dhBindScrubs(); window.ScrollTrigger && window.ScrollTrigger.refresh(); } catch (e) {}
}

// Failsafe: if motion has not booted a few seconds in, show everything. Armed
// at evaluation, because Babel compiles this file after the load event fired.
setTimeout(() => {
  if (!window.__motionBooted) document.documentElement.classList.remove("anim-ready");
}, 8000);

Object.assign(window, {
  ClientLogo, dhSentence, DhBoundary,
  Mark, Wordmark, Lockup, Img, Split, StrokeList, Nav, Footer, Intro,
  bootMotion, dhRefreshMotion, dhRevealSplit, scrollToId, dhNavClick, dhOnHome, DH_REDUCED,
});
