// Home page sections. Salt by default; Services and Contact are the inverse
// (Dusk) pages, never two in a row.

function dhProjectHref(p) { return "/work/" + encodeURIComponent(p.slug); }

function dhCardStash(p) {
  return { slug: p.slug, title: p.title, type: p.type, year: p.year, sector: p.sector, summary: p.summary, tagline: p.tagline, overview: p.overview, cover_url: p.cover_url, cover_w: p.cover_w, cover_h: p.cover_h, logo_url: p.logo_url, deliverables: p.deliverables, link_url: p.link_url };
}

/* ---------------------------------- hero ----------------------------------- */
function Hero() {
  const h = window.useContent().hero;
  return (
    <section className="hero wrap" id="top" aria-labelledby="hero-h">
      <Split as="h1" id="hero-h" className="t-display" text={h.headline} />
      <div className="split hero-row">
        <div className="split-body">
          <p className="t-lead" data-r="">{h.lead}</p>
          <div className="hero-actions" data-r="">
            <a className="btn" href="#contact" onClick={(e) => dhNavClick(e, "contact")}>
              {h.ctaPrimary}<Icon name="arrowR" className="arr" />
            </a>
            <a className="btn btn-ghost" href="#work" onClick={(e) => dhNavClick(e, "work")}>{h.ctaSecondary}</a>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------------------------- reel ------------------------------------
   One frame of real client work under the headline. It cross-fades through a
   few projects and grows to full width as you scroll.                       */
function Reel() {
  const c = window.useContent();
  const all = c.projects.filter((p) => p.cover_url);
  const wanted = (c.hero.reel || []).map((s) => all.find((p) => p.slug === s)).filter(Boolean);
  const list = (wanted.length ? wanted : all).slice(0, 6);
  const [i, setI] = React.useState(0);
  const [paused, setPaused] = React.useState(false);
  const [held, setHeld] = React.useState(false);
  const auto = list.length > 1 && !DH_REDUCED();
  const ref = React.useRef(null);
  const visible = React.useRef(true);

  React.useEffect(() => {
    if (!ref.current || !("IntersectionObserver" in window)) return;
    const io = new IntersectionObserver(([e]) => { visible.current = e.isIntersecting; }, { threshold: 0.2 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);

  React.useEffect(() => {
    if (!auto || paused || held) return;
    const t = setInterval(() => {
      if (visible.current && !document.hidden) setI((n) => (n + 1) % list.length);
    }, 4200);
    return () => clearInterval(t);
  }, [auto, paused, held]);

  if (!list.length) return null;
  const cur = list[i % list.length];
  return (
    <section className="reel wrap" aria-label="Recent work"
      onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}
      onFocus={() => setPaused(true)} onBlur={(e) => { if (!e.currentTarget.contains(e.relatedTarget)) setPaused(false); }}>
      <a
        ref={ref}
        className="reel-frame sq"
        href={dhProjectHref(cur)}
        onMouseEnter={() => window.dhPrefetchProject(cur.slug, dhCardStash(cur))}
        onClick={() => window.dhPrefetchProject(cur.slug, dhCardStash(cur))}
        aria-label={cur.title + ", " + cur.type}
      >
        {list.map((p, k) => (
          <Img key={p.slug} src={p.cover_url} w={p.cover_w} h={p.cover_h} alt="" eager={k === 0} className={k === i ? "is-on" : ""} />
        ))}
      </a>
      <div className="reel-cap">
        <div className="reel-titles">
          {list.map((p, k) => (
            <div key={p.slug} className={"reel-title" + (k === i ? " is-on" : "")} aria-hidden={k === i ? undefined : "true"}>
              <a className="t-label" href={dhProjectHref(p)} tabIndex={k === i ? undefined : -1}>{p.title}</a>
              <span className="t-cap">{p.type}</span>
            </div>
          ))}
        </div>
        {list.length > 1 ? (
          <div className="reel-ctrl">
            {auto ? (
              <button className="reel-play" onClick={() => setHeld((v) => !v)} aria-label={held ? "Play the reel" : "Pause the reel"}>
                {held ? "Play" : "Pause"}
              </button>
            ) : null}
            <div className="reel-dots" role="group" aria-label="Choose a project">
              {list.map((p, k) => (
                <button key={p.slug} className={k === i ? "is-on" : ""} aria-label={p.title} aria-pressed={k === i} onClick={() => { setI(k); setHeld(true); }} />
              ))}
            </div>
          </div>
        ) : null}
      </div>
    </section>
  );
}

/* ---------------------------------- work ------------------------------------
   The work is the hero. A frame and a caption, nothing more. Rows of one wide
   piece, then two side by side, at equal heights.                           */
function WorkCard({ p, wide, i }) {
  const warm = () => window.dhPrefetchProject(p.slug, dhCardStash(p));
  return (
    <a
      className={"card" + (wide ? " is-wide" : "")}
      href={dhProjectHref(p)}
      onMouseEnter={warm}
      onFocus={warm}
      onClick={warm}
      data-r=""
    >
      <div className="card-media sq-img js-zoom">
        <Img src={p.cover_url} w={p.cover_w} h={p.cover_h} alt="" />
      </div>
      <div className="card-cap">
        <h3 className="t-heading">{p.title}<Icon name="arrowUR" className="arr" /></h3>
        <div className="card-meta">
          <span className="t-label">{p.type}</span>
          <span className="t-cap">{[p.sector, p.year].filter(Boolean).join(" · ")}</span>
        </div>
      </div>
    </a>
  );
}

function Work() {
  const c = window.useContent();
  const w = c.work;
  const list = c.projects.filter((p) => p.cover_url);
  // wide, half, half, wide, half, half ... and a lone half at the end goes wide
  const wideAt = (k) => {
    const m = k % 3;
    if (m === 0) return true;
    if (m === 1 && k === list.length - 1) return true;
    return false;
  };
  return (
    <section className="section wrap" id="work" aria-labelledby="work-h">
      <div className="split work-head">
        <div className="split-head"><Split as="h2" id="work-h" className="t-display" text={w.heading} /></div>
        <div className="split-body"><p className="t-lead" data-r="">{w.lead}</p></div>
      </div>
      <div className="work-grid">
        {list.map((p, k) => <WorkCard key={p.slug} p={p} wide={wideAt(k)} i={k} />)}
      </div>
    </section>
  );
}

/* ---------------------------------- statement ------------------------------- */
function Statement() {
  const c = window.useContent();
  const s = c.statement;
  const imgs = c.projects.filter((p) => p.cover_url).slice(0, 6);
  const [i, setI] = React.useState(0);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (imgs.length < 2 || DH_REDUCED() || !ref.current || !("IntersectionObserver" in window)) return;
    let t = null;
    const io = new IntersectionObserver(([e]) => {
      clearInterval(t);
      if (!e.isIntersecting) return;
      let n = 0;
      t = setInterval(() => {
        setI((x) => (x + 1) % imgs.length);
        if (++n >= 3) clearInterval(t);
      }, 1500);
    }, { threshold: 0.3 });
    io.observe(ref.current);
    return () => { io.disconnect(); clearInterval(t); };
  }, [imgs.length]);
  return (
    <section className="statement wrap" ref={ref} aria-label={s.before + " " + s.after}>
      <p className="t-display" data-r="">
        {s.before}{" "}
        <span className="inline-img" aria-hidden="true">
          {imgs.map((p, k) => <img key={p.slug} src={p.cover_url} alt="" loading="lazy" decoding="async" className={k === i ? "is-on" : ""} />)}
        </span>
        {s.after}
      </p>
      {s.sub ? <p className="t-lead statement-sub" data-r="">{s.sub}</p> : null}
    </section>
  );
}

/* ---------------------------------- services -------------------------------- */
// Hold an element at its screen position while content above it changes height.
function dhKeepInPlace(el, ms) {
  if (!el) return;
  const top0 = el.getBoundingClientRect().top;
  const start = performance.now();
  const tick = (now) => {
    const d = el.getBoundingClientRect().top - top0;
    if (Math.abs(d) > 0.5) {
      if (window.__lenis) window.__lenis.scrollTo(window.scrollY + d, { immediate: true, force: true });
      else window.scrollTo(0, window.scrollY + d);
    }
    if (now - start < ms) requestAnimationFrame(tick);
  };
  requestAnimationFrame(tick);
}

function Services() {
  const c = window.useContent();
  const s = c.services;
  const [open, setOpen] = React.useState(0);
  const items = (s.items || []).filter((x) => x && x.title);
  const byslug = (slug) => c.projects.find((p) => p.slug === slug && p.cover_url);
  React.useEffect(() => {
    // the panel height changes the page length; let ScrollTrigger re-measure
    const t = setTimeout(() => { try { window.ScrollTrigger && window.ScrollTrigger.refresh(); } catch (e) {} }, 650);
    return () => clearTimeout(t);
  }, [open]);
  return (
    <section className="services inverse section" id="services" aria-labelledby="svc-h">
      <div className="wrap split">
        <div className="split-head">
          <Split as="h2" id="svc-h" className="t-display" text={s.heading} />
          {s.lead ? <p className="t-cap" data-r="" style={{ marginTop: 20, maxWidth: "26ch" }}>{s.lead}</p> : null}
        </div>
        <div className="split-body">
          <div className="svc-list">
            {items.map((it, k) => {
              const isOpen = open === k;
              const p = byslug(it.project);
              const pid = "svc-p-" + k;
              return (
                <div className={"svc" + (isOpen ? " is-open" : "")} key={k} data-r="">
                  <button className="svc-btn" aria-expanded={isOpen} aria-controls={pid} onClick={(e) => { dhKeepInPlace(e.currentTarget, 750); setOpen(isOpen ? -1 : k); }}>
                    <span className="svc-n">{String(k + 1).padStart(2, "0")}</span>
                    <span className="t-heading">{it.title}</span>
                    <span className="svc-plus" aria-hidden="true" />
                  </button>
                  <div className="svc-panel" id={pid} role="region" aria-label={it.title}>
                    <div>
                      <div className="svc-inner">
                        <p className="t-serif">{it.body}</p>
                        <StrokeList items={it.includes} />
                        {p ? (
                          <a className="svc-shot" href={dhProjectHref(p)}
                            onMouseEnter={() => window.dhPrefetchProject(p.slug, dhCardStash(p))}
                            >
                            <div className="frame sq-sm"><Img src={p.cover_url} w={p.cover_w} h={p.cover_h} alt="" /></div>
                            <span className="link t-label">{p.title}<Icon name="arrowUR" className="arr" /></span>
                          </a>
                        ) : null}
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------------------------- clients --------------------------------- */
function Clients() {
  const c = window.useContent();
  const k = c.clients;
  const seen = new Set();
  const logos = [];
  c.projects.forEach((p) => {
    if (seen.has(p.title)) return;
    seen.add(p.title);
    logos.push({ name: p.title, logo: p.logo_url, href: dhProjectHref(p) });
  });
  window.normClients(k.items).forEach((x) => { if (!seen.has(x.name)) { seen.add(x.name); logos.push(x); } });
  if (!logos.length) return null;
  return (
    <section className="section-tight wrap" id="clients" aria-labelledby="cl-h">
      <div className="split">
        <div className="split-head">
          <h2 className="t-heading" id="cl-h" data-r="">{k.heading}</h2>
          {k.lead ? <p className="t-cap" data-r="" style={{ marginTop: 14, maxWidth: "30ch" }}>{k.lead}</p> : null}
        </div>
        <div className="split-body">
          <ul className="logos tile-white sq" data-r="" style={{ listStyle: "none" }}>
            {logos.map((l) => {
              const inner = l.logo ? <ClientLogo src={l.logo} name={l.name} /> : <span className="t-label">{l.name}</span>;
              return <li className="logo" key={l.name}>{l.href ? <a href={l.href} aria-label={l.name}>{inner}</a> : inner}</li>;
            })}
          </ul>
        </div>
      </div>
    </section>
  );
}

/* ---------------------------------- studio ---------------------------------- */
function Studio() {
  const s = window.useContent().studio;
  const team = window.normTeam(s.team);
  return (
    <section className="section wrap" id="studio" aria-labelledby="st-h">
      <div className="split">
        <div className="split-head"><Split as="h2" id="st-h" className="t-display" text={s.heading} /></div>
        <div className="split-body studio-body">
          <p className="t-lead" data-r="">{s.body}</p>
          {(s.points || []).length ? (
            <div className="studio-points">
              {s.points.slice(0, 4).map((p, k) => (
                <div className="studio-point" key={k} data-r="">
                  <h3 className="t-label">{p.title}</h3>
                  <p className="t-serif">{p.body}</p>
                </div>
              ))}
            </div>
          ) : null}
          {team.length ? (
            <div className="team">
              {team.map((m) => (
                <figure key={m.name} data-r="">
                  <div className="ph sq-sm">{m.photo ? <Img src={m.photo} alt={m.name} /> : null}</div>
                  <figcaption><span className="t-label">{m.name}</span><br /><span className="t-cap">{m.role}</span></figcaption>
                </figure>
              ))}
            </div>
          ) : null}
        </div>
      </div>
    </section>
  );
}

/* ---------------------------------- contact ---------------------------------
   The form is a letter. You fill in the blanks of a few plain sentences, and
   that letter is what we receive.                                           */
function dhLetterText(f) {
  const parts = [];
  parts.push(`Hi, I'm ${f.name || "..."}${f.company ? " from " + f.company : ""}.`);
  if (f.services.length) parts.push(`We'd like help with ${f.services.map(dhSentence).join(", ")}.`);
  if (f.timing) parts.push(`Ideally we start ${dhSentence(f.timing)}.`);
  if (f.about) parts.push(`A little about it: ${f.about}`);
  parts.push(`You can reply to me at ${f.reply || "..."}.`);
  return parts.join(" ");
}

function LetterInput({ value, onChange, placeholder, label, type = "text", bad, name, autoComplete, inputMode, describedBy }) {
  const size = Math.max(String(value || "").length, placeholder.length) + 1;
  return (
    <span className={"field" + (bad ? " is-bad" : "")}>
      <input
        type={type}
        name={name}
        value={value}
        placeholder={placeholder}
        aria-label={label}
        aria-invalid={bad ? "true" : undefined}
        aria-describedby={bad && describedBy ? describedBy : undefined}
        autoComplete={autoComplete}
        inputMode={inputMode}
        size={size}
        onChange={(e) => onChange(e.target.value)}
      />
    </span>
  );
}

function Contact() {
  const c = window.useContent().contact;
  const [f, setF] = React.useState({ name: "", company: "", services: [], timing: "", about: "", reply: "", website: "" });
  const [bad, setBad] = React.useState({});
  const [state, setState] = React.useState("idle"); // idle | sending | sent | error
  const t0 = React.useRef(Date.now());
  const sentRef = React.useRef(null);
  React.useEffect(() => { if (state === "sent" && sentRef.current) sentRef.current.focus({ preventScroll: true }); }, [state]);
  const set = (k) => (v) => { setF((o) => Object.assign({}, o, { [k]: v })); setBad((b) => Object.assign({}, b, { [k]: false })); };
  const toggle = (s) => setF((o) => Object.assign({}, o, { services: o.services.includes(s) ? o.services.filter((x) => x !== s) : o.services.concat(s) }));

  // a radio group moves with the arrow keys and is one tab stop (roving tabindex)
  const timingKeys = (e) => {
    const opts = c.timing || [];
    const step = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[e.key];
    if (!step || !opts.length) return;
    e.preventDefault();
    const at = opts.indexOf(f.timing);
    const k = at < 0 ? (step > 0 ? 0 : opts.length - 1) : (at + step + opts.length) % opts.length;
    set("timing")(opts[k]);
    const btns = e.currentTarget.querySelectorAll('[role="radio"]');
    if (btns[k]) btns[k].focus();
  };

  const validReply = (v) => {
    const t = v.trim();
    return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(t) || (/^[+()\d\s-]+$/.test(t) && t.replace(/\D/g, "").length >= 7);
  };

  const submit = async (e) => {
    e.preventDefault();
    const nb = { name: f.name.trim().length < 2, reply: !validReply(f.reply) };
    setBad(nb);
    if (nb.name || nb.reply) {
      const first = document.querySelector('.letter input[name="' + (nb.name ? "name" : "reply") + '"]');
      if (first) first.focus();
      return;
    }
    setState("sending");
    try {
      const r = await fetch("/api/enquiry", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(Object.assign({}, f, { letter: dhLetterText(f), elapsed: Date.now() - t0.current })),
      });
      if (r.status === 400) {
        const j = await r.json().catch(() => ({}));
        if (j && (j.error === "name" || j.error === "reply")) {
          setBad({ [j.error]: true });
          setState("idle");
          const el = document.querySelector('.letter input[name="' + j.error + '"]');
          if (el) el.focus();
          return;
        }
      }
      if (!r.ok) throw new Error("status " + r.status);
      setState("sent");
    } catch (err) {
      setState("error");
    }
  };

  const mailto = "mailto:" + c.email + "?subject=" + encodeURIComponent("Project enquiry" + (f.name ? " from " + f.name : "")) + "&body=" + encodeURIComponent(dhLetterText(f));

  return (
    <section className="contact inverse" id="contact" aria-labelledby="ct-h">
      <div className="wrap split">
        <div className="split-head">
          <Split as="h2" id="ct-h" className="t-display" text={c.heading} />
          <p className="t-cap" data-r="">{c.lead}</p>
        </div>
        <div className="split-body" aria-live="polite">
          {state === "sent" ? (
            <div data-r="" ref={sentRef} tabIndex={-1}>
              <p className="sent">Thank you{f.name ? ", " + f.name.trim().split(/\s+/)[0] : ""}. {String(c.success || "").replace(/^thank you[.,!]?\s*/i, "")}</p>
              <p className="t-cap">We will write back to {f.reply.trim()}.</p>
            </div>
          ) : (
            <form className="letter" onSubmit={submit} noValidate data-r="">
              <p>
                Hi, I'm <LetterInput value={f.name} onChange={set("name")} placeholder="your name" label="Your name" name="name" autoComplete="name" bad={bad.name} describedBy="letter-err" />{" "}
                from <LetterInput value={f.company} onChange={set("company")} placeholder="company or project" label="Company or project" name="organization" autoComplete="organization" />.
              </p>
              <p>
                We'd like help with{" "}
                <span className="chips" role="group" aria-label="What you need">
                  {(c.services || []).map((s) => (
                    <button type="button" key={s} className="chip" aria-pressed={f.services.includes(s)} onClick={() => toggle(s)}>{dhSentence(s)}</button>
                  ))}
                </span>
              </p>
              <p>
                Ideally we start{" "}
                <span className="chips" role="radiogroup" aria-label="When you would like to start" onKeyDown={timingKeys}>
                  {(c.timing || []).map((s, k) => (
                    <button type="button" key={s} className="chip" role="radio" aria-checked={f.timing === s}
                      tabIndex={f.timing === s || (!f.timing && k === 0) ? 0 : -1}
                      onClick={() => set("timing")(f.timing === s ? "" : s)}>{dhSentence(s)}</button>
                  ))}
                </span>
              </p>
              <p>
                A little about it:
                <span className="field about">
                  <textarea
                    rows="2"
                    value={f.about}
                    placeholder="a sentence or two is plenty"
                    aria-label="A little about it"
                    maxLength={2000}
                    onChange={(e) => { set("about")(e.target.value); e.target.style.height = "auto"; e.target.style.height = e.target.scrollHeight + "px"; }}
                  />
                </span>
              </p>
              <p>
                You can reply to me at <LetterInput value={f.reply} onChange={set("reply")} placeholder="email or phone" label="Email or phone" name="reply" autoComplete="email" bad={bad.reply} describedBy="letter-err" />.
              </p>
              <label className="hp" aria-hidden="true">Website<input tabIndex={-1} autoComplete="off" value={f.website} onChange={(e) => set("website")(e.target.value)} /></label>
              <div className="letter-foot">
                <button className="btn btn-reed" type="submit" disabled={state === "sending"}>
                  {state === "sending" ? "Sending" : "Send the letter"}<Icon name="arrowR" className="arr" />
                </button>
                {state === "error" ? (
                  <p className="t-cap err" role="alert">That did not send. <a className="link" href={mailto}>Email it to {c.email} instead</a>.</p>
                ) : (bad.name || bad.reply) ? (
                  <p className="t-cap err" role="alert" id="letter-err">
                    {bad.name && bad.reply ? "Add your name and an email or phone number" : bad.name ? "Add your name" : "Add an email or phone number"} so we can reply.
                  </p>
                ) : (
                  <p className="t-cap">Or write to <a className="link" href={"mailto:" + c.email}>{c.email}</a></p>
                )}
              </div>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, Reel, Work, WorkCard, Statement, Services, Clients, Studio, Contact, dhProjectHref, dhCardStash });
