/* gate-client.jsx — the access gate, frontend half (v0.8.1)
   ============================================================
   Pairs with the Worker's guard (STRICT_GATE).

   Owns three things and nothing else:
     1. Loads the invisible Turnstile widget, mints a fresh token per call.
     2. Asks for the operator's email ONCE, at the moment of generation.
        Framed as signing the work, not paying a toll.
     3. Hands both to whoever is about to POST a paid route.

   Deliberately vanilla DOM, not React: it can be awaited from any call
   site without touching a component tree, state, or render path. Zero
   blast radius on the existing dashboard.

   Public API (one function):
     const gate = await window.rhbGate({ confirm: false });
     → { ok: true, email, token }  |  { ok: false, cancelled: true }

     confirm: false → ask for the email (first artifact — the poster)
     confirm: true  → show the stored address and let one tap through
                      (second artifact — the investment brief)

   The email persists per project in localStorage, so the brief is a
   confirm, never a re-type.
   ============================================================ */

const RHB_TURNSTILE_SITE_KEY = '0x4AAAAAAEsKs52LuXHDd3RA';
const RHB_EMAIL_KEY = 'rh.gate.email';

/* ───────────── email store (per browser, shared across projects) ───────────── */
function rhbStoredEmail() {
  try { return localStorage.getItem(RHB_EMAIL_KEY) || ''; } catch (e) { return ''; }
}
function rhbStoreEmail(v) {
  try { localStorage.setItem(RHB_EMAIL_KEY, String(v || '').trim().toLowerCase()); } catch (e) {}
}
/* v0.9.8 — the owner gives a little more at each board. Board 1: an email. Board 2:
   who they are. Board 3: how to reach them and where the project stands. Kept per
   browser like the email, so nothing is typed twice. */
const RHB_CONTACT_KEY = 'rh.gate.contact';
function rhbStoredContact() {
  try { return JSON.parse(localStorage.getItem(RHB_CONTACT_KEY) || '{}') || {}; } catch (e) { return {}; }
}
function rhbStoreContact(patch) {
  try { localStorage.setItem(RHB_CONTACT_KEY, JSON.stringify(Object.assign({}, rhbStoredContact(), patch))); } catch (e) {}
}
/* v0.9.9 — institutional wording (Jair): documents with names, labels only, no
   sentence explaining why a field is there. People know what a form is. */
const RHB_GATE_STEPS = {
  1: {
    eyebrow: '◆ PROJECT BRIEF · 1 OF 3', h: 'Issued to', go: 'COMPOSE ▸', fields: [],
    note: '◆ THE THREE DOCUMENTS ARE ISSUED AT NO CHARGE · THE CONSULTATION IS QUOTED IN THE THIRD',
  },
  2: {
    eyebrow: '◆ INVESTMENT BRIEF · 2 OF 3', h: 'Prepared for', go: 'VIEW ▸',
    fields: [
      { id: 'name', label: 'Name', type: 'text', required: true, auto: 'name' },
      { id: 'company', label: 'Company', type: 'text', required: true, auto: 'organization' },
      { id: 'role', label: 'Role', type: 'select', required: false,
        options: ['Owner', 'Operator', 'Investor', 'Developer', 'Architect or designer', 'Other'] },
    ],
  },
  3: {
    eyebrow: '◆ QUOTATION · 3 OF 3', h: 'Contact for the quotation', go: 'REQUEST ▸',
    fields: [
      { id: 'phone', label: 'Telephone', type: 'tel', required: true, auto: 'tel' },
      { id: 'status', label: 'Project status', type: 'select', required: true,
        options: ['Exploring an idea', 'Looking at a building', 'Own or lease the building', 'Financing in place', 'Ready to start'] },
      { id: 'opening', label: 'Target opening', type: 'select', required: false,
        options: ['Within 6 months', '6 to 12 months', '1 to 2 years', 'Not decided'] },
      { id: 'note', label: 'Note', type: 'text', required: false },
    ],
  },
};
function rhbValidEmail(e) {
  if (typeof e !== 'string') return false;
  const s = e.trim().toLowerCase();
  if (s.length > 254) return false;
  return /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(s);
}

/* ───────────── Turnstile ─────────────
   Invisible mode. Tokens are single-use and short-lived, so we mint a
   fresh one per generation rather than holding one. If Turnstile fails
   to load (blocked, offline), we resolve null — the Worker decides what
   that means. Never block the operator on our own script. */
let _tsReady = null;
function rhbTurnstileReady() {
  if (_tsReady) return _tsReady;
  _tsReady = new Promise((resolve) => {
    if (window.turnstile) return resolve(true);
    const s = document.createElement('script');
    s.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
    s.async = true; s.defer = true;
    s.onload = () => resolve(true);
    s.onerror = () => resolve(false);
    document.head.appendChild(s);
    setTimeout(() => resolve(Boolean(window.turnstile)), 6000);
  });
  return _tsReady;
}

async function rhbTurnstileToken() {
  const ok = await rhbTurnstileReady();
  if (!ok || !window.turnstile) return null;
  return new Promise((resolve) => {
    let done = false;
    const finish = (v) => { if (!done) { done = true; resolve(v); } };
    let host = document.getElementById('rhb-ts-host');
    if (!host) {
      host = document.createElement('div');
      host.id = 'rhb-ts-host';
      host.style.cssText = 'position:absolute;width:0;height:0;overflow:hidden;left:-9999px';
      document.body.appendChild(host);
    }
    host.innerHTML = '';
    try {
      window.turnstile.render(host, {
        sitekey: RHB_TURNSTILE_SITE_KEY,
        callback: (t) => finish(t),
        'error-callback': () => finish(null),
        'timeout-callback': () => finish(null),
      });
    } catch (e) { finish(null); }
    setTimeout(() => finish(null), 8000);   /* never hang the operator */
  });
}

/* ───────────── the modal ─────────────
   Bone chassis, mono eyebrow, serif ask, orange commit key. Mechanical
   press only — nothing performs. Survives prefers-reduced-motion by
   having no motion to survive. */
function rhbInjectGateStyles() {
  if (document.getElementById('rhb-gate-style')) return;
  const css = `
.rhb-gate-veil{position:fixed;inset:0;background:rgba(31,31,29,.34);backdrop-filter:blur(2px);
  z-index:9999;display:flex;align-items:center;justify-content:center;padding:20px}
.rhb-gate{background:#F2F0EB;border:1px solid rgba(31,31,29,.55);border-radius:3px;
  max-width:460px;width:100%;padding:26px 26px 22px;
  box-shadow:0 18px 50px rgba(31,31,29,.22), inset 0 1px 0 rgba(255,255,255,.6)}
.rhb-gate-eyebrow{font-family:'JetBrains Mono',monospace;font-size:9px;letter-spacing:.18em;
  color:rgba(31,31,29,.52);text-transform:uppercase;margin-bottom:12px}
.rhb-gate-h{font-family:'Source Serif 4',Georgia,serif;font-size:23px;font-weight:600;
  color:#1F1F1D;line-height:1.2;margin-bottom:8px}
.rhb-gate-p{font-family:'Source Serif 4',Georgia,serif;font-size:14.5px;line-height:1.55;
  color:rgba(31,31,29,.72);margin-bottom:18px}
.rhb-gate-field{width:100%;border:1px solid rgba(31,31,29,.55);border-radius:3px;background:#fff;
  padding:12px 13px;font-family:'JetBrains Mono',monospace;font-size:13px;color:#1F1F1D;outline:none}
.rhb-gate-field:focus{border-color:#E17863}
.rhb-gate-field.bad{border-color:#C0392B}
.rhb-gate-err{font-family:'JetBrains Mono',monospace;font-size:10px;letter-spacing:.06em;
  color:#C0392B;margin-top:7px;min-height:13px}
.rhb-gate-row{display:flex;gap:10px;margin-top:16px;align-items:center;justify-content:flex-end}
.rhb-gate-key{border:1px solid rgba(31,31,29,.55);border-radius:3px;cursor:pointer;
  font-family:'JetBrains Mono',monospace;font-size:10px;letter-spacing:.14em;padding:11px 18px;
  background:#E4E1D9;color:#1F1F1D;box-shadow:0 2px 0 rgba(31,31,29,.25),inset 0 1px 0 rgba(255,255,255,.5);
  transition:transform .09s,box-shadow .09s}
.rhb-gate-key:active{transform:translateY(2px);box-shadow:0 0 0,inset 0 1px 2px rgba(31,31,29,.2)}
.rhb-gate-key.go{background:#E17863;border-color:#E17863;color:#fff}
.rhb-gate-key[disabled]{opacity:.45;cursor:default}
.rhb-gate-lab{font-family:'JetBrains Mono',monospace;font-size:9px;letter-spacing:.12em;
  color:rgba(31,31,29,.6);text-transform:uppercase;margin:12px 0 5px}
.rhb-gate-note{font-family:'JetBrains Mono',monospace;font-size:9px;letter-spacing:.1em;
  color:rgba(31,31,29,.52);margin-top:14px;line-height:1.6}
@media (prefers-reduced-motion:reduce){.rhb-gate-key{transition:none}}`;
  const el = document.createElement('style');
  el.id = 'rhb-gate-style';
  el.textContent = css;
  document.head.appendChild(el);
}

function rhbAskEmail(opts) {
  const confirmMode = Boolean(opts && opts.confirm);
  const stored = rhbStoredEmail();
  rhbInjectGateStyles();
  const step = opts && RHB_GATE_STEPS[opts.step] ? RHB_GATE_STEPS[opts.step] : null;
  const gateNote = (step && step.note) || '◆ DETAILS ARE SHARED WITH ROOTHERHUB TO PREPARE THE QUOTATION · NOT SOLD, NOT LISTED';
  const had = rhbStoredContact();
  const esc = (v) => String(v == null ? '' : v).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
  const extra = step ? step.fields.map((f) => `
        <div class="rhb-gate-lab">${f.label}</div>
        ${f.type === 'select'
          ? `<select class="rhb-gate-field" id="rhb-gate-f-${f.id}"><option value="">Choose</option>${f.options.map((o) => `<option${had[f.id] === o ? ' selected' : ''}>${o}</option>`).join('')}</select>`
          : `<input class="rhb-gate-field" id="rhb-gate-f-${f.id}" type="${f.type}" autocomplete="${f.auto || 'off'}" value="${esc(had[f.id])}" />`}`).join('') : '';

  return new Promise((resolve) => {
    const veil = document.createElement('div');
    veil.className = 'rhb-gate-veil';
    veil.innerHTML = `
      <div class="rhb-gate" role="dialog" aria-modal="true" aria-label="Sign the work">
        <div class="rhb-gate-eyebrow">${step ? step.eyebrow : '◆ ROOTHERHUB'}</div>
        <div class="rhb-gate-h" style="margin-bottom:14px">${step ? step.h : 'Issued to'}</div>
        <div class="rhb-gate-lab">Email</div>
        <input class="rhb-gate-field" id="rhb-gate-email" type="email" autocomplete="email"
               placeholder="you@company.com" value="${stored.replace(/"/g, '&quot;')}" />
        ${extra}
        <div class="rhb-gate-err" id="rhb-gate-err"></div>
        <div class="rhb-gate-row">
          <button class="rhb-gate-key" id="rhb-gate-cancel">CANCEL</button>
          <button class="rhb-gate-key go" id="rhb-gate-go">${step ? step.go : (confirmMode ? 'CONFIRM ▸' : 'COMPOSE ▸')}</button>
        </div>
        <div class="rhb-gate-note">${gateNote}${step && step.note ? '<br>◆ DETAILS ARE SHARED WITH ROOTHERHUB TO PREPARE THE QUOTATION · NOT SOLD, NOT LISTED' : ''}</div>
      </div>`;
    document.body.appendChild(veil);

    const input = veil.querySelector('#rhb-gate-email');
    const err = veil.querySelector('#rhb-gate-err');
    const go = veil.querySelector('#rhb-gate-go');
    const close = (val) => { veil.remove(); document.removeEventListener('keydown', onKey); resolve(val); };
    const submit = () => {
      const v = (input.value || '').trim().toLowerCase();
      if (!rhbValidEmail(v)) {
        input.classList.add('bad');
        err.textContent = 'EMAIL ADDRESS NOT VALID.';
        input.focus();
        return;
      }
      if (step) {
        const got = {};
        for (const f of step.fields) {
          const el = veil.querySelector('#rhb-gate-f-' + f.id);
          const val = (el && el.value ? String(el.value) : '').trim().slice(0, 160);
          if (f.required && !val) {
            if (el) { el.classList.add('bad'); el.focus(); }
            err.textContent = 'REQUIRED: ' + f.label.toUpperCase() + '.';
            return;
          }
          if (f.id === 'phone' && val.replace(/[^0-9]/g, '').length < 7) {
            el.classList.add('bad'); el.focus();
            err.textContent = 'TELEPHONE NUMBER TOO SHORT.';
            return;
          }
          got[f.id] = val;
        }
        rhbStoreContact(got);
      }
      rhbStoreEmail(v);
      close(v);
    };
    const onKey = (e) => {
      if (e.key === 'Escape') close(null);
      if (e.key === 'Enter' && document.activeElement && document.activeElement.classList.contains('rhb-gate-field') && document.activeElement.tagName !== 'SELECT') submit();
    };

    go.addEventListener('click', submit);
    veil.querySelector('#rhb-gate-cancel').addEventListener('click', () => close(null));
    veil.addEventListener('mousedown', (e) => { if (e.target === veil) close(null); });
    document.addEventListener('keydown', onKey);
    setTimeout(() => { input.focus(); if (confirmMode) input.select(); }, 40);
  });
}

/* ───────────── the one public call ─────────────
   Await this immediately before any paid POST. Returns the email and a
   fresh Turnstile token, or { ok:false, cancelled:true } if the operator
   backed out — in which case do NOT fire the request. */
async function rhbGate(opts) {
  const options = opts || {};
  const stored = rhbStoredEmail();

  /* Confirm mode with a stored address still shows the modal — one tap,
     pre-filled. The operator always sees where their work is going. */
  /* The first document asks under step 1 unless a later step is named. */
  const email = await rhbAskEmail({ confirm: options.confirm && rhbValidEmail(stored), step: options.step || (options.confirm ? undefined : 1) });
  if (!email) return { ok: false, cancelled: true };

  const token = await rhbTurnstileToken();
  return { ok: true, email, token, contact: rhbStoredContact() };
}

/* Background routes (site intelligence, the brain chat, the sales email) need a
   Turnstile token but never a popup. Expose the silent minter so they can pass
   the bouncer without asking the operator anything. */
Object.assign(window, { rhbGate, rhbStoredContact, rhbStoredEmail, rhbValidEmail, rhbTurnstileToken, RHB_TURNSTILE_SITE_KEY });
