/* ============================================================
   TEND, SHARED SITE SHELL
   Nav (mega-menu), Footer, and layout helpers shared across every
   page. Exports to window so each page script can compose them.
   Load AFTER react, react-dom, babel, compass.js, icons.js, _ds_bundle.js
   ============================================================ */
const { useState, useEffect, useRef, useCallback } = React;

/* ---------- icon helper (TEND glyph family) ---------- */
function Glyph({ name, size = 18, color = 'currentColor', sw = 1.6 }) {
  return <span style={{ display: 'inline-flex', width: size, height: size, color }}
    dangerouslySetInnerHTML={{ __html: window.TENDIcons.get(name, { size, color, strokeWidth: sw }) }} />;
}

/* A tiny inline compass mark for the wordmark */
function CompassMark({ size = 22 }) {
  return <span className="mk" style={{ width: size, height: size }}
    dangerouslySetInnerHTML={{ __html: window.TENDCompass.render({ aqua: 70, coral: 30, amber: 22, violet: 44, size, style: 'minimal', labels: false }) }} />;
}

function Wordmark({ to = 'index.html', light = false }) {
  return (
    <a className="wordmark" href={to} style={light ? { color: 'var(--tend-page)' } : null}>
      <CompassMark />
      <span>TEND<span className="tm">©</span></span>
    </a>
  );
}

/* TEND inside a heading takes the landing page's colour-cycling style.
   tendify(x, 'tn') gives the quieter treatment used in running text. */
function tendify(node, cls = 'tend-c') {
  if (typeof node === 'string') {
    if (!/\bTEND\b/.test(node)) return node;
    return node.split(/\b(TEND)\b/).map((p, i) => p === 'TEND' ? <span key={'t' + i} className={cls}>TEND</span> : p);
  }
  if (Array.isArray(node)) return node.map((n, i) => typeof n === 'string' ? <React.Fragment key={'f' + i}>{tendify(n, cls)}</React.Fragment> : n);
  return node;
}

/* ---------- Navigation IA ---------- */
const NAV = [
  { label: 'Why TEND', key: 'why', href: 'why.html' },
  {
    label: 'How it works', key: 'how',
    aside: { eyebrow: 'Free · 12 questions', title: 'Which way do you TEND?', body: 'TEND Bearing takes ' + (window.TENDTimes ? window.TENDTimes.bearing : 'about 2 minutes') + ' and gives you a first read of the direction of your needle.', href: 'index.html#bearing', cta: 'Start TEND Bearing' },
    links: [
      { t: 'The TEND Compass', d: 'Four currents and one needle.', href: 'index.html#compass', ico: 'compass' },
      { t: 'The Partnership Path', d: 'Five phases, Spark to Elevate.', href: 'index.html#path', ico: 'elevate' },
      { t: 'Taking TEND, step by step', d: 'From the first question to your report.', href: 'how-it-works.html', ico: 'engineer' },
      { t: 'The four currents', d: 'Aqua · Coral · Amber · Violet.', href: 'science.html#energies', ico: 'spark' },
    ],
  },
  {
    label: 'Packages', key: 'pkg',
    aside: { eyebrow: 'For teams', title: 'Bring TEND to your team', body: 'Tell us about your team and we will shape a programme of TEND, talks and workshops with you.', href: 'journey.html', cta: 'Start a conversation' },
    links: [
      { t: 'Prices for individuals', d: 'TEND Bearing, Heading and Direction.', href: 'packages.html#prices', ico: 'compass' },
      { t: 'TEND Keynote', d: '60 minutes · main stage.', href: 'packages.html#keynote', ico: 'spark' },
      { t: 'TEND Workshop · 4 hours', d: 'Half-day, hands-on.', href: 'packages.html#workshop4', ico: 'engineer' },
      { t: 'TEND Workshop · 8 hours', d: 'Full-day immersion.', href: 'packages.html#workshop8', ico: 'champion' },
      { t: 'TEND Leadership Lab', d: '2 hours · the team Compass.', href: 'packages.html#lab', ico: 'reframe' },
      { t: 'Learning programmes', d: '3 to 6 months · shape yours in the builder.', href: 'journey.html', ico: 'elevate' },
    ],
  },
  {
    label: 'For practitioners', key: 'prac',
    links: [
      { t: 'Practitioner programme', d: 'Register your interest.', href: 'practitioners.html', ico: 'reframe' },
      { t: 'Practitioner log in', d: 'The TEND console.', href: 'console.html', ico: 'validity' },
    ],
  },
  {
    label: 'Resources', key: 'res',
    links: [
      { t: 'All resources', d: 'Everything in one place.', href: 'resources.html', ico: 'citation' },
      { t: 'The science & validity', d: 'Big Five, ten aspects, and the manual.', href: 'science.html#manual-request', ico: 'validity' },
      { t: 'Blog', d: 'News and research on personality at work.', href: 'blog.html', ico: 'spark' },
      { t: 'Talks & videos', d: 'Watch TEND explained.', href: 'resources.html#videos', ico: 'compass' },
    ],
  },
  {
    label: 'About', key: 'about',
    links: [
      { t: 'Methodology', d: 'How a profile is built.', href: 'methodology.html', ico: 'engineer' },
      { t: 'Andrew Wolhuter', d: 'The author of TEND.', href: 'resources.html#author', ico: 'champion' },
    ],
  },
];

function Chevron() {
  return <svg className="chev" viewBox="0 0 12 12" fill="none" aria-hidden="true"><path d="M2.5 4.5 L6 8 L9.5 4.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" /></svg>;
}

function Nav({ active }) {
  const [open, setOpen] = useState(null);
  const [scrolled, setScrolled] = useState(false);
  const [mobile, setMobile] = useState(false);
  const closeT = useRef(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 12);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const enter = (k) => { clearTimeout(closeT.current); setOpen(k); };
  const leave = () => { closeT.current = setTimeout(() => setOpen(null), 120); };

  return (
    <nav className={'nav' + (scrolled ? ' scrolled' : '')}>
      <div className="nav-inner">
        <Wordmark />
        <div className="nav-links" onMouseLeave={leave}
          onBlur={e => { if (!e.currentTarget.contains(e.relatedTarget)) setOpen(null); }}
          onKeyDown={e => { if (e.key === 'Escape') setOpen(null); }}>
          {NAV.map(group => group.href ? (
            <div key={group.key} className="nav-item" onMouseEnter={leave}>
              <a className={'nav-trigger' + (active === group.key ? ' is-on' : '')} href={group.href}>{group.label}</a>
            </div>
          ) : (
            <div key={group.key} className={'nav-item' + (open === group.key ? ' open' : '')}
              onMouseEnter={() => enter(group.key)}>
              <button className="nav-trigger" aria-expanded={open === group.key}
                onClick={() => setOpen(o => (o === group.key ? null : group.key))} onFocus={() => enter(group.key)}>
                {group.label}<Chevron />
              </button>
              <div className={'mega' + (group.aside ? ' wide' : '')} onMouseEnter={() => enter(group.key)}>
                <div className="mega-list">
                  {group.links.map(l => (
                    <a key={l.t} className="mega-link" href={l.href}>
                      <span className="ml-t"><span className="ml-ico"><Glyph name={l.ico} size={18} /></span>{l.t}</span>
                      <span className="ml-d" style={{ paddingLeft: 27 }}>{l.d}</span>
                    </a>
                  ))}
                </div>
                {group.aside && (
                  <a className="mega-aside" href={group.aside.href} style={{ textDecoration: 'none' }}>
                    <div>
                      <div className="ma-eyebrow">{group.aside.eyebrow}</div>
                      <div className="ma-title">{tendify(group.aside.title)}</div>
                      <div className="ma-body" style={{ marginTop: 8 }}>{group.aside.body}</div>
                    </div>
                    <span className="btn-link" style={{ color: 'var(--aqua-deep)', fontWeight: 600 }}>{group.aside.cta} →</span>
                  </a>
                )}
              </div>
            </div>
          ))}
        </div>
        <div className="nav-cta">
          <a className="btn-link cta-secondary" href="signin.html">Sign in</a>
          <a className="btn btn-ink nav-start" href="index.html#bearing">Start TEND Bearing</a>
          <button className="nav-burger" aria-label="Menu" onClick={() => setMobile(m => !m)}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">
              {mobile ? <><path d="M6 6 L18 18" /><path d="M18 6 L6 18" /></> : <><path d="M4 7 H20" /><path d="M4 12 H20" /><path d="M4 17 H20" /></>}
            </svg>
          </button>
        </div>
      </div>
      <div className={'mobile-menu' + (mobile ? ' open' : '')}>
        {NAV.map(group => group.href ? (
          <div className="mobile-group" key={group.key}><a className="mg-t" href={group.href}>{group.label}</a></div>
        ) : (
          <div className="mobile-group" key={group.key}>
            <div className="mg-t">{group.label}</div>
            {group.links.map(l => <a key={l.t} href={l.href}>{l.t}</a>)}
          </div>
        ))}
        <div style={{ display: 'flex', gap: 12, marginTop: 24 }}>
          <a className="btn btn-ink btn-lg" href="index.html#bearing" style={{ flex: 1 }}>Start TEND Bearing</a>
          <a className="btn btn-outline btn-lg" href="signin.html" style={{ flex: 1 }}>Sign in</a>
        </div>
      </div>
    </nav>
  );
}

/* ---------- Footer ---------- */
const FOOT = [
  { h: 'Explore', links: [['Why TEND', 'why.html'], ['How it works', 'how-it-works.html'], ['The science', 'science.html'], ['Methodology', 'methodology.html'], ['Blog', 'blog.html'], ['Resources', 'resources.html']] },
  { h: 'Packages', links: [['Prices', 'packages.html#prices'], ['Keynote', 'packages.html#keynote'], ['Workshops', 'packages.html#workshop4'], ['Leadership Lab', 'packages.html#lab'], ['Learning programmes', 'journey.html']] },
  { h: 'Take part', links: [['Start TEND Bearing', 'index.html#bearing'], ['Bring TEND to your team', 'journey.html'], ['Practitioner programme', 'practitioners.html'], ['Sign in', 'signin.html'], ['Practitioner log in', 'console.html']] },
];

/* ---------- Cookie consent ----------
   Essential storage (your place in the questions, a kept TEND Bearing,
   the offer timer) always runs. Analytics run only after Accept all. */
const CONSENT_KEY = 'tend-cookie-consent';
function readConsent() { try { return JSON.parse(localStorage.getItem(CONSENT_KEY) || 'null'); } catch (e) { return null; } }
function openCookieSettings(e) { if (e) e.preventDefault(); window.dispatchEvent(new Event('tend-cookie-open')); }
function CookieBanner() {
  const [show, setShow] = useState(() => !readConsent());
  useEffect(() => { const on = () => setShow(true); window.addEventListener('tend-cookie-open', on); return () => window.removeEventListener('tend-cookie-open', on); }, []);
  const save = (analytics) => { try { localStorage.setItem(CONSENT_KEY, JSON.stringify({ essential: true, analytics, at: Date.now() })); } catch (e) {} setShow(false); };
  if (!show) return null;
  return (
    <section className="cookie" role="region" aria-label="Cookies">
      <div className="cookie-in">
        <p className="cookie-t">Cookies on TEND</p>
        <p className="cookie-b">TEND keeps a small amount of information on your device so that it works, such as your place in the questions. With your permission, we would also like to use analytics cookies to learn which pages help people most. <a href="privacy.html#cookies">Read the cookie policy</a>.</p>
        <div className="cookie-acts">
          <button type="button" className="btn btn-ink" onClick={() => save(true)}>Accept all</button>
          <button type="button" className="btn btn-outline" onClick={() => save(false)}>Essential only</button>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div className="footer-brand">
            <a className="wordmark wm" href="index.html" style={{ color: 'var(--tend-page)' }}>
              TEND<span className="tm">©</span>
            </a>
            <p className="signoff" style={{ color: 'color-mix(in srgb, var(--tend-page) 88%, transparent)', marginTop: 18, maxWidth: '22ch' }}>Now go tend to it.</p>
            <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'color-mix(in srgb, var(--tend-page) 62%, transparent)', maxWidth: '34ch', marginTop: 18, lineHeight: 1.55 }}>
              The Trait-based Executive Navigation Diagnostic, a workplace diagnostic for everyone at work.
            </p>
          </div>
          {FOOT.map(col => (
            <div className="footer-col" key={col.h}>
              <h4>{col.h}</h4>
              <ul>{col.links.map(([t, h]) => <li key={t}><a href={h}>{t}</a></li>)}</ul>
            </div>
          ))}
        </div>
        <div className="footer-bottom">
          <div className="footer-tomc">
            <img src="assets/tomc/tomc-logo-white.svg" alt="The ONmedia Collective" />
            <p>TEND is a brand of The ONmedia Collective (Pty) Ltd. Reg 2026/110700/07.</p>
          </div>
          <p className="footer-legal">
            TEND is for development only. It is never used for selection, promotion or any employment decision. © {new Date().getFullYear()} The ONmedia Collective (Pty) Ltd. All rights reserved.
          </p>
        </div>
        <ul className="footer-policy">
          <li><a href="privacy.html">Privacy policy</a></li>
          <li><a href="terms.html">Terms and conditions</a></li>
          <li><a href="privacy.html#cookies">Cookie policy</a></li>
          <li><button type="button" onClick={openCookieSettings}>Cookie settings</button></li>
        </ul>
      </div>
      <CookieBanner />
    </footer>
  );
}

/* ---------- Reveal on scroll ---------- */
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    if (!('IntersectionObserver' in window)) { els.forEach(e => e.classList.add('in')); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); } });
    }, { threshold: 0.12, rootMargin: '0px 0px -8% 0px' });
    els.forEach(e => io.observe(e));
    return () => io.disconnect();
  });
}

/* ---------- Section header ---------- */
function SectionHead({ eyebrow, title, lead, align = 'left', energy, kicker }) {
  return (
    <div className={'section-head ' + (align === 'center' ? 'center mx-auto' : '')} style={align === 'center' ? { maxWidth: 760 } : null}>
      {eyebrow && <div className="eyebrow" style={energy ? { '--energy-core': `var(--${energy}-core)` } : null}>{eyebrow}</div>}
      <h2 className="display-l">{tendify(title)}</h2>
      {lead && <p className="lead" style={{ marginTop: 20, maxWidth: 620, marginInline: align === 'center' ? 'auto' : 0 }}>{tendify(lead, 'tn')}</p>}
    </div>
  );
}

/* The four current marks, as supplied. Each sits in a square box with
   object-fit: contain; the m-* classes only centre and match their size. */
function CurrentMark({ k, size = 72, alt = '' }) {
  return <span className="cmark" style={{ width: size, height: size }}><img className={'m-' + k} src={'assets/marks/tend-mark-' + k + '.png'} alt={alt} /></span>;
}

Object.assign(window, { Glyph, CompassMark, Wordmark, Nav, Footer, useReveal, SectionHead, NAV, tendify, CookieBanner, openCookieSettings, CurrentMark });

/* Re-export DS primitives as bare globals so page scripts (separate Babel
   scopes) can use them without destructuring on every page. */
(function () {
  const DS = window.TENDDesignSystem_f72a8e || {};
  ['Button', 'Card', 'Field', 'Tag', 'Compass', 'StageBadge', 'StenBar', 'ValidityFlag'].forEach(k => {
    if (DS[k]) window[k] = DS[k];
  });
})();
