/* global React */
const { useState, useEffect, useRef, useCallback } = React;

/* ---------- Scroll reveal ---------- */
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const root = ref.current;
    if (!root) return;
    const els = root.matches?.('.reveal') ? [root] : Array.from(root.querySelectorAll('.reveal'));
    if (!els.length) return;
    if (!('IntersectionObserver' in window)) { els.forEach(e => e.classList.add('in')); return; }
    const io = new IntersectionObserver((entries) => {
      entries.forEach(en => {
        if (en.isIntersecting) { en.target.classList.add('in'); io.unobserve(en.target); }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -8% 0px' });
    els.forEach(e => io.observe(e));
    return () => io.disconnect();
  });
  return ref;
}

/* ---------- Logo — hex mark + official wordmark ---------- */
function Logo({ size = 24 }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center' }}>
      {/* Official lockup — mark + wordmark in one coordinate space.
          Mark scaled 0.409 so its stroke (22→9) matches the wordmark stroke (9);
          both centered on the shared y-axis (48) and sitting level. */}
      <svg viewBox="0 0 474 96" height={size * 1.09} width={size * 1.09 * (474 / 96)}
           role="img" aria-label="Xaint" style={{ display: 'block' }}>
        {/* Mark */}
        <g transform="translate(-23 -17.4) scale(0.409)" strokeLinejoin="miter">
          <path d="M160 62 L243 110 L243 210 L160 258 L77 210 L77 110 Z" fill="none"
                stroke="var(--accent)" strokeWidth="22" />
          <path d="M120 192 L160 138 L200 192" fill="none"
                stroke="var(--accent)" strokeWidth="20" />
          <circle cx="160" cy="206" r="6" fill="var(--accent)" />
        </g>
        {/* Wordmark — A·I carry the accent (hidden AI) */}
        <g transform="translate(105.5 4)" strokeLinecap="square" fill="none">
          <g stroke="var(--ink)" strokeWidth="9">
            <line x1="8" y1="14" x2="62" y2="74" /><line x1="62" y1="14" x2="8" y2="74" />
            <line x1="208" y1="74" x2="208" y2="14" /><line x1="208" y1="14" x2="270" y2="74" /><line x1="270" y1="74" x2="270" y2="14" />
            <line x1="296" y1="14" x2="358" y2="14" /><line x1="327" y1="14" x2="327" y2="74" />
          </g>
          <g stroke="var(--accent)" strokeWidth="9">
            <line x1="92" y1="74" x2="123" y2="14" /><line x1="123" y1="14" x2="154" y2="74" />
            <line x1="180" y1="14" x2="180" y2="74" />
          </g>
        </g>
      </svg>
    </span>
  );
}

/* ---------- Section label ---------- */
function SectionLabel({ index, children, accent }) {
  return (
    <div className="tag" style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
      {index && <span className="tag-accent tabnum">{index}</span>}
      <span style={{ width: 26, height: 1, background: 'var(--line-2)' }} />
      <span className={accent ? 'tag-accent' : ''}>{children}</span>
    </div>
  );
}

/* ---------- Button ---------- */
function Btn({ children, primary, sm, href = '#', onClick, arrow }) {
  return (
    <a className={`btn${primary ? ' btn-primary' : ''}${sm ? ' btn-sm' : ''}`}
       href={href} onClick={onClick}>
      {children}
      {arrow && <span className="arr">→</span>}
    </a>
  );
}

/* ---------- Placeholder image ---------- */
function Ph({ label, ratio = '16 / 10', style, children, grid }) {
  return (
    <div className={`ph${grid ? ' grid-bg' : ''}`} style={{ aspectRatio: ratio, ...style }}>
      <CornerTicks />
      {children || <span className="ph-label">{label}</span>}
    </div>
  );
}

/* ---------- Corner registration ticks ---------- */
function CornerTicks({ color = 'var(--line-2)', size = 9, inset = 8 }) {
  const base = { position: 'absolute', pointerEvents: 'none' };
  const h = { width: size, height: 1, background: color };
  const v = { width: 1, height: size, background: color };
  return (
    <>
      <i style={{ ...base, top: inset, left: inset, ...h }} />
      <i style={{ ...base, top: inset, left: inset, ...v }} />
      <i style={{ ...base, top: inset, right: inset, ...h }} />
      <i style={{ ...base, top: inset, right: inset, ...v }} />
      <i style={{ ...base, bottom: inset, left: inset, ...h }} />
      <i style={{ ...base, bottom: inset, left: inset, ...v }} />
      <i style={{ ...base, bottom: inset, right: inset, ...h }} />
      <i style={{ ...base, bottom: inset, right: inset, ...v }} />
    </>
  );
}

/* ---------- Readout chip ---------- */
function Readout({ k, v, accent }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
      <span className="tag" style={{ fontSize: '0.6rem' }}>{k}</span>
      <span className="mono tabnum" style={{ fontSize: '1.05rem', fontWeight: 600,
            color: accent ? 'var(--accent)' : 'var(--ink)' }}>{v}</span>
    </div>
  );
}

/* ---------- Nav ---------- */
const NAV = [
  { id: 'platform',      label: 'Platform' },
  { id: 'collaboration', label: 'Collaboration' },
];

function Nav({ route, go }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const on = () => setScrolled(window.scrollY > 12);
    on(); window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, []);
  const onLink = (id) => (e) => { e.preventDefault(); setOpen(false); go(id); };

  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 100,
      borderBottom: '1px solid var(--line)',
      background: scrolled ? 'color-mix(in oklch, var(--bg) 82%, transparent)' : 'var(--bg)',
      backdropFilter: scrolled ? 'blur(14px) saturate(140%)' : 'none',
      WebkitBackdropFilter: scrolled ? 'blur(14px) saturate(140%)' : 'none',
      transition: 'background .3s var(--ease)',
    }}>
      <div className="wrap" style={{ display: 'flex', alignItems: 'center',
           justifyContent: 'space-between', height: 64, gap: 24 }}>
        <a href="#" onClick={onLink('home')} aria-label="Xaint home"><Logo /></a>

        <nav style={{ display: 'flex', alignItems: 'center', gap: 30 }} className="nav-links">
          {NAV.map(n => (
            <a key={n.id} href={'#' + n.id} onClick={onLink(n.id)}
               className="mono" style={{
                 fontSize: '0.74rem', letterSpacing: '0.1em',
                 color: route === n.id ? 'var(--accent)' : 'var(--ink-2)',
                 transition: 'color .2s', position: 'relative', paddingBlock: 6,
               }}
               onMouseEnter={e => e.currentTarget.style.color = 'var(--ink)'}
               onMouseLeave={e => e.currentTarget.style.color = route === n.id ? 'var(--accent)' : 'var(--ink-2)'}>
              {n.label}
            </a>
          ))}
        </nav>

        <button className="nav-burger" aria-label="Menu" onClick={() => setOpen(o => !o)}
          style={{ display: 'none', background: 'transparent', border: '1px solid var(--line-2)',
                   borderRadius: 2, width: 38, height: 34, cursor: 'pointer', color: 'var(--ink)' }}>
          <span style={{ display: 'block', width: 16, height: 1, background: 'currentColor',
                 margin: '0 auto', boxShadow: '0 -4px 0 currentColor, 0 4px 0 currentColor' }} />
        </button>
      </div>

      {open && (
        <div className="nav-mobile" style={{ borderTop: '1px solid var(--line)', padding: 'var(--gut)',
             display: 'flex', flexDirection: 'column', gap: 18, background: 'var(--bg)' }}>
          {NAV.map(n => (
            <a key={n.id} href={'#' + n.id} onClick={onLink(n.id)}
               className="mono" style={{ fontSize: '0.95rem', letterSpacing: '0.06em', color: 'var(--ink)' }}>
              {n.label}
            </a>
          ))}
        </div>
      )}
    </header>
  );
}

/* ---------- Platform availability glyphs ---------- */
function AppleGlyph({ s = 16 }) {
  return (
    <svg width={s} height={s} viewBox="0 0 24 24" aria-hidden="true" style={{ display: 'block' }}>
      <path fill="currentColor" d="M17.05 12.04c-.03-2.6 2.13-3.85 2.22-3.91-1.21-1.77-3.1-2.01-3.77-2.04-1.6-.16-3.13.94-3.94.94-.81 0-2.07-.92-3.4-.89-1.75.03-3.36 1.02-4.26 2.58-1.82 3.15-.47 7.81 1.31 10.37.87 1.25 1.9 2.66 3.26 2.61 1.31-.05 1.8-.85 3.39-.85 1.58 0 2.03.85 3.41.82 1.41-.02 2.3-1.28 3.16-2.54.99-1.45 1.4-2.86 1.42-2.93-.03-.01-2.72-1.04-2.75-4.13z" />
      <path fill="currentColor" d="M14.94 5.19c.72-.87 1.2-2.08 1.07-3.29-1.03.04-2.28.69-3.02 1.56-.66.77-1.24 2-1.08 3.18 1.15.09 2.32-.58 3.03-1.45z" />
    </svg>
  );
}
function AndroidGlyph({ s = 16 }) {
  return (
    <svg width={s} height={s} viewBox="0 0 24 24" aria-hidden="true" style={{ display: 'block' }}>
      <path fill="#3DDC84" d="M5 11a7 7 0 0 1 14 0z" />
      <line x1="7" y1="5.4" x2="8.6" y2="8" stroke="#3DDC84" strokeWidth="1" strokeLinecap="round" />
      <line x1="17" y1="5.4" x2="15.4" y2="8" stroke="#3DDC84" strokeWidth="1" strokeLinecap="round" />
      <circle cx="9.3" cy="9" r="0.85" fill="var(--bg-2)" />
      <circle cx="14.7" cy="9" r="0.85" fill="var(--bg-2)" />
    </svg>
  );
}
function WindowsGlyph({ s = 14 }) {
  return (
    <svg width={s} height={s} viewBox="0 0 24 24" aria-hidden="true" style={{ display: 'block' }}>
      <path fill="#3DA7E8" d="M3 5.4l8-1.1v7.2H3zM13 4l8-1.1V11h-8zM3 12.5h8v7.2l-8-1.1zM13 12.5h8v8.6l-8-1.1z" />
    </svg>
  );
}

/* ---------- Footer ---------- */
function Footer({ go }) {
  const onLink = (id) => (e) => { e.preventDefault(); go(id); };
  const { AppStoreBadge, GooglePlayBadge, QR } = window;
  const platforms = [
    { label: 'iOS', glyph: <AppleGlyph s={15} /> },
    { label: 'Android', glyph: <AndroidGlyph s={16} /> },
    { label: 'Windows', glyph: <WindowsGlyph s={14} /> },
  ];
  return (
    <footer style={{ borderTop: '1px solid var(--line)', background: 'var(--bg-2)' }}>
      <div className="wrap" style={{ paddingBlock: 'clamp(48px,7vw,80px)' }}>
        <div className="foot-dl" style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr',
             gap: 'clamp(32px,5vw,64px)', alignItems: 'center' }}>

          {/* Left — brand + slogan + verbiage */}
          <div className="foot-brand">
            <Logo />
            <div className="mono" style={{ marginTop: 22, display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{ width: 22, height: 1, background: 'var(--accent)' }} />
              <span style={{ fontSize: '0.82rem', letterSpacing: '0.42em', color: 'var(--accent)', fontWeight: 500 }}>KNOW&nbsp;FIRST</span>
            </div>
            <p className="mono" style={{ fontSize: '0.74rem', color: 'var(--ink-3)',
               lineHeight: 1.7, marginTop: 18, maxWidth: 300, letterSpacing: '0.04em' }}>
              Every maintenance need, from capture to invoice, in one flow. Maintenance that
              tells you first — and pays for itself.
            </p>
          </div>

          {/* Center — Get the app */}
          <div className="foot-getapp" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center' }}>
            <div className="tag" style={{ marginBottom: 16 }}>GET THE APP</div>
            <div className="store-row" style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center' }}>
              {AppStoreBadge ? <AppStoreBadge /> : null}
              {GooglePlayBadge ? <GooglePlayBadge /> : null}
            </div>
            <div style={{ display: 'flex', gap: 20, flexWrap: 'wrap', marginTop: 22, alignItems: 'center', justifyContent: 'center' }}>
              <span className="mono" style={{ fontSize: '0.72rem', letterSpacing: '0.06em', color: 'var(--ink-3)', textTransform: 'uppercase' }}>Available on</span>
              {platforms.map((p) => (
                <span key={p.label} className="mono" style={{ display: 'inline-flex', alignItems: 'center', gap: 8,
                  fontSize: '0.72rem', letterSpacing: '0.06em', color: 'var(--ink-2)', textTransform: 'uppercase', whiteSpace: 'nowrap' }}>
                  <span style={{ color: 'var(--ink)', display: 'inline-flex' }}>{p.glyph}</span>{p.label}
                </span>
              ))}
            </div>
          </div>

          {/* Right — QR */}
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 10 }}>
            <div style={{ padding: 9, border: '1px solid var(--line)', borderRadius: 8, background: 'var(--surface)' }}>
              {QR ? <QR size={104} /> : null}
            </div>
            <span className="mono" style={{ fontSize: '0.6rem', letterSpacing: '0.14em', color: 'var(--ink-3)' }}>SCAN TO DOWNLOAD</span>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ---------- Frozen footer bar (mirrors sticky header) ---------- */
function FooterBar({ go, route }) {
  const onLink = (id) => (e) => { e.preventDefault(); go(id); };
  const links = [['About', 'about'], ['Privacy', 'privacy'], ['Contact', 'contact']];
  return (
    <div className="footer-bar">
      <div className="wrap footer-bar-inner">
        <span className="fb-copy mono">© 2026 XAINT · <span style={{ color: 'var(--accent)' }}>KNOW FIRST</span></span>
        <nav className="fb-links">
          {links.map(([label, id]) => (
            <a key={id} href={'#' + id} onClick={onLink(id)}
               style={{ color: route === id ? 'var(--accent)' : 'var(--ink-2)', transition: 'color .2s' }}
               onMouseEnter={e => e.currentTarget.style.color = 'var(--ink)'}
               onMouseLeave={e => e.currentTarget.style.color = route === id ? 'var(--accent)' : 'var(--ink-2)'}>
              {label}
            </a>
          ))}
        </nav>
      </div>
    </div>
  );
}

Object.assign(window, {
  useReveal, Logo, SectionLabel, Btn, Ph, CornerTicks, Readout, Nav, Footer, FooterBar, NAV,
});
