/* primitives.jsx — shared building blocks for the site
   WordPicker (1–4 max + freeform), Chip, Eyebrow, Nav, Colophon */

const Eyebrow = ({ children }) => (
  <div className="eyebrow"><span className="dot" />{children}</div>
);

const Nav = ({ active }) => {
  const links = [
    { href: '/',            label: 'Home',        id: 'home' },
    { href: '/brain',       label: 'Brain',       id: 'landing' },
    { href: '/hospitality', label: 'Hospitality', id: 'hospitality' },
    { href: '/industrial',  label: 'Industrial',  id: 'industrial' },
  ];
  return (
    <div className="nav">
      <div className="nav-l">
        <a href="/" className="nav-brand" style={{ display: 'inline-flex', alignItems: 'center', gap: 10, textDecoration: 'none', color: 'inherit', fontFamily: 'Outfit, system-ui, sans-serif', fontWeight: 800, fontSize: 15, letterSpacing: '.14em' }}>
          <img src="/assets/brand/mark-56.png" alt="" width="19" height="28" style={{ display: 'block', height: 28, width: 'auto' }} />
          <span>ROOTHERHUB</span>
        </a>
      </div>
      <div className="nav-r">
        {links.map(l => (
          <a key={l.id} href={l.href} className={active === l.id ? 'on' : ''}>{l.label}</a>
        ))}
      </div>
    </div>
  );
};

const Colophon = () => (
  <div className="colophon">
    <div>
      <img src="/assets/brand/mark-56.png" alt="" width="19" height="28" style={{ display: 'block', marginBottom: 10 }} />
      <strong>ROOTHERHUB · LLC</strong>
      Architecture and engineering for hospitality and industry. Mexico and the United States.
    </div>
    <div>
      <strong>REGISTERED OFFICE</strong>
      5900 Balcones Dr, Austin, TX 78731
    </div>
    <div>
      <strong>CONTACT</strong>
      <a href="mailto:sales@rootherhub.com">sales@rootherhub.com</a><br />
      <a href="/">rootherhub.com</a>
    </div>
  </div>
);

const Chip = ({ kind = '', children }) => (
  <span className={`chip ${kind}`}>
    {kind === 'bonded' ? <span className="dot" /> : null}
    {children}
  </span>
);

/* ── WORD PICKER ─────────────────────────────────────────────
   Constraint: pick 1–4 from the list; if none fit, complement
   with a small free-text box. The data feeds the brain API. */
const WordPicker = ({
  question,
  words,           // [{ id, label }]
  selected,        // Set<string>
  onSelect,        // (id) => void
  freeform,        // string
  onFreeform,      // (str) => void
  max = 4,
  min = 1,
}) => {
  const count = selected.size;
  const atMax = count >= max;
  return (
    <div className="wp">
      <div className="wp-head">
        <div className="wp-q">{question}</div>
        <div className="wp-counter">
          <span className="v">{count}</span>/ {max} MAX
        </div>
      </div>
      <div className="wp-grid">
        {words.map((w, i) => {
          const on = selected.has(w.id);
          const dim = !on && atMax;
          return (
            <button
              key={w.id}
              className={`wp-tile ${on ? 'on' : ''} ${dim ? 'dim' : ''}`}
              onClick={() => onSelect(w.id)}
            >
              <span className="num">{String(i + 1).padStart(2, '0')}</span>
              {w.label}
              <span className="pill">✓</span>
            </button>
          );
        })}
      </div>
      <div>
        <div className="wp-free-l">
          <span>◆ Or complement — your own words</span>
          <span className="mono">{(freeform || '').length} CHAR</span>
        </div>
        <textarea
          className="wp-free"
          placeholder="If none of the above quite fits — write what you actually mean. Two or three lines is plenty."
          value={freeform || ''}
          onChange={(e) => onFreeform(e.target.value)}
          maxLength={500}
        />
      </div>
      <div className="body-sm" style={{ color: 'var(--ink-3)', fontFamily: 'var(--ff-mono)', fontSize: 10, letterSpacing: '0.10em' }}>
        ◆ {min}–{max} WORDS · OR FREE TEXT · OR BOTH · CONSTANT THROUGHOUT THE FOLDS
      </div>
    </div>
  );
};

/* Persistence — was global pool, now project-scoped.
   loadAnswers / saveAnswers are defined in state-projects.jsx, which
   must load AFTER primitives.jsx (see hospitality.html and
   dashboard.html script ordering). This file no longer touches
   localStorage directly. */


/* ───────── FlapTitle — fold titles on the same split-flap board as the homepage hero ───────── */
const FlapTitle = ({ text }) => {
  const ref = React.useRef(null);
  const state = React.useRef({ grid: '', tiles: [], cols: 0, rows: 0, timers: [] });
  const A = " ABCDEFGHIJKLMNOPQRSTUVWXYZ.,?'";
  const STEP = 150, STAGGER = 55, ROWLAG = 140, TILE = 0.79;
  const still = typeof window !== 'undefined' && window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches;

  const wrap = (t, cols) => {
    const out = []; let line = '';
    t.toUpperCase().split(' ').forEach(w => {
      if (!line) line = w; else if ((line + ' ' + w).length <= cols) line += ' ' + w; else { out.push(line); line = w; }
    });
    if (line) out.push(line);
    return out;
  };
  const toGrid = (t, cols, rows) => {
    const r = wrap(t, cols); let g = '';
    for (let y = 0; y < rows; y++) { let l = r[y] || ''; while (l.length < cols) l += ' '; g += l; }
    return g;
  };
  const build = (keepText) => {
    const el = ref.current; if (!el) return;
    const st = state.current;
    const W = el.parentNode.clientWidth;
    const cols = W < 420 ? 14 : (W < 640 ? 18 : 22);
    const rows = wrap(text, cols).length;
    el.style.fontSize = Math.min(44, Math.floor(W / (cols * TILE))) + 'px';
    el.textContent = '';
    st.tiles = []; st.cols = cols; st.rows = rows;
    const g = toGrid(keepText, cols, rows);
    for (let y = 0; y < rows; y++) {
      const r = document.createElement('div'); r.className = 'fb-r'; r.setAttribute('aria-hidden', 'true');
      r.style.gridTemplateColumns = 'repeat(' + cols + ',1fr)';
      for (let x = 0; x < cols; x++) {
        const c = document.createElement('span'); c.className = 'fb-c';
        const i = document.createElement('i'); i.textContent = g[y * cols + x]; c.appendChild(i); r.appendChild(c); st.tiles.push(i);
      }
      el.appendChild(r);
    }
    st.grid = g;
  };
  const flip = (el) => { const c = el.parentNode; c.classList.remove('f'); void c.offsetWidth; c.classList.add('f'); };

  React.useEffect(() => {
    const st = state.current;
    st.timers.forEach(clearTimeout); st.timers = [];
    build(still ? text : '');
    if (still) return;
    const g = toGrid(text, st.cols, st.rows);
    st.tiles.forEach((el, idx) => {
      const x = idx % st.cols, y = (idx - x) / st.cols;
      const to = g[idx]; let b = A.indexOf(to); if (b < 0) b = 0;
      if (b === 0) return;
      let a = (b - Math.min(6, b) + A.length) % A.length, p = a;
      const tick = () => { p = (p + 1) % A.length; el.textContent = A[p]; flip(el); if (p !== b) st.timers.push(setTimeout(tick, STEP)); };
      st.timers.push(setTimeout(tick, x * STAGGER + y * ROWLAG));
    });
    return () => { st.timers.forEach(clearTimeout); st.timers = []; };
  }, [text]);

  React.useEffect(() => {
    let t; const on = () => { clearTimeout(t); t = setTimeout(() => build(text), 200); };
    window.addEventListener('resize', on);
    return () => { window.removeEventListener('resize', on); clearTimeout(t); };
  }, [text]);

  return <div className="fold-q flap-board" ref={ref} role="heading" aria-level="2" aria-label={text}>{text}</div>;
};

Object.assign(window, { Eyebrow, Nav, Colophon, Chip, WordPicker, FlapTitle });
