/* fold-primitives.jsx — v0.3 fold-specific primitives
   ============================================================
   TaxonomyTree (parent-child + standalone) · BracketGrid
   AddressTypeahead · LineMap · SiteTypePicker · LandStatusPicker
   AreaInput · CapacityInput · WhoPicker · HowModelPicker
   StoryFreeField · TwoGrid · ReferenceTag · RunningSummary
*/

/* ───────── REFERENCE TAG ─────────
   60-char optional handle at top of configurator (per A.5). */
/* ============================================================
   TYPOLOGY RE-SKIN — INSTRUMENT FACE  (v0.8 instrument grammar)
   Drop-in replacement for ReferenceTag + TaxonomyTree + BracketGrid
   in fold-primitives.jsx.

   PRESERVED VERBATIM (the product richness — untouched):
   - props: (value, onChange) / (typologyId, value, onChange, label)
   - state: open Set, showBlock
   - pick() logic: re-pick promotes secondary, 3rd pick → 3600ms block
   - value shape: {primary, secondary, primaryBracket, secondaryBracket, renovation}
   - data globals: TAXONOMY, BRACKET_RANGES, ALL_BRACKETS, leafById
   - ReferenceTag moderation hint (useModerationHint)
   CHANGED: JSX markup + class names only (the instrument face).
   ============================================================ */

/* periodic two-letter symbols — APPROVED set, collision-free (42 total) */
const TYPE_SYM = {
  /* parents */
  hotels:'Ho', restaurants:'Re', bars:'Ba', fitness:'Fi', wellness:'We', renovations:'Rn',
  /* hotels */
  hotel_boutique:'Bt', hotel_signature:'Sg', hotel_franchise:'Fh', hotel_guesthouse:'Gh', hotel_hostal:'Hl', hotel_airbnb:'Ab',
  /* restaurants */
  rest_seafood:'Sf', rest_fine:'Fn', rest_design:'Dr', rest_origen:'Do', rest_market:'Mk', rest_counter:'Qs', rest_franchise:'Rf', rest_foodtruck:'Ft',
  /* bars */
  bar_beergarden:'Bg', bar_cocktail:'Ck', bar_wine:'Wn', bar_speakeasy:'Sk', bar_karaoke:'Kk', bar_experience:'Xb', bar_signature:'Sb',
  /* fitness */
  hyrox:'Hx', padel:'Pd', tennis:'Tn', crossfit:'Cf', boxing:'Bx', climbing:'Cl',
  /* wellness */
  spa:'Sp', thermal:'Th', recovery:'Rc', meditation:'Md', hammam:'Hm',
  /* renovations */
  reno_heritage:'Hg', reno_adaptive:'Ar', reno_restoration:'Rs', reno_conversion:'Cv',
};
const symFor = (id) => TYPE_SYM[id] || (id||'').slice(0,2).toUpperCase();

/* ───────── Tile pictograms — line drawings, same pen as the homepage ───────── */
const TILE_ICON = {
  hotels: <svg viewBox="0 0 24 24"><path d="M3 18V8M3 14h18v4M21 14v-2a3 3 0 0 0-3-3h-7v5"/><circle cx="7" cy="11.5" r="1.6"/></svg>,
  restaurants: <svg viewBox="0 0 24 24"><path d="M7 3v8M5 3v5a2 2 0 0 0 4 0V3M7 11v10M16 21V3c-2 1.5-3 4-3 7h3"/></svg>,
  bars: <svg viewBox="0 0 24 24"><path d="M5 4h14l-7 8zM12 12v8M8 20h8"/></svg>,
  fitness: <svg viewBox="0 0 24 24"><path d="M8 12h8M2 12h2M20 12h2"/><rect x="4" y="7" width="4" height="10"/><rect x="16" y="7" width="4" height="10"/></svg>,
  wellness: <svg viewBox="0 0 24 24"><path d="M12 21c-5-2-7-6-7-11 4 0 7 2 7 6 0-4 3-6 7-6 0 5-2 9-7 11zM12 16V9"/></svg>,
  renovations: <svg viewBox="0 0 24 24"><path d="M14 6a4 4 0 0 0 5 5l-9 9-3-3 9-9a4 4 0 0 1-2-2z"/></svg>,
};

/* ───────── ReferenceTag — the DEFINE: lit screen ───────── */
const ReferenceTag = ({ value, onChange }) => {
  const mod = useModerationHint(value);
  return (
    <div className="inst-face">
      <div className="inst-brand">ROOTHERHUB<b>BRAIN</b></div>
      <div className="inst-define">
        <span className="inst-define-lbl">DEFINE:</span>
        <div className={"inst-screen" + (mod.flagged ? " mod-flag-input" : "")}>
          <input
            className="inst-screen-input"
            maxLength={REFERENCE_TAG.maxChars}
            placeholder={REFERENCE_TAG.placeholder || 'VENUE_26'}
            value={value || ''}
            onChange={(e) => onChange(e.target.value)}
          />
        </div>
      </div>
      <div className="inst-code">MODULE 01<br/>TYPOLOGY</div>
      {mod.flagged && <div className="mod-flag-caption">{mod.hint}</div>}
    </div>
  );
};

/* ───────── TaxonomyTree — periodic bank + channel strips + scale ───────── */
const TaxonomyTree = ({ value, onChange }) => {
  const v = value || { primary: null, secondary: null, primaryBracket: null, secondaryBracket: null, renovation: false };

  /* which parent's strip-tray is open for selection (UI only) */
  const [editParent, setEditParent] = React.useState(() => {
    const lf = leafById(v.primary); return lf ? lf.parent : null;
  });
  const [editRole, setEditRole] = React.useState('p');
  const [showBlock, setShowBlock] = React.useState(false);

  /* pick() — PRESERVED VERBATIM from production logic */
  const pick = (id) => {
    if (id === v.primary) {
      onChange({ ...v, primary: v.secondary, secondary: null,
                primaryBracket: v.secondaryBracket, secondaryBracket: null });
      return;
    }
    if (id === v.secondary) {
      onChange({ ...v, secondary: null, secondaryBracket: null });
      return;
    }
    if (!v.primary) { onChange({ ...v, primary: id }); return; }
    if (!v.secondary) { onChange({ ...v, secondary: id }); return; }
    setShowBlock(true);
    setTimeout(() => setShowBlock(false), 3600);
  };

  /* touch a parent cell → open its strip tray for the right role */
  const touchParent = (pid) => {
    const primLeaf = leafById(v.primary);
    const secLeaf = leafById(v.secondary);
    if (primLeaf && primLeaf.parent === pid) { setEditParent(pid); setEditRole('p'); return; }
    if (secLeaf && secLeaf.parent === pid)  { setEditParent(pid); setEditRole('s'); return; }
    setEditParent(pid);
    setEditRole(!v.primary ? 'p' : (!v.secondary ? 's' : 'p'));
  };

  const editBranch = TAXONOMY.find(b => b.id === editParent) || null;

  return (
    <div className="inst-body">
      <div className="inst-modhead">
        <span className="mono">{!v.primary ? '◇ NO VENUE YET'
          : (v.secondary ? 'TWO SIGNALS · SET EACH SCALE BELOW'
          : (v.primaryBracket ? 'SCALE SET · LOCK FOLD TO CONTINUE' : 'VENUE SET · SET THE SCALE BELOW'))}</span>
        <span className="inst-stage">
          <span className={"st" + (v.primary ? " done" : " active")}></span>
          <span className={"st" + (v.primary && v.primaryBracket ? " done" : (v.primary ? " active" : ""))}></span>
          <span className={"st" + (v.primary && v.primaryBracket ? " active" : "")}></span>
        </span>
      </div>

      {/* PERIODIC PARENT BANK */}
      <div className="inst-bank">
        {TAXONOMY.map((branch, i) => {
          const primLeaf = leafById(v.primary);
          const secLeaf = leafById(v.secondary);
          const isP = primLeaf && primLeaf.parent === branch.id;
          const isS = secLeaf && secLeaf.parent === branch.id;
          const editing = editParent === branch.id;
          return (
            <button key={branch.id} type="button"
              className={"inst-cell" + (isP ? " on-p" : "") + (isS ? " on-s" : "") + (editing ? " editing" : "")}
              onClick={() => touchParent(branch.id)}>
              <span className="inst-cell-idx mono">{String(i+1).padStart(2,'0')}</span>
              <span className="inst-cell-ico" aria-hidden="true">{TILE_ICON[branch.id]}</span>
              <span className="inst-cell-sym mono">{symFor(branch.id)}</span>
              <span className="inst-cell-nm">{branch.label}</span>
              <span className="inst-cell-cnt mono">{branch.children.length} SIG</span>
            </button>
          );
        })}
        <a className="inst-cell inst-cell-other" href="mailto:management@rootherhub.com?subject=Off-list%20project">
          <span className="inst-cell-idx mono">07</span>
          <span className="inst-cell-sym mono">+</span>
          <span className="inst-cell-nm">Other</span>
          <span className="inst-cell-cnt mono">TALK TO US</span>
        </a>
      </div>

      {/* CHANNEL STRIPS — sub-types of the touched parent */}
      {editBranch ? (
        <div className={"inst-strips-wrap for-" + editRole}>
          <div className="inst-strips-h mono">
            <span>{editBranch.label.toUpperCase()} · PICK ONE</span>
            <span className="inst-for">{editRole === 'p' ? 'PRIMARY' : 'SECONDARY'}</span>
          </div>
          <div className="inst-strips">
            {editBranch.children.map(c => {
              const isP = v.primary === c.id;
              const isS = v.secondary === c.id;
              const on = isP || isS;
              return (
                <button key={c.id} type="button"
                  className={"inst-strip" + (isP ? " armed-p" : "") + (isS ? " armed-s" : "")}
                  onClick={() => pick(c.id)}>
                  <div className="inst-strip-sym mono">{symFor(c.id)}</div>
                  <div className="inst-strip-rail"><div className="inst-strip-cap"></div></div>
                  <div className="inst-strip-name">{c.label}</div>
                  <div className="inst-strip-tag mono">{c.headline ? 'HEADLINE' : (isP ? 'PRIMARY' : (isS ? 'SECOND' : ''))}</div>
                </button>
              );
            })}
          </div>
        </div>
      ) : null}

      {/* THREE-OR-MORE BLOCK — preserved verbatim copy */}
      {showBlock ? (
        <div className="inst-block">
          ◆ Three-or-more typology combinations require Practice consultation. From the dashboard, choose <em>Engage the Practice</em>.
        </div>
      ) : null}

      {/* SCALE KNOBS — one channel per armed signal */}
      {v.primary ? (
        <div className="inst-controls">
          <BracketGrid
            typologyId={v.primary}
            value={v.primaryBracket}
            onChange={(b) => onChange({ ...v, primaryBracket: b })}
            label={(leafById(v.primary)?.label || '') + ' (primary)'}
            role="p" />
          {v.secondary ? (
            <BracketGrid
              typologyId={v.secondary}
              value={v.secondaryBracket}
              onChange={(b) => onChange({ ...v, secondaryBracket: b })}
              label={(leafById(v.secondary)?.label || '') + ' (secondary)'}
              role="s" />
          ) : null}
        </div>
      ) : null}

      {/* RENOVATION — hardware toggle, same checkbox binding */}
      {v.primary ? (
        <div className="inst-switches">
          <button type="button"
            className={"inst-toggle" + (v.renovation ? " on" : "")}
            onClick={() => onChange({ ...v, renovation: !v.renovation })}>
            <span className="inst-sw"></span>RENOVATION TRACK
          </button>
        </div>
      ) : null}
    </div>
  );
};

/* ───────── BracketGrid — scale channel: knob ticks XS–XL ─────────
   Same props (typologyId, value, onChange, label) + optional role for accent.
   Reads real BRACKET_RANGES; toggle-off preserved. */
/* ScaleKnob — rotary that drives the same value as the ticks.
   Knob drag/wheel → snaps to nearest bracket; ticks remain the
   visible value + accessible fallback. Same onChange contract. */
const SCALE_ANG = { XS:-100, S:-50, M:0, L:50, XL:100 };
const ScaleKnob = ({ value, onChange, role }) => {
  const ref = React.useRef(null);
  const dragging = React.useRef(false);
  const idx = value ? ALL_BRACKETS.indexOf(value) : -1;
  const ang = value ? SCALE_ANG[value] : -100;
  const nearestFromPoint = (clientX, clientY) => {
    const el = ref.current; if (!el) return value;
    const r = el.getBoundingClientRect();
    const cx = r.left + r.width/2, cy = r.top + r.height/2;
    let d = Math.atan2(clientX - cx, -(clientY - cy)) * 180 / Math.PI;
    d = Math.max(-110, Math.min(110, d));
    let best = ALL_BRACKETS[0], bd = 1e9;
    for (const b of ALL_BRACKETS) { const dd = Math.abs(d - SCALE_ANG[b]); if (dd < bd){ bd = dd; best = b; } }
    return best;
  };
  const down = (e) => { dragging.current = true; try{ ref.current.setPointerCapture(e.pointerId);}catch(_){}; const b = nearestFromPoint(e.clientX, e.clientY); if (b !== value) onChange(b); };
  const move = (e) => { if (!dragging.current) return; const b = nearestFromPoint(e.clientX, e.clientY); if (b !== value) onChange(b); };
  const up = () => { dragging.current = false; };
  const wheel = (e) => { e.preventDefault(); const cur = idx < 0 ? -1 : idx; const next = Math.max(0, Math.min(ALL_BRACKETS.length-1, cur + (e.deltaY > 0 ? 1 : -1))); onChange(ALL_BRACKETS[next]); };
  return (
    <div className="inst-knob-unit">
      <div ref={ref} className={"inst-knob" + (value ? " set" : "")}
        role="slider" tabIndex={0} aria-label="scale" aria-valuetext={value || 'unset'}
        onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerCancel={up} onWheel={wheel}
        onKeyDown={(e)=>{ const cur = idx<0?-1:idx; if(e.key==='ArrowRight'||e.key==='ArrowUp'){e.preventDefault();onChange(ALL_BRACKETS[Math.min(ALL_BRACKETS.length-1,cur+1)]);} if(e.key==='ArrowLeft'||e.key==='ArrowDown'){e.preventDefault();onChange(ALL_BRACKETS[Math.max(0,cur+ (cur<0?1:-1))]);} }}>
        <div className="inst-knob-notchwrap" style={{ transform: `rotate(${ang}deg)` }}>
          <div className={"inst-knob-notch " + (role === 'p' ? 'pri' : 'sec')}></div>
        </div>
      </div>
      <div className="inst-knob-cap mono">XS · XL</div>
    </div>
  );
};

const BracketGrid = ({ typologyId, value, onChange, label = 'Bracket', role = 'p' }) => {
  const ranges = BRACKET_RANGES[typologyId] || {};
  const leaf = leafById(typologyId);
  if (!leaf) return null;
  return (
    <div className={"inst-ch " + (role === 'p' ? 'primary' : 'secondary')}>
      <div className="inst-ch-h mono">
        <span>{role === 'p' ? 'CH 1 · PRIMARY' : 'CH 2 · SECONDARY'} · {symFor(typologyId)} {label.toUpperCase()}</span>
        <span>SCALE</span>
      </div>
      <div className="inst-ch-row knobbed">
        <ScaleKnob value={value} onChange={(b) => onChange(b)} role={role} />
        <div className="inst-ch-readout">
          <div className="inst-ticks">
            {ALL_BRACKETS.map(b => {
              const on = value === b;
              return (
                <button key={b} type="button"
                  className={"inst-tick" + (on ? " on" : "")}
                  onClick={() => onChange(on ? null : b)}>
                  {b}
                </button>
              );
            })}
          </div>
          <div className="inst-cap">
            <span className="inst-cap-lbl mono">{value ? 'CAPACITY · ' + value : 'SET THE SCALE'}</span>
            <span className="inst-cap-big">{value ? (ranges[value] || '–') : '–'}</span>
          </div>
        </div>
      </div>
    </div>
  );
};


/* ───────── ADDRESS TYPEAHEAD (Nominatim) ───────── */
const AddressTypeahead = ({ value, onChange }) => {
  const [q, setQ] = React.useState(value?.display || '');
  const [results, setResults] = React.useState([]);
  const [open, setOpen] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const tRef = React.useRef(null);

  React.useEffect(() => {
    if (!q || q.length < 3) { setResults([]); return; }
    if (value?.display === q) return;
    clearTimeout(tRef.current);
    tRef.current = setTimeout(async () => {
      setBusy(true);
      try {
        const url = `https://nominatim.openstreetmap.org/search?format=json&limit=5&q=${encodeURIComponent(q)}`;
        const r = await fetch(url, { headers: { 'Accept-Language': 'en' } });
        const data = await r.json();
        setResults(Array.isArray(data) ? data : []);
        setOpen(true);
      } catch (e) { setResults([]); }
      finally { setBusy(false); }
    }, 320);
    return () => clearTimeout(tRef.current);
  }, [q]);

  const choose = (r) => {
    onChange({ display: r.display_name, lat: parseFloat(r.lat), lng: parseFloat(r.lon) });
    setQ(r.display_name);
    setOpen(false);
  };
  const clearAddr = () => { onChange(null); setQ(''); setResults([]); };

  const state = value ? 'LOCKED' : busy ? 'SEARCHING' : (q.length >= 3 ? 'READY' : 'IDLE');
  return (
    <div className="inst-site-mod inst-addr-mod">
      <div className="inst-mod-h mono"><span>◆ ADDRESS · TRUTH</span><span className="inst-addr-state">{state}</span></div>
      <div className="inst-addr-screen">
        <div className="inst-addr-input-row">
          <input
            className="inst-addr-input"
            placeholder="City, address or coordinates. Try Tulum, Mexico"
            value={q}
            onChange={(e) => setQ(e.target.value)}
            onFocus={() => results.length && setOpen(true)} />
          {value ? <button type="button" className="inst-addr-clear" onClick={clearAddr}>clear</button> : null}
        </div>
        {busy ? <div className="inst-addr-busy mono">searching the globe…</div> : null}
        {open && results.length ? (
          <div className="inst-addr-list">
            {results.map(r => (
              <button key={r.place_id} type="button" className="inst-addr-item" onClick={() => choose(r)}>
                {r.display_name}
              </button>
            ))}
          </div>
        ) : null}
        {value ? (
          <div className="inst-addr-pin mono">◆ PIN · {value.lat.toFixed(3)}, {value.lng.toFixed(3)}</div>
        ) : null}
      </div>
    </div>
  );
};

/* ───────── LINE MAP — world map, editorial cartographic register ─────────
   Equirectangular projection. Lng range [-180,180] → x [0,360].
   Lat range [-90,90] → y [180,0] (inverted, north up).
   Continent silhouettes are simplified Natural Earth-inspired polylines —
   recognizable as continents without claiming geodetic accuracy.
   The pin is the visual hero in mineral clay.

   Doctrine:
   - Bone ground, charcoal hairlines, no fills inside continents.
   - Equator + tropics + arctic circles as dashed hairlines.
   - Graticule (lng/lat grid) at lowest opacity for atmosphere.
   - When pin set: clay dot + halo + crosshair leader to "SITE" label.
   - When no pin: faint regional anchors hint at where projects typically land. */
const LineMap = ({ pin }) => {
  const project = (lat, lng) => [(lng + 180), (90 - lat)];
  const px = pin ? project(pin.lat, pin.lng) : null;

  /* Real geography — generated Natural Earth 110m coastlines from
     data/world-coastline.jsx (WORLD_COASTLINE_PATH global, loaded before
     this file). One source, never retyped. Doctrine: the instrument
     never contains hand-traced geography. */
  const coastPath = (typeof WORLD_COASTLINE_PATH !== 'undefined') ? WORLD_COASTLINE_PATH : '';

  return (
    <div className="lm">
      <div className="lm-l mono">◆ MAP · LINE-ORIENTED · GEODETIC</div>
      <svg viewBox="0 0 360 180" className="lm-svg" preserveAspectRatio="xMidYMid meet">
        {/* Graticule — lightest layer, atmospheric grid */}
        <g stroke="rgba(31,31,29,0.06)" strokeWidth="0.25" fill="none">
          {[15, 30, 45, 60, 75, 90, 105, 120, 135, 150, 165].map(y => <line key={`h${y}`} x1="0" y1={y} x2="360" y2={y} />)}
          {[30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330].map(x => <line key={`v${x}`} x1={x} y1="0" x2={x} y2="180" />)}
        </g>
        {/* Equator + tropics + arctic/antarctic — dashed mid-tone */}
        <g stroke="rgba(31,31,29,0.18)" strokeWidth="0.35" fill="none" strokeDasharray="2 2.5">
          <line x1="0" y1="90" x2="360" y2="90" />
          <line x1="0" y1="66.5" x2="360" y2="66.5" />
          <line x1="0" y1="113.5" x2="360" y2="113.5" />
          <line x1="0" y1="23.5" x2="360" y2="23.5" />
          <line x1="0" y1="156.5" x2="360" y2="156.5" />
        </g>
        {/* Coastlines — real Natural Earth geography, charcoal hairline, no fill */}
        <g stroke="rgba(31,31,29,0.62)" strokeWidth="0.4" fill="none" strokeLinejoin="round" strokeLinecap="round">
          <path d={coastPath} />
        </g>
        {/* Faint regional hints when no pin — where projects typically land */}
        {!pin ? (
          <g fill="rgba(44,95,98,0.06)" stroke="rgba(44,95,98,0.40)" strokeWidth="0.35" strokeDasharray="1.5 1.5">
            <ellipse cx="92" cy="58" rx="44" ry="20" />
            <ellipse cx="195" cy="50" rx="26" ry="14" />
            <ellipse cx="120" cy="125" rx="22" ry="22" />
          </g>
        ) : null}
        {/* The pin — mineral clay, visual hero */}
        {px ? (
          <g>
            <circle cx={px[0]} cy={px[1]} r="14" fill="none" stroke="rgba(201,107,90,0.18)" strokeWidth="0.3" />
            <circle cx={px[0]} cy={px[1]} r="8" fill="none" stroke="rgba(201,107,90,0.40)" strokeWidth="0.4" />
            <circle cx={px[0]} cy={px[1]} r="3.2" fill="#C96B5A" stroke="#1F1F1D" strokeWidth="0.5" />
            <line x1={px[0]} y1={px[1] - 4} x2={px[0]} y2={px[1] - 16} stroke="#1F1F1D" strokeWidth="0.4" />
            <text x={px[0] + 4} y={px[1] - 11} fontSize="4.5" fill="#1F1F1D" fontFamily="JetBrains Mono" letterSpacing="0.5">SITE</text>
          </g>
        ) : null}
      </svg>
      <div className="lm-foot mono">
        {pin
          ? `◆ ${pin.display.length > 60 ? pin.display.slice(0, 60) + '…' : pin.display}`
          : '◆ NO PIN YET · OUR REGIONS GLOW · NORTH AMERICA · WESTERN EUROPE'}
      </div>
    </div>
  );
};

/* ───────── GEO GLOBE — orthographic, real geography, the healed loader ─────────
   Replaces the CSS-ring "spinning" globe (spinning loaders are forbidden by
   the motion grammar). Reads WORLD_LAND_RINGS from data/world-coastline.jsx.

   States, mapped onto the existing IDLE/READING/PINNED vocabulary:
   - No pin  → DRIFT: slow ambient rotation ("quietly reading", rest not work)
   - Pin set → TRAVEL: rotates shortest-path to center the address,
               easeOutCubic ~900ms — claimed as the Site fold's first breath.
               "Here's where this goes", never "look how I'm thinking."
   - Settled → LOCK: drift stops, clay pin + halo holds.

   Bone rendering: charcoal hairlines on bone, clay pin — per the canvas rule.
   prefers-reduced-motion: no drift, no travel — snaps to the pinned state. */
const GeoGlobe = ({ pin }) => {
  const gRef = React.useRef(null);
  const cam = React.useRef({ lon: 20, lat: 15 });
  const animRef = React.useRef(null);
  const RINGS = (typeof WORLD_LAND_RINGS !== 'undefined') ? WORLD_LAND_RINGS : [];
  const R = 44, CX = 50, CY = 50, D2R = Math.PI / 180;

  const draw = () => {
    const { lon, lat } = cam.current;
    const φ0 = lat * D2R, λ0 = lon * D2R;
    const proj = (la, lo) => {
      const φ = la * D2R, λ = lo * D2R;
      const cosc = Math.sin(φ0) * Math.sin(φ) + Math.cos(φ0) * Math.cos(φ) * Math.cos(λ - λ0);
      if (cosc < 0) return null;
      return [CX + R * Math.cos(φ) * Math.sin(λ - λ0),
              CY - R * (Math.cos(φ0) * Math.sin(φ) - Math.sin(φ0) * Math.cos(φ) * Math.cos(λ - λ0))];
    };
    const ringPath = (ring, step = 1) => {
      let d = '', pen = false;
      for (let i = 0; i < ring.length; i += step) {
        const p = proj(ring[i][1], ring[i][0]);
        if (p) { d += (pen ? 'L' : 'M') + p[0].toFixed(1) + ',' + p[1].toFixed(1); pen = true; }
        else pen = false;
      }
      return d;
    };
    let s = '<circle cx="' + CX + '" cy="' + CY + '" r="' + R + '" fill="none" stroke="rgba(31,31,29,.45)" stroke-width=".6"/>';
    s += '<g stroke="rgba(31,31,29,.08)" stroke-width=".3" fill="none">';
    for (let la = -60; la <= 60; la += 30) { const r = []; for (let lo = -180; lo <= 180; lo += 6) r.push([lo, la]); s += '<path d="' + ringPath(r) + '"/>'; }
    for (let lo = -180; lo < 180; lo += 30) { const r = []; for (let la = -88; la <= 88; la += 4) r.push([lo, la]); s += '<path d="' + ringPath(r) + '"/>'; }
    s += '</g><g stroke="rgba(31,31,29,.6)" stroke-width=".45" fill="none" stroke-linejoin="round">';
    for (const r of RINGS) { const d = ringPath(r); if (d) s += '<path d="' + d + '"/>'; }
    s += '</g>';
    if (pin) {
      const p = proj(pin.lat, pin.lng);
      if (p) s += '<g><circle cx="' + p[0] + '" cy="' + p[1] + '" r="7" fill="none" stroke="rgba(201,107,90,.22)" stroke-width=".4"/>'
        + '<circle cx="' + p[0] + '" cy="' + p[1] + '" r="4" fill="none" stroke="rgba(201,107,90,.45)" stroke-width=".5"/>'
        + '<circle cx="' + p[0] + '" cy="' + p[1] + '" r="1.8" fill="#C96B5A" stroke="#1F1F1D" stroke-width=".4"/></g>';
    }
    if (gRef.current) gRef.current.innerHTML = s;
  };

  React.useEffect(() => {
    const RM = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    cancelAnimationFrame(animRef.current);
    if (pin) {
      const tLon = pin.lng, tLat = pin.lat * 0.7;
      if (RM) { cam.current = { lon: tLon, lat: tLat }; draw(); return; }
      const sLon = cam.current.lon, sLat = cam.current.lat;
      const dLon = ((tLon - sLon) % 360 + 540) % 360 - 180;   /* shortest path */
      const T = 900, t0 = performance.now();
      const step = (now) => {
        const k = Math.min(1, (now - t0) / T), e = 1 - Math.pow(1 - k, 3);
        cam.current = { lon: sLon + dLon * e, lat: sLat + (tLat - sLat) * e };
        draw();
        if (k < 1) animRef.current = requestAnimationFrame(step);
      };
      animRef.current = requestAnimationFrame(step);
    } else {
      if (RM) { draw(); return; }
      const loop = () => { cam.current.lon += 0.05; draw(); animRef.current = requestAnimationFrame(loop); };
      animRef.current = requestAnimationFrame(loop);
    }
    return () => cancelAnimationFrame(animRef.current);
  }, [pin && pin.lat, pin && pin.lng]);

  return (
    <svg viewBox="0 0 100 100" className="inst-geoglobe" aria-label={pin ? 'Globe centered on project site' : 'Globe at rest'}>
      <g ref={gRef}></g>
    </svg>
  );
};

/* ───────── SITE TYPE PICKER ───────── */
const SiteTypePicker = ({ selected, onToggle, max = 4, own = [], onAddOwn, onRemoveOwn }) => {
  const set = selected instanceof Set ? selected : new Set(selected || []);
  const atMax = set.size >= max;
  const [ownInput, setOwnInput] = React.useState('');
  const mod = useModerationHint(ownInput);
  const handleAdd = () => {
    const t = ownInput.trim();
    if (!t || !onAddOwn) return;
    const id = 'own-' + t.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'').slice(0,32) + '-' + Math.random().toString(36).slice(2,5);
    onAddOwn({ id, label: t, own: true, pending: mod.flagged });
    setOwnInput('');
  };
  const all = [...SITE_TYPE, ...own];
  return (
    <div className="stp">
      <div className="stp-l mono">◆ SITE TYPE · ≤ {max}</div>
      <div className="stp-row">
        {all.map(s => {
          const on = set.has(s.id);
          const dim = !on && atMax;
          return (
            <button key={s.id} type="button"
              className={`stp-chip ${on ? 'on' : ''} ${dim ? 'dim' : ''} ${s.own ? 'own' : ''}`}
              onClick={() => onToggle(s.id)}>
              {s.own ? <span className="who-chip-own-mark">+</span> : null}
              {s.label}
            </button>
          );
        })}
      </div>
      {onAddOwn ? (
        <div className="own-row">
          <div className="own-l mono">◆ OR IN YOUR OWN WORDS</div>
          <div className="own-input-row">
            <input className={"own-input" + (mod.flagged ? " mod-flag-input" : "")} placeholder="e.g. cliffside · former cannery · floating dock"
              value={ownInput} onChange={(e) => setOwnInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleAdd(); } }}
              maxLength={48} />
            <button type="button" className="own-add" onClick={handleAdd} disabled={!ownInput.trim()}>+ ADD</button>
          </div>
          {mod.flagged && <div className="mod-flag-caption">{mod.hint}</div>}
        </div>
      ) : null}
    </div>
  );
};

/* ───────── LAND STATUS PICKER ───────── */
const LandStatusPicker = ({ value, onChange }) => (
  <div className="inst-site-mod">
    <div className="inst-mod-h mono">◆ LAND STATUS</div>
    <div className="inst-land-row">
      {LAND_STATUS.map(s => {
        const on = value === s.id;
        return (
          <button key={s.id} type="button"
            className={"inst-land-opt" + (on ? " on" : "")}
            onClick={() => onChange(on ? null : s.id)} title={s.gloss}>
            <span className="inst-land-h">{s.label}</span>
            <span className="inst-land-g">{s.gloss}</span>
          </button>
        );
      })}
    </div>
  </div>
);

/* ───────── AREA INPUT (lives inside Site fold now) ───────── */
const AreaInput = ({ value, onChange, unit, onUnit, length, width, dimUnit, onLength, onWidth, onDimUnit, stories, onStories }) => {
  const du = dimUnit || 'lf';
  const computed = (length && width) ? (length * width) : null;
  /* Volumetric v0.9 (Path B) — stories knob + type-in. Footprint × stories = GFA.
     Default 1 story; knob sweeps 1..40, type-in overrides past the sweep. */
  const stVal = Math.max(1, Math.floor(Number(stories)) || 1);
  const stArmed = stVal > 1;
  const stPct = Math.max(0, Math.min(1, (Math.min(40, stVal) - 1) / 39));
  const stAngle = -70 + stPct * 140;
  const gfa = computed != null ? computed * stVal : null;
  return (
    <div className="inst-area">
      {/* DIMENSIONS — length × width with LF / M switch (instrument) */}
      <div className="inst-mod-h mono"><span>◆ DIMENSIONS · LENGTH × WIDTH</span>
        <span className="inst-dim-switch">
          <button type="button" className={du === 'lf' ? 'on' : ''} onClick={() => onDimUnit && onDimUnit('lf')}>LF</button>
          <button type="button" className={du === 'm' ? 'on' : ''} onClick={() => onDimUnit && onDimUnit('m')}>M</button>
        </span>
      </div>
      <div className="inst-dim-row">
        <div className="inst-dim-field">
          <input type="number" min="0" placeholder="length"
            value={length ?? ''}
            onChange={(e) => onLength && onLength(e.target.value === '' ? null : Number(e.target.value))}
            className="inst-dim-input mono" />
          <span className="inst-dim-u mono">{du.toUpperCase()}</span>
        </div>
        <span className="inst-dim-x mono">×</span>
        <div className="inst-dim-field">
          <input type="number" min="0" placeholder="width"
            value={width ?? ''}
            onChange={(e) => onWidth && onWidth(e.target.value === '' ? null : Number(e.target.value))}
            className="inst-dim-input mono" />
          <span className="inst-dim-u mono">{du.toUpperCase()}</span>
        </div>
        <div className="inst-dim-eq mono">
          {computed ? <React.Fragment>= <b>{computed.toLocaleString()}</b> {du === 'm' ? 'm²' : 'SF'} <span style={{ color: 'var(--ink-3)' }}>footprint</span></React.Fragment> : '= –'}
        </div>
      </div>

      {/* STORIES — knob + type-in (v0.9 Path B). Drives GFA = footprint × stories. */}
      <div className="inst-mod-h mono" style={{ marginTop: 14 }}><span>◆ STORIES · FLOORS ON THE FOOTPRINT</span></div>
      <div className="inst-cap-row">
        <div className={"inst-cap-knob" + (stArmed ? " armed" : "")}
          onClick={() => onStories && onStories(Math.min(40, stVal + 1))}
          onContextMenu={(e) => { e.preventDefault(); onStories && onStories(Math.max(1, stVal - 1)); }}
          title="click to add a floor · right-click to remove">
          <div className="inst-cap-n" style={{ transform: `rotate(${stAngle}deg)` }}></div>
        </div>
        <div className="inst-cap-read">
          <div className="inst-cap-val">
            <input type="number" min="1" step="1" placeholder="1"
              value={stories ?? ''}
              onChange={(e) => onStories && onStories(e.target.value === '' ? null : Math.max(1, Math.floor(Number(e.target.value))))}
              className="inst-cap-input mono" />
            <span className="inst-cap-unit">{stVal === 1 ? 'story' : 'stories'}</span>
          </div>
          <div className="inst-cap-hint mono">Turn the knob or type the floors.</div>
        </div>
      </div>

      {/* GFA — computed, the number the brain prices */}
      <div className="inst-dim-row" style={{ marginTop: 8 }}>
        <div className="inst-dim-eq mono">
          {gfa != null
            ? <React.Fragment>◆ GFA = <b>{gfa.toLocaleString()}</b> {du === 'm' ? 'm²' : 'SF'} <span style={{ color: 'var(--ink-3)' }}>· {computed.toLocaleString()} × {stVal} {stVal === 1 ? 'floor' : 'floors'}</span></React.Fragment>
            : <span style={{ color: 'var(--ink-3)' }}>◆ GFA · ENTER LENGTH × WIDTH</span>}
        </div>
      </div>

      {/* AREA — fallback: only used when no L×W footprint is given */}
      <div className="inst-mod-h mono" style={{ marginTop: 14 }}><span>◆ OR TOTAL AREA · FALLBACK IF NO L×W</span>
        <span className="inst-dim-switch">
          <button type="button" className={unit === 'sf' ? 'on' : ''} onClick={() => onUnit('sf')}>SF</button>
          <button type="button" className={unit === 'm2' ? 'on' : ''} onClick={() => onUnit('m2')}>m²</button>
        </span>
      </div>
      <div className="inst-dim-row">
        <div className="inst-dim-field wide">
          <input type="number" min="0" placeholder="e.g. 28000"
            value={value ?? ''}
            onChange={(e) => onChange(e.target.value === '' ? null : Number(e.target.value))}
            className="inst-dim-input mono" />
          <span className="inst-dim-u mono">{unit === 'm2' ? 'm²' : 'SF'}</span>
        </div>
      </div>
      <div className="inst-area-foot mono">◆ BLANK IS FINE · THE BRAIN SIZES IT</div>
    </div>
  );
};

/* ───────── SITE CONDITION PICKER v0.7.1 (May 16 2026) ─────────
   6-condition selector. Adopted from Investment Brain Board review.
   Site condition determines:
   - Which capex track runs (greenfield vs renovation)
   - Capital posture for investment brief
   - Schedule logic adjustments
   - Risk flag defaults

   For renovation/conversion conditions, also surfaces work_scope question. */
const SITE_COND_SYM = { empty_lot:'El', existing_same_use:'Ex', existing_change_use:'Cu', rooftop:'Rt', historic:'Hs', mixed:'Mx' };
/* v0.9.5 (2026-11-14) — the same six stored values, asked in the order an owner
   thinks. Most owners take over a building; that comes first and is what the
   dashboard assumes until they answer. Ids are unchanged, so the cost engine and
   the Worker read exactly what they read before. */
const SITE_CONDITION_OPTIONS = [
  { id: 'existing_same_use',   label: 'Existing building',          note: 'Same use, renovation to upgrade or reposition' },
  { id: 'existing_change_use', label: 'Existing · different use',   note: 'Conversion / adaptive reuse' },
  { id: 'rooftop',             label: 'Rooftop / insert',           note: 'Adding above or within existing fabric' },
  { id: 'historic',            label: 'Historic / character',       note: 'Preserved fabric, approval-heavy' },
  { id: 'mixed',               label: 'Mixed condition',            note: 'Multiple zones: new build, renovation, exterior' },
  { id: 'empty_lot',           label: 'Empty lot',                  note: 'Full greenfield, you control everything' },
];
const SITE_Q1 = [
  { id: 'building', sym: 'Ex', label: 'Yes, there is a building', note: 'Taking over, renting or buying a place that is already built.' },
  { id: 'empty_lot', sym: 'El', label: 'No, it is empty land', note: 'Building new from the ground up.' },
  { id: 'mixed', sym: 'Mx', label: 'Both', note: 'Part existing building, part new construction.' },
];
const SITE_Q2 = [
  { id: 'existing_same_use',   label: 'The same kind of place', note: 'A restaurant that stays a restaurant, a hotel that stays a hotel.' },
  { id: 'existing_change_use', label: 'Something else',         note: 'An office, shop, house or warehouse becoming your venue.' },
  { id: 'rooftop',             label: 'A rooftop or a space inside', note: 'Built on top of, or inside, a building that keeps running.' },
  { id: 'historic',            label: 'A protected or historic building', note: 'Old fabric to keep. More approvals.' },
];
const WORK_SCOPE_OPTIONS = [
  { id: 'light',          label: 'Light',     note: 'Same layout. New finishes, lighting and furniture.' },
  { id: 'medium',         label: 'Medium',    note: 'New kitchen or bathrooms, new wiring and air, some walls move.' },
  { id: 'heavy',          label: 'Heavy',     note: 'Stripped to the shell and rebuilt inside.' },
  { id: 'adaptive_reuse', label: 'Full conversion', note: 'A new use, brought up to today\'s rules. The deepest work.' },
];
/* What the cost engine assumes when the depth is not answered (construction-brain router). */
const assumedWorkScope = (condition) =>
  condition === 'existing_change_use' ? 'adaptive_reuse'
  : (condition === 'rooftop' || condition === 'historic') ? 'heavy' : 'medium';

const SiteConditionPicker = ({ condition, workScope, onCondition, onWorkScope }) => {
  const q1 = !condition ? null : condition === 'empty_lot' ? 'empty_lot' : condition === 'mixed' ? 'mixed' : 'building';
  const q1Shown = q1 || 'building';            /* unanswered reads as a building, marked assumed */
  const isBuilding = q1Shown === 'building';
  const q2 = isBuilding ? (condition || 'existing_same_use') : null;
  const depthAssumed = assumedWorkScope(q2);
  const depthShown = workScope || depthAssumed;
  const depthOptions = WORK_SCOPE_OPTIONS.filter(o => o.id !== 'adaptive_reuse' || q2 === 'existing_change_use' || workScope === 'adaptive_reuse');
  const tile = (key, on, assumed, sym, label, note, onClick) => (
    <button key={key} type="button" className={"inst-cond" + (on ? " on" : "")} onClick={onClick} title={note}
      style={assumed ? { borderStyle: 'dashed', borderColor: '#E17863' } : null}>
      {sym ? <span className="inst-cond-sym mono">{sym}</span> : null}
      <span className="inst-cond-name">{label}</span>
      <span className="inst-cond-note">{assumed ? 'ASSUMED UNTIL YOU CHOOSE · ' : ''}{note}</span>
    </button>
  );
  return (
    <div className="inst-site-mod">
      <div className="inst-mod-h mono">◆ 1 · IS THERE A BUILDING ALREADY?</div>
      <div className="inst-cond-grid">
        {SITE_Q1.map(o => tile(o.id, q1 === o.id, !q1 && o.id === 'building', o.sym, o.label, o.note,
          () => onCondition(o.id === 'building' ? (isBuilding && condition ? condition : 'existing_same_use') : o.id)))}
      </div>

      {isBuilding ? (
        <React.Fragment>
          <div className="inst-mod-h mono" style={{ marginTop: 14 }}>◆ 2 · WHAT WAS IT BEFORE?</div>
          <div className="inst-cond-grid" style={{ gridTemplateColumns: 'repeat(2,1fr)' }}>
            {SITE_Q2.map(o => tile(o.id, condition === o.id, !condition && o.id === 'existing_same_use', SITE_COND_SYM[o.id], o.label, o.note,
              () => onCondition(o.id)))}
          </div>

          <div className="inst-mod-h mono" style={{ marginTop: 14 }}>◆ 3 · HOW MUCH ARE YOU CHANGING?</div>
          <div className="inst-cond-grid" style={{ gridTemplateColumns: `repeat(${depthOptions.length},1fr)` }}>
            {depthOptions.map(o => tile(o.id, workScope === o.id, !workScope && o.id === depthAssumed, null, o.label, o.note,
              () => { if (!condition) onCondition('existing_same_use'); onWorkScope(workScope === o.id ? null : o.id); }))}
          </div>
          <div className="inst-ws-note">
            This is the answer that moves the cost most. Heavy work can cost about four times light work on the same building. The dashboard shows each level priced for your building, so you can pick the one that fits your budget.
          </div>
        </React.Fragment>
      ) : (
        <div className="inst-ws-note">
          {q1Shown === 'empty_lot'
            ? 'New construction is priced from the ground up. It is the largest commitment of the three.'
            : 'Part new, part existing is priced as a deep conversion until the zones are split out.'}
        </div>
      )}
    </div>
  );
};

/* ───────── CAPACITY INPUT ───────── */
const CapacityInput = ({ typologyId, bracket, value, onChange }) => {
  const leaf = leafById(typologyId);
  if (!leaf) return (
    <div className="cap empty">◆ Pick a typology in fold 01 first.</div>
  );
  /* Derive a sensible unit label from leaf id */
  const unitMap = {
    spa:'rooms', thermal:'m² wet', recovery:'stations', meditation:'rooms', hammam:'m²',
    hyrox:'athletes', padel:'courts', tennis:'courts', crossfit:'athletes', boxing:'rings', climbing:'m² wall',
    restaurant:'seats', bar:'seats', hotel:'keys', reno:'SF',
  };
  const unit = unitMap[typologyId] || 'units';
  const range = bracket ? (BRACKET_RANGES[typologyId] || {})[bracket] : null;

  /* Parse min/max from the bracket range string (e.g. "40–80", "2-4") for the knob sweep */
  const parseRange = (r) => {
    if (!r) return null;
    const nums = String(r).match(/\d+/g);
    if (!nums || nums.length < 2) return null;
    return { min: Number(nums[0]), max: Number(nums[nums.length - 1]) };
  };
  const rng = parseRange(range);
  const armed = value != null;
  /* knob notch angle: sweep -70deg..+70deg across the bracket; out-of-range (manual override) pins to an edge */
  let knobAngle = -70;
  if (rng && armed) {
    const clamped = Math.max(rng.min, Math.min(rng.max, value));
    const pct = rng.max > rng.min ? (clamped - rng.min) / (rng.max - rng.min) : 0;
    knobAngle = -70 + pct * 140;
  } else if (armed && !rng) {
    knobAngle = 0;
  }
  const knobStep = (dir) => {
    if (!rng) { onChange((value || 0) + dir); return; }
    const cur = value == null ? rng.min : value;
    const next = Math.max(rng.min, Math.min(rng.max, cur + dir));
    onChange(next);
  };

  return (
    <div className="inst-cap-mod">
      <div className="inst-mod-h mono"><span>◆ CAPACITY · {unit.toUpperCase()} · FROM {leaf.label.toUpperCase()}{bracket ? ` · ${bracket}` : ''}</span></div>
      <div className="inst-cap-row">
        <div className={"inst-cap-knob" + (armed ? " armed" : "")}
          onClick={() => knobStep(1)}
          onContextMenu={(e) => { e.preventDefault(); knobStep(-1); }}
          title="click to raise · right-click to lower">
          <div className="inst-cap-n" style={{ transform: `rotate(${knobAngle}deg)` }}></div>
        </div>
        <div className="inst-cap-read">
          <div className="inst-cap-val">
            <input type="number" min="0" placeholder={rng ? String(rng.min) : '0'}
              value={value ?? ''}
              onChange={(e) => onChange(e.target.value === '' ? null : Number(e.target.value))}
              className="inst-cap-input mono" />
            <span className="inst-cap-unit">{unit}</span>
          </div>
          <div className="inst-cap-bracket mono">◆ BRACKET RANGE · {range || 'PICK A BRACKET'}</div>
          <div className="inst-cap-hint mono">Turn the knob or type a number.</div>
        </div>
      </div>
      <div className="inst-cap-foot mono">◆ BLANK IS FINE · THE BRAIN SIZES IT</div>
    </div>
  );
};

/* ───────── WHO PICKER (Users + Operators + AI/Robotics) ─────────
   Users column is typology-driven: seed list from USERS_BY_LEAF, with
   a "Refine with brain" button that calls claude.complete and swaps in
   AI-tuned chips. Operators + AI carry forward unchanged. */
const WhoPicker = ({ selectedByGroup, onToggle, max = 6, typology, atmosphere, ownUsers = [], onAddOwn }) => {
  /* ADDITIVE refine: brain output is appended to the existing pool, deduped by id.
     This preserves prior selections AND lets the user keep refining to grow options. */
  const [brainUsers, setBrainUsers] = React.useState([]);
  const [refining, setRefining] = React.useState(false);
  const [refineCount, setRefineCount] = React.useState(0);
  const [ownInput, setOwnInput] = React.useState('');
  const [activeModule, setActiveModule] = React.useState(0);
  const mod = useModerationHint(ownInput);

  const seedUsers = React.useMemo(
    () => usersForCombination({ primary: typology?.primary, secondary: typology?.secondary }),
    [typology?.primary, typology?.secondary]
  );
  /* Reset accumulated brain users when typology changes */
  React.useEffect(() => { setBrainUsers([]); setRefineCount(0); }, [typology?.primary, typology?.secondary]);

  /* Merge: seed + brain + own (own = user's freeform additions, persisted in answers) */
  const mergedUsers = React.useMemo(() => {
    const seen = new Set();
    const out = [];
    for (const u of [...seedUsers, ...brainUsers, ...ownUsers]) {
      if (!u || !u.id || seen.has(u.id)) continue;
      seen.add(u.id);
      out.push(u);
    }
    return out;
  }, [seedUsers, brainUsers, ownUsers]);

  const handleRefine = async () => {
    if (!typology?.primary) return;
    setRefining(true);
    const fresh = await refineUsersWithBrain({
      primary: typology.primary,
      secondary: typology.secondary,
      feeling: atmosphere?.feeling || [],
      materiality: atmosphere?.materiality || [],
    });
    /* Filter out anything we already have, then append */
    const existingIds = new Set(mergedUsers.map(u => u.id));
    const additions = (fresh || []).filter(u => u && u.id && !existingIds.has(u.id));
    if (additions.length) {
      setBrainUsers(prev => [...prev, ...additions]);
    }
    setRefineCount(c => c + 1);
    setRefining(false);
  };
  const handleClearBrain = () => { setBrainUsers([]); setRefineCount(0); };

  const handleAddOwn = () => {
    const t = ownInput.trim();
    if (!t || !onAddOwn) return;
    const id = 'own-' + t.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32) + '-' + Math.random().toString(36).slice(2, 5);
    onAddOwn({ id, label: t, gloss: 'Your own.', own: true, pending: mod.flagged });
    setOwnInput('');
  };

  /* Build groups dynamically — Users is dynamic, others are static */
  const groups = [
    { id:'guests', label:'Users', sub:'Seeded from your typology. Refine with the Brain for sharper picks.', options: mergedUsers, dynamic: true },
    ...WHO_GROUPS.filter(g => g.id !== 'guests'),
  ];

  return (
    <div className="who-wrap">
      {typology?.primary ? (
        <div className="refine-row">
          <div className="refine-l">
            ◆ USERS · SEEDED FROM <strong>{(leafById(typology.primary)?.label || '').toUpperCase()}</strong>
            {typology.secondary ? <> + <strong>{(leafById(typology.secondary)?.label || '').toUpperCase()}</strong></> : null}
            {refineCount > 0 ? <> · <strong>BRAIN ×{refineCount}</strong></> : null}
            {ownUsers.length ? <> · <strong>{ownUsers.length} OWN</strong></> : null}
          </div>
          <div style={{ display:'flex', gap:8 }}>
            {brainUsers.length ? (
              <button className="refine-btn revert" onClick={handleClearBrain} type="button">↺ clear brain ({brainUsers.length})</button>
            ) : null}
            <button className="refine-btn" onClick={handleRefine} disabled={refining} type="button">
              {refining ? '◆ THINKING…' : (refineCount > 0 ? '◆ REFINE AGAIN' : '◆ REFINE WITH BRAIN')}
            </button>
          </div>
        </div>
      ) : (
        <div className="refine-row">
          <div className="refine-l">◆ USERS · PICK A TYPOLOGY IN FOLD 01 TO SEED</div>
        </div>
      )}
      {typology?.primary && onAddOwn ? (
        <div className="own-row">
          <div className="own-l mono">◆ OR IN YOUR OWN WORDS</div>
          <div className="own-input-row">
            <input
              className={"own-input" + (mod.flagged ? " mod-flag-input" : "")}
              placeholder="e.g. boat captains who lunch · digital nomads on three-week loops"
              value={ownInput}
              onChange={(e) => setOwnInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleAddOwn(); } }}
              maxLength={64} />
            <button type="button" className="own-add" onClick={handleAddOwn} disabled={!ownInput.trim()}>+ ADD</button>
          </div>
          {mod.flagged && <div className="mod-flag-caption">{mod.hint}</div>}
        </div>
      ) : null}
      <div className="who-modules">
        <div className="who-tabs">
          {groups.map((g, i) => {
            const set = selectedByGroup[g.id] || new Set();
            const isAI = g.id === 'ai_robotics';
            return (
              <button key={g.id} type="button"
                className={"who-tab" + (i === activeModule ? " active" : "") + (set.size > 0 ? " has" : "") + (isAI ? " ai" : "")}
                onClick={() => setActiveModule(i)}>
                <span className="wt-l">{g.label}</span>
                <span className="wt-c mono">{set.size > 0 ? set.size + ' SET' : g.options.length + ' OPTIONS'}</span>
              </button>
            );
          })}
        </div>
        {(() => {
          const g = groups[activeModule];
          const set = selectedByGroup[g.id] || new Set();
          const atMax = set.size >= max;
          const isAI = g.id === 'ai_robotics';
          return (
            <div className="who-drill">
              <div className="who-sub">{g.sub}</div>
              {g.id === 'guests' ? (
                /* GUESTS — click-arm knobs (orange), 4-up grid */
                <div className="who-knob-grid">
                  {g.options.map((o, i) => {
                    const on = set.has(o.id);
                    const dim = !on && atMax;
                    const onAngle = 38 + (i % 3) * 8;
                    return (
                      <button key={o.id} type="button"
                        className={"inst-how-knob who-knob" + (on ? " on" : "") + (dim ? " dim" : "") + (o.own ? " own" : "")}
                        title={o.gloss || ''} onClick={() => onToggle(g.id, o.id)}>
                        <span className="inst-how-dial"><span className="inst-how-n" style={{ transform: `rotate(${on ? onAngle : 0}deg)` }}></span></span>
                        <span className="inst-how-lbl">{o.own ? <span className="who-chip-own-mark">+</span> : null}{o.label}</span>
                      </button>
                    );
                  })}
                </div>
              ) : (
                /* OPERATORS + AI·ROBOTICS — sliding switches (orange / green), responsive rows */
                <div className={"who-switch-grid" + (isAI ? " ai" : "")}>
                  {g.options.map(o => {
                    const on = set.has(o.id);
                    const dim = !on && atMax;
                    return (
                      <button key={o.id} type="button"
                        className={"who-switch" + (on ? " on" : "") + (dim ? " dim" : "") + (o.own ? " own" : "")}
                        title={o.gloss || ''} onClick={() => onToggle(g.id, o.id)}>
                        <span className="who-switch-track"><span className="who-switch-knob"></span></span>
                        <span className="who-switch-lbl">{o.own ? <span className="who-chip-own-mark">+</span> : null}{o.label}</span>
                      </button>
                    );
                  })}
                </div>
              )}
              <div className="who-drill-cap mono">◆ {set.size} / {max} SELECTED IN {g.label.toUpperCase()}</div>
            </div>
          );
        })()}
      </div>
    </div>
  );
};

/* ───────── HOW MODEL PICKER ───────── */
const HowModelPicker = ({ selected, onToggle, max = 4, own = [], onAddOwn }) => {
  const set = selected instanceof Set ? selected : new Set(selected || []);
  const atMax = set.size >= max;
  const [ownInput, setOwnInput] = React.useState('');
  const mod = useModerationHint(ownInput);
  const handleAdd = () => {
    const t = ownInput.trim();
    if (!t || !onAddOwn) return;
    const id = 'own-' + t.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'').slice(0,32) + '-' + Math.random().toString(36).slice(2,5);
    onAddOwn({ id, label: t, own: true, pending: mod.flagged });
    setOwnInput('');
  };
  const all = [...HOW_MODEL, ...own];
  return (
    <div className="inst-how-mod">
      <div className="inst-mod-h mono"><span>◆ OPERATING MODEL · DEPTH ≤ {max}</span><span>{set.size}/{max}</span></div>
      <div className="inst-how-grid">
        {all.map((m, i) => {
          const on = set.has(m.id);
          const dim = !on && atMax;
          /* armed knobs auto-rotate to a set angle; idle sits neutral. Vary slightly by index for life. */
          const onAngle = 38 + (i % 3) * 8;
          return (
            <button key={m.id} type="button"
              className={"inst-how-knob" + (on ? " on" : "") + (dim ? " dim" : "") + (m.own ? " own" : "")}
              onClick={() => onToggle(m.id)} title={m.label}>
              <span className="inst-how-dial">
                <span className="inst-how-n" style={{ transform: `rotate(${on ? onAngle : 0}deg)` }}></span>
              </span>
              <span className="inst-how-lbl">{m.own ? <span className="who-chip-own-mark">+</span> : null}{m.label}</span>
            </button>
          );
        })}
      </div>
      {onAddOwn ? (
        <div className="own-row">
          <div className="own-l mono">◆ OR IN YOUR OWN WORDS</div>
          <div className="own-input-row">
            <input className={"own-input" + (mod.flagged ? " mod-flag-input" : "")} placeholder="e.g. owner-operated · seasonal pop-up · membership-led"
              value={ownInput} onChange={(e) => setOwnInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); handleAdd(); } }}
              maxLength={48} />
            <button type="button" className="own-add" onClick={handleAdd} disabled={!ownInput.trim()}>+ ADD</button>
          </div>
          {mod.flagged && <div className="mod-flag-caption">{mod.hint}</div>}
        </div>
      ) : null}
    </div>
  );
};

/* ───────── STORY FREE FIELD ───────── */
const STORY_GLYPHS = '\u2593\u2592\u2591\u2573\u25ca\u2317\u00a7\u00b6\u2206\u25c8\u203b#@%&$';
const StoryFreeField = ({ value, onChange, picked, onPicked }) => {
  const set = picked instanceof Set ? picked : new Set(picked || []);
  const atMax = set.size >= 4;
  const [blurredValue, setBlurredValue] = React.useState(value || '');
  React.useEffect(() => { setBlurredValue(value || ''); }, []);
  const mod = useModerationHint(blurredValue);

  /* VAULT — cipher encryption (visual only; real story stays in `value`/answers).
     Reversible: Decrypt·Edit resolves the cipher back and reopens the field. */
  const [vaulted, setVaulted] = React.useState(false);
  const [cipherText, setCipherText] = React.useState('');
  const animRef = React.useRef(null);
  const reduceMotion = (typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);
  const cipherChar = (ch) => (ch === ' ' || ch === '\n') ? ch : STORY_GLYPHS[Math.floor(Math.random() * STORY_GLYPHS.length)];
  const fullCipher = (src) => [...src].map(cipherChar).join('');

  const doVault = () => {
    const src = value || '';
    setVaulted(true);
    /* Start fully ciphered (plain NEVER visible). A short scramble settle re-rolls
       glyphs a few frames, then locks to a stable cipher. */
    let stable = fullCipher(src);
    setCipherText(stable);
    if (reduceMotion) return;
    let frame = 0;
    clearInterval(animRef.current);
    animRef.current = setInterval(() => {
      frame++;
      if (frame >= 5) { setCipherText(stable); clearInterval(animRef.current); return; }
      setCipherText(fullCipher(src)); /* re-roll glyphs = scrambling motion */
    }, 40);
  };
  const doDecrypt = () => {
    const src = value || '';
    if (reduceMotion) { clearInterval(animRef.current); setVaulted(false); return; }
    let frame = 0;
    clearInterval(animRef.current);
    animRef.current = setInterval(() => {
      frame++;
      let out = '';
      for (let i = 0; i < src.length; i++) out += (i < frame * 5) ? src[i] : cipherChar(src[i]);
      setCipherText(out);
      if (frame * 5 >= src.length) { clearInterval(animRef.current); setVaulted(false); }
    }, 28);
  };
  React.useEffect(() => () => clearInterval(animRef.current), []);

  /* interpretive brain + EQ — visual read of text + drivers (not literal) */
  const textLen = (value || '').trim().length;
  const nPick = set.size;
  const active = textLen > 0 || nPick > 0;
  const seed = [...set].reduce((a, id) => a + String(id).length, 0) + Math.floor(textLen / 12);
  const BRAIN_SHAPE = [0,1,1,1,1,1,0,1,1,0,1,0,1,1,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,0,1,1,1,0,1,1,1,0,1,0,1,1,0,1,1,0,1,1,0];
  const bars = [];
  for (let i = 0; i < 12; i++) {
    let h = 8;
    if (active) { const w = Math.sin((i + seed) * 0.9) * 0.5 + 0.5; h = 12 + w * 70 * (0.4 + nPick * 0.16 + Math.min(0.3, textLen / 500)); }
    bars.push(Math.min(96, h));
  }

  return (
    <div className="inst-story">
      {/* 1 · WRITING + cipher vault */}
      <div className="inst-story-mod story-wrap">
        <div className="inst-mod-h mono">◆ YOUR STORY · {STORY_FIELD.prompt.toUpperCase()}</div>
        <div className="story-hint">{STORY_FIELD.hint}</div>
        <div className={"story-vault-wrap" + (vaulted ? " is-vaulted" : "")}>
          <textarea
            className={"inst-story-area" + (mod.flagged ? " mod-flag-input" : "")}
            maxLength={STORY_FIELD.maxChars}
            placeholder="Three to ten honest sentences."
            value={value || ''}
            onChange={(e) => onChange(e.target.value)}
            onBlur={(e) => setBlurredValue(e.target.value)}
          />
          {vaulted ? (
            <div className="inst-cipher">
              <div className="inst-cipher-stamp mono">VAULTED</div>
              <span className="inst-cipher-text mono">{cipherText}</span>
            </div>
          ) : null}
        </div>
        {mod.flagged && !vaulted && <div className="mod-flag-caption">{mod.hint}</div>}
        {!vaulted ? (
          <div className="inst-story-foot">
            <span className="story-counter mono">{(value||'').length}/{STORY_FIELD.maxChars}</span>
            <button type="button" className="inst-vault-btn mono" disabled={(value||'').trim().length < 20} onClick={doVault}>◆ VAULT STORY</button>
          </div>
        ) : (
          <div className="inst-vaulted-row">
            <span className="inst-vault-tag mono">◆ STORY VAULTED · ENCRYPTED · READY</span>
            <button type="button" className="inst-decrypt-btn mono" onClick={doDecrypt}>DECRYPT · EDIT</button>
          </div>
        )}
      </div>

      {/* 2 · BRAIN + EQ (interpretive) */}
      <div className="inst-story-mod">
        <div className="inst-mod-h mono">◆ BRAIN · READING YOUR INTENT</div>
        <div className="inst-eq-screen">
          <div className="inst-brain-box">
            <div className="inst-brain-px">
              {BRAIN_SHAPE.map((v, i) => (
                <i key={i} className={v ? (active && ((i * 7 + seed) % 10) < (3 + nPick + Math.min(3, Math.floor(textLen/100))) ? 'lit' : 'dim') : ''}></i>
              ))}
            </div>
            <div className="inst-brain-lbl mono">RHB</div>
            <div className="inst-brain-think mono">{active ? 'INTERPRETING' : 'IDLE'}</div>
          </div>
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
            <div className="inst-eq-bars">
              {bars.map((h, i) => <div key={i} className="inst-eq-bar" style={{ height: h + '%' }}></div>)}
            </div>
            <div className="inst-eq-cap mono">{active ? '\u25c6 BRAIN WEIGHTING STORY' + (nPick ? ' + ' + nPick + ' DRIVER' + (nPick>1?'S':'') : '') + ' INTO THE NARRATIVE ARC' : 'WRITE AND SELECT DRIVERS \u00b7 WATCH THE BRAIN INTERPRET'}</div>
          </div>
        </div>
      </div>

      {/* 3 · DRIVER KEYS */}
      <div className="inst-story-mod">
        <div className="inst-mod-h mono">◆ DRIVERS · WHAT MAKES THIS WORTH IT · ≤ 4</div>
        <div className="inst-story-keys">
          {STORY_WORDS.map(w => {
            const on = set.has(w.id);
            const dim = !on && atMax;
            return (
              <button key={w.id} type="button"
                className={"inst-story-key" + (on ? " on" : "") + (dim ? " dim" : "")}
                onClick={() => onPicked(w.id)}>
                {w.label}
              </button>
            );
          })}
        </div>
        <div className="inst-story-keys-cap mono">◆ {set.size} / 4 SELECTED</div>
      </div>
    </div>
  );
};

/* ───────── TWO GRID — Atmosphere ─────────
   Two parallel 28-word grids. Each grid: ≤ max selections (default 4).
   Each grid also accepts user's "own words" additions (chip-form, prefixed +). */
/* control-type by word position (meaningful + interspersed); 40% knob 25% btn 20% tog 15% fad */
const ATM_CTRL_CYCLE = ['knob','fad','btn','knob','tog','knob','btn','fad','knob','tog','btn','knob','tog','fad','knob','btn','knob','tog','fad','knob','btn','knob','tog','fad','knob','btn','tog','knob'];
const atmCtrlType = (i) => ATM_CTRL_CYCLE[i % ATM_CTRL_CYCLE.length];
const atmTitle = (w) => String(w).replace(/(^|[\s&·-])([a-z])/g, (m, sep, ch) => sep + ch.toUpperCase());
const AtmControl = ({ word, type, on, dim, own, onClick }) => (
  <div className={"atm-ctrl" + (on ? " on" : "") + (dim ? " dim" : "") + (own ? " own" : "")} onClick={dim ? undefined : onClick}>
    {type === 'knob' ? <div className="atm-knob"><div className="atm-knob-n"></div></div>
      : type === 'btn' ? <div className="atm-btn"></div>
      : type === 'tog' ? <div className="atm-tog"></div>
      : <div className="atm-fad"><div className="atm-fad-rail"></div><div className="atm-fad-cap"></div></div>}
    <div className="atm-lbl">{own ? <span className="who-chip-own-mark">+</span> : null}{atmTitle(word)}</div>
  </div>
);

const TwoGrid = ({ leftWords, rightWords, leftSelected, rightSelected,
                   onLeftToggle, onRightToggle, leftLabel, rightLabel, max = 4,
                   leftOwn = [], rightOwn = [], onLeftAddOwn, onRightAddOwn }) => {
  const l = leftSelected instanceof Set ? leftSelected : new Set(leftSelected || []);
  const r = rightSelected instanceof Set ? rightSelected : new Set(rightSelected || []);
  /* max=null → uncapped (Atmosphere fold per Spec feedback (5)) */
  const uncapped = max == null;
  const lAtMax = uncapped ? false : l.size >= max;
  const rAtMax = uncapped ? false : r.size >= max;
  const [lIn, setLIn] = React.useState('');
  const [rIn, setRIn] = React.useState('');
  const lMod = useModerationHint(lIn);
  const rMod = useModerationHint(rIn);
  const addOwn = (text, onAdd, setIn) => {
    const t = (text || '').trim();
    if (!t || !onAdd) return;
    onAdd(t);
    setIn('');
  };
  /* twin-bar resonance — own words (the own arrays) lift BOTH bars */
  const lOwnPicked = leftOwn.filter(w => l.has(w)).length;
  const rOwnPicked = rightOwn.filter(w => r.has(w)).length;
  const braveTotal = lOwnPicked + rOwnPicked;
  const NSEG = 22;
  const shared = braveTotal * 3.0;                 /* bravery bonus lifts both */
  const soulLevel = Math.min(NSEG, l.size * 3.4 + shared);
  const skinLevel = Math.min(NSEG, r.size * 3.4 + shared);
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => { const id = setInterval(() => setTick(x => x + 1), 90); return () => clearInterval(id); }, []);
  const reduceMotion = (typeof window !== 'undefined' && window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);
  const segArray = (level, fast) => {
    const shimmer = reduceMotion ? 0 : (fast ? Math.round(Math.sin(tick * 0.5) * 1.2) : Math.sin(tick * 0.28) * 0.8) * (level > 0.5 ? 1 : 0);
    const h = Math.max(0, Math.round(level + shimmer));
    /* index 0 = BOTTOM (CSS uses column-reverse). lit if below the level.
       brave (green) only colors the TOP lit segments, and ONLY when own words are active. */
    return Array.from({ length: NSEG }, (_, i) => {
      const fromBottom = NSEG - i;          /* i=NSEG-1 is bottom -> fromBottom=1 lights first */
      const lit = fromBottom <= h;
      const brave = braveTotal > 0 && lit && fromBottom > h - 3;  /* top of the lit stack */
      return { lit, brave };
    });
  };
  const soulSegs = segArray(soulLevel, false);
  const skinSegs = segArray(skinLevel, true);
  const active = l.size + r.size > 0;
  return (
    <div className="atm">
      {/* SOUL console — scattered mixed controls */}
      <div className="atm-side">
        <div className="atm-side-h mono"><span><span className="atm-side-tag">SOUL</span>{leftLabel}</span><span className="atm-side-c">{l.size}/{max}</span></div>
        <div className="atm-console">
          {leftWords.map((w, i) => (
            <AtmControl key={w} word={w} type={atmCtrlType(i)} on={l.has(w)} dim={!l.has(w) && lAtMax} own={false} onClick={() => onLeftToggle(w)} />
          ))}
          {leftOwn.map((w, i) => (
            <AtmControl key={'own-'+w} word={w} type="knob" on={l.has(w)} dim={!l.has(w) && lAtMax} own={true} onClick={() => onLeftToggle(w)} />
          ))}
        </div>
        {onLeftAddOwn ? (
          <div className="own-row atm-own">
            <div className="own-input-row">
              <input className={"own-input" + (lMod.flagged ? " mod-flag-input" : "")} placeholder="your own feeling…"
                value={lIn} onChange={(e) => setLIn(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addOwn(lIn, onLeftAddOwn, setLIn); } }}
                maxLength={32} />
              <button type="button" className="own-add green" onClick={() => addOwn(lIn, onLeftAddOwn, setLIn)} disabled={!lIn.trim()}>+</button>
            </div>
            {lMod.flagged && <div className="mod-flag-caption">{lMod.hint}</div>}
            <div className="atm-own-note mono">◆ your words go green · lift both bars</div>
          </div>
        ) : null}
      </div>

      {/* CENTER — twin protagonist bars */}
      <div className="atm-core">
        <div className="atm-core-h mono"><span>◆ RESONANCE</span><span>{active ? 'RISING' : 'IDLE'}</span></div>
        <div className="atm-core-read mono">TWIN READ · SOUL // SKIN</div>
        <div className="atm-twin">
          <div className="atm-col">
            <div className="atm-col-bar">
              {soulSegs.map((seg, i) => <div key={i} className={"atm-seg" + (seg.lit ? " lit" : "") + (seg.brave ? " brave" : "")}></div>)}
            </div>
            <div className={"atm-col-num mono" + (braveTotal ? " brave" : "")}>{String(Math.min(99, l.size * 12 + braveTotal * 9)).padStart(2,'0')}</div>
            <div className="atm-col-cap mono">SOUL</div>
          </div>
          <div className="atm-col">
            <div className="atm-col-bar">
              {skinSegs.map((seg, i) => <div key={i} className={"atm-seg" + (seg.lit ? " lit" : "") + (seg.brave ? " brave" : "")}></div>)}
            </div>
            <div className={"atm-col-num mono" + (braveTotal ? " brave" : "")}>{String(Math.min(99, r.size * 12 + braveTotal * 9)).padStart(2,'0')}</div>
            <div className="atm-col-cap mono">SKIN</div>
          </div>
        </div>
        <div className="atm-core-sig mono">{!active ? '◇ COMPOSE THE ROOM' : '◆ ' + (braveTotal ? 'BRAVE · ' : '') + (l.size > r.size + 1 ? 'SOUL-LED' : r.size > l.size + 1 ? 'SKIN-LED' : 'BALANCED') + ' · RISING'}</div>
      </div>

      {/* SKIN console — scattered mixed controls */}
      <div className="atm-side">
        <div className="atm-side-h mono"><span><span className="atm-side-tag skin">SKIN</span>{rightLabel}</span><span className="atm-side-c">{r.size}/{max}</span></div>
        <div className="atm-console">
          {rightWords.map((w, i) => (
            <AtmControl key={w} word={w} type={atmCtrlType(i + 3)} on={r.has(w)} dim={!r.has(w) && rAtMax} own={false} onClick={() => onRightToggle(w)} />
          ))}
          {rightOwn.map((w, i) => (
            <AtmControl key={'own-'+w} word={w} type="knob" on={r.has(w)} dim={!r.has(w) && rAtMax} own={true} onClick={() => onRightToggle(w)} />
          ))}
        </div>
        {onRightAddOwn ? (
          <div className="own-row atm-own">
            <div className="own-input-row">
              <input className={"own-input" + (rMod.flagged ? " mod-flag-input" : "")} placeholder="your own material…"
                value={rIn} onChange={(e) => setRIn(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addOwn(rIn, onRightAddOwn, setRIn); } }}
                maxLength={32} />
              <button type="button" className="own-add green" onClick={() => addOwn(rIn, onRightAddOwn, setRIn)} disabled={!rIn.trim()}>+</button>
            </div>
            {rMod.flagged && <div className="mod-flag-caption">{rMod.hint}</div>}
            <div className="atm-own-note mono">◆ your words go green · lift both bars</div>
          </div>
        ) : null}
      </div>
    </div>
  );
};

/* ───────── RUNNING SUMMARY ─────────
   Compact mono panel that lives in the rail or footer — shows what the
   brain currently knows about this project. */
const RunningSummary = ({ answers }) => {
  const t = answers.typology || {};
  const s = answers.site || {};
  const o = answers.operation || {};
  const st = answers.story || {};
  const a = answers.atmosphere || {};

  const lines = [];
  if (t.primary) {
    const pl = leafById(t.primary);
    let line = `01  ${(pl?.label || t.primary).toUpperCase()}`;
    if (t.primaryBracket) line += ` · ${t.primaryBracket}`;
    if (t.secondary) {
      const sl = leafById(t.secondary);
      line += ` + ${(sl?.label || t.secondary).toUpperCase()}`;
      if (t.secondaryBracket) line += ` · ${t.secondaryBracket}`;
    }
    if (t.renovation) line += ' · RENO';
    lines.push(line);
  } else lines.push('01  –');

  if (s.pin || s.landStatus || (s.siteType||[]).length || s.area) {
    const parts = [];
    if (s.pin) parts.push('PIN');
    if (s.landStatus) parts.push(s.landStatus.toUpperCase());
    if ((s.siteType||[]).length) parts.push(`${s.siteType.length} SITE`);
    if (s.area) parts.push(`${s.area} ${s.areaUnit||'sf'}`);
    lines.push(`02  ${parts.join(' · ')}`);
  } else lines.push('02  –');

  if (o.precise != null || (o.guests||[]).length || (o.operators||[]).length || (o.ai_robotics||[]).length || (o.model||[]).length) {
    const parts = [];
    if (o.precise != null) parts.push(`${o.precise}`);
    const peopleCt = (o.guests||[]).length + (o.operators||[]).length + (o.ai_robotics||[]).length;
    if (peopleCt) parts.push(`${peopleCt} PICKED`);
    if ((o.model||[]).length) parts.push(`${o.model.length} MODEL`);
    lines.push(`03  ${parts.join(' · ')}`);
  } else lines.push('03  –');

  if ((st.picked||[]).length || (st.free||'').trim().length) {
    const parts = [];
    if ((st.picked||[]).length) parts.push(`${st.picked.length}W`);
    if ((st.free||'').trim().length) parts.push(`${(st.free||'').trim().split(/\s+/).length}wd`);
    lines.push(`04  ${parts.join(' · ')}`);
  } else lines.push('04  –');

  if ((a.feeling||[]).length || (a.materiality||[]).length) {
    const parts = [];
    if ((a.feeling||[]).length) parts.push(`${a.feeling.length}F`);
    if ((a.materiality||[]).length) parts.push(`${a.materiality.length}M`);
    lines.push(`05  ${parts.join(' · ')}`);
  } else lines.push('05  –');

  /* recorder screen: session timer + per-fold level bars */
  const [secs, setSecs] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setSecs(x => x + 1), 1000);
    return () => clearInterval(id);
  }, []);
  const mm = String(Math.floor(secs / 60)).padStart(2, '0');
  const ss = String(secs % 60).padStart(2, '0');
  const FOLD_NAMES = ['TYPOLOGY','SITE','OPERATION','STORY','ATMOSPHERE'];
  const filled = lines.filter(l => l.slice(2).trim() !== '–' && l.slice(2).trim() !== '').length;
  const pct = Math.round((filled / lines.length) * 100);
  const signals = (t.primary ? 1 : 0) + (t.secondary ? 1 : 0);

  return (
    <div className="rsum rec">
      <div className="rec-h mono"><span className="rdot">REC</span><span>BRAIN · SESSION</span></div>
      <div className="rec-screen">
        <div className="rec-screen-top">
          <div>
            <div className="rec-timer mono">{mm}:{ss}</div>
            <div className="rec-timer-lbl mono">SESSION TIME</div>
          </div>
          <div className="rec-meta mono">FOLD <b>{filled || 1}</b>/5<br/>SIGNALS <b>{signals}</b><br/>BONDED <b>NO</b></div>
        </div>
        <div className="rec-bars">
          {lines.map((l, i) => {
            const val = l.slice(2).trim();
            const empty = val === '–' || val === '';
            return (
              <div key={i} className={"rec-bar" + (empty ? " empty" : "")}>
                <span className="bn mono">{l.slice(0,2)}</span>
                <div className="track">{!empty ? <div className="fill mono">{val}</div> : null}</div>
                <span className="lvl mono">{empty ? '–' : 'SET'}</span>
              </div>
            );
          })}
        </div>
      </div>
      <div className="rec-foot mono"><span>◆ THE BRAIN CURRENTLY KNOWS</span><span className="pct">{pct}%</span></div>
    </div>
  );
};

Object.assign(window, {
  ReferenceTag,
  TaxonomyTree, BracketGrid,
  AddressTypeahead, LineMap, GeoGlobe, SiteTypePicker, LandStatusPicker, AreaInput,
  CapacityInput, WhoPicker, HowModelPicker,
  StoryFreeField, TwoGrid,
  RunningSummary,
});
