/* global React */

const { useEffect: useContactEffect, useRef: useContactRef, useState: useContactState } = React;

const RE_CONTACT = {
  calendly: "https://calendly.com/noah-rapidedge/30min",
};

// Email, phone and LinkedIn are not in the source as plain text. They are
// AES-GCM encrypted under a key that takes a few seconds of chained PBKDF2 to
// derive, so a scraper has to run real JS and burn real CPU per page. To change
// them, run scripts/seal-contact.mjs (see the usage note at its top).
/* SEALED:start (generated by scripts/seal-contact.mjs; do not edit by hand) */
const SEALED = {
  pass: "VVBAMpAG06GFCvsk+PrcGGBR",
  salt: "W+SEFbS0QLUmsvygpU0FOg==",
  iv: "DuM+1BK1xIsDN184",
  rounds: 20,
  iterations: 1000000,
  data: "4wZRZxygqhq0ZiLgLGQqwtPpahHu+22GS6knkdZ63XPZZQWP9NZ4RvB6I9TVmtMHE+LYUOWnvsmSmNJi1lKWi3gPaB10EkiSt6rIJRBpCy30aVUS8U2vGIV7JbvjJfIRTT74h1fNgoyULSQAKqlLQX1UY2Z+Sc60EsNVnanAvJ85isHwQBm6isZExCGAAKT5v46eimT8+CtLFGeCNBAqqhuM7B7fOCxP9huleFDmSEGFfPO6aB05+8yuWsZM4rFMdEU=",
};
/* SEALED:end */

async function unseal(sealed, onProgress) {
  const subtle = window.crypto && window.crypto.subtle;
  if (!sealed || !subtle) throw new Error("unavailable");
  const enc = new TextEncoder();
  const bin = (s) => Uint8Array.from(atob(s), (ch) => ch.charCodeAt(0));
  const salt = bin(sealed.salt);
  // Must match scripts/seal-contact.mjs.
  let bits = enc.encode(sealed.pass);
  for (let r = 0; r < sealed.rounds; r++) {
    const base = await subtle.importKey("raw", bits, "PBKDF2", false, ["deriveBits"]);
    bits = new Uint8Array(await subtle.deriveBits(
      { name: "PBKDF2", hash: "SHA-256", salt, iterations: sealed.iterations }, base, 256));
    onProgress((r + 1) / sealed.rounds);
  }
  const key = await subtle.importKey("raw", bits, "AES-GCM", false, ["decrypt"]);
  const plain = await subtle.decrypt({ name: "AES-GCM", iv: bin(sealed.iv) }, key, bin(sealed.data));
  return JSON.parse(new TextDecoder().decode(plain));
}

function useUnsealedContact() {
  const [state, setState] = useContactState({ info: null, progress: 0, failed: false });
  useContactEffect(() => {
    let cancelled = false;
    unseal(SEALED, (progress) => { if (!cancelled) setState((s) => ({ ...s, progress })); })
      .then((info) => { if (!cancelled) setState({ info, progress: 1, failed: false }); })
      .catch(() => { if (!cancelled) setState({ info: null, progress: 0, failed: true }); });
    return () => { cancelled = true; };
  }, []);
  return state;
}

function CalendlyEmbed({ url }) {
  const wrapRef = useContactRef(null);
  useContactEffect(() => {
    let cancelled = false;
    // widget.js loads async from the CDN; poll until it has attached itself.
    const tick = () => {
      if (cancelled || !wrapRef.current) return;
      if (window.Calendly && typeof window.Calendly.initInlineWidget === "function") {
        wrapRef.current.innerHTML = "";
        window.Calendly.initInlineWidget({ url, parentElement: wrapRef.current, prefill: {}, utm: {} });
      } else {
        setTimeout(tick, 150);
      }
    };
    tick();
    return () => { cancelled = true; };
  }, [url]);
  return (
    <div className="re-calendly-wrap">
      <span className="re-eyebrow">BOOK A TIME</span>
      <div className="re-calendly" ref={wrapRef} />
      <p className="re-calendly-note">
        Trouble loading the calendar? <a className="re-link" href={url} target="_blank" rel="noopener">Open it in a new tab.</a>
      </p>
    </div>
  );
}

function Contact() {
  const c = RE_CONTACT;
  const { info, progress, failed } = useUnsealedContact();
  const pending = failed ? "Use the calendar" : `Decrypting ${Math.round(progress * 100)}%`;
  const sealedRow = (icon, label, value, href, external) => info
    ? { icon, label, value, href, external }
    : { icon, label, value: pending, sealed: true };
  const rows = [
    sealedRow("ph-envelope-simple", "Email",    info && info.email,         info && `mailto:${info.email}`),
    sealedRow("ph-phone",           "Phone",    info && info.phone,         info && info.phoneHref),
    sealedRow("ph-linkedin-logo",   "LinkedIn", info && info.linkedinLabel, info && info.linkedin, true),
    { icon: "ph-map-pin",           label: "Shop", value: "Providence, RI" },
  ];
  return (
    <section className="re-close" id="contact">
      <div className="re-close-frame">
        <span className="re-eyebrow">FREE 30 MINUTE CALL</span>
        <h2 className="re-close-h">Tell us what you're building.</h2>
        <p className="re-close-body">
          You tell us about the project, and we tell you whether we can help, what a sprint would
          look like, and roughly what it would cost. If we're not the right fit, we'll point you to
          someone who is.
        </p>
        <div className="re-close-grid">
          <aside className="re-person">
            <img className="re-person-photo" src="assets/people/noah-page.jpg" alt="Noah Page" width="720" height="900" />
            <div>
              <h3 className="re-person-name">Noah Page</h3>
              <p className="re-person-role">Founder and principal engineer</p>
            </div>
            <ul className="re-person-list" aria-busy={!info && !failed}>
              {rows.map(r => {
                const inner = (
                  <>
                    <i className={"ph-thin " + r.icon} aria-hidden="true"></i>
                    <span className="re-person-label">{r.label}</span>
                    <span className={"re-person-value" + (r.sealed ? " is-sealed" : "")}>{r.value}</span>
                  </>
                );
                return (
                  <li key={r.label}>
                    {r.href
                      ? <a className="re-person-row" href={r.href} {...(r.external ? { target: "_blank", rel: "noopener" } : {})}>{inner}</a>
                      : <div className="re-person-row">{inner}</div>}
                  </li>
                );
              })}
            </ul>
          </aside>
          <CalendlyEmbed url={c.calendly} />
        </div>
      </div>
    </section>
  );
}

window.Contact = Contact;
