// Shared UI primitives
const { useState, useEffect, useRef, useMemo } = React;

// Simple client router using hash
function useRoute() {
  const [route, setRoute] = useState(() => window.location.hash.replace('#/', '') || 'home');
  useEffect(() => {
    const onHash = () => {
      setRoute(window.location.hash.replace('#/', '') || 'home');
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  const go = (r) => { window.location.hash = '#/' + r; };
  return [route, go];
}

function Link({ to, children, className = '', style }) {
  const onClick = (e) => {
    e.preventDefault();
    window.location.hash = '#/' + to;
  };
  return (
    <a href={'#/' + to} onClick={onClick} className={className} style={style}>
      {children}
    </a>
  );
}

function Nav({ route }) {
  const [open, setOpen] = React.useState(false);
  const links = [
    { to: 'home', label: 'Home' },
    { to: 'organisations', label: 'For Organisations' },
    { to: 'professionals', label: 'For Professionals' },
    { to: 'circle', label: 'Transformation Circle' },
    { to: 'thesis', label: 'Thesis' },
    { to: 'articles', label: 'Insights' },
    { to: 'about', label: 'About' },
  ];
  const close = () => setOpen(false);
  return (
    <>
      <nav className="nav">
        <div className="container nav-inner">
          <Link to="home" className="brand" onClick={close}>
            <img src="assets/logo.png" alt="NRX Auaha" style={{height: 36, width: 'auto', display:'block'}}/>
            <div className="brand-text">
              <span className="brand-name">NRX Auaha</span>
              <span className="brand-sub">Ethical AI · Career</span>
            </div>
          </Link>
          <div className="nav-links">
            {links.map(l => (
              <Link key={l.to} to={l.to} className={route === l.to ? 'active' : ''}>{l.label}</Link>
            ))}
          </div>
          <div className="nav-cta">
            <Link to="contact" className="btn btn-primary" style={{padding: '10px 16px', fontSize: 13}} onClick={close}>
              Start a kōrero <span className="arrow">→</span>
            </Link>
            <button className="nav-hamburger" onClick={() => setOpen(o => !o)} aria-label="Menu">
              <span style={{transform: open ? 'rotate(45deg) translate(5px, 5px)' : 'none'}}/>
              <span style={{opacity: open ? 0 : 1}}/>
              <span style={{transform: open ? 'rotate(-45deg) translate(5px, -5px)' : 'none'}}/>
            </button>
          </div>
        </div>
      </nav>
      <div className={'nav-mobile' + (open ? ' open' : '')}>
        {links.map(l => (
          <Link key={l.to} to={l.to} className={route === l.to ? 'active' : ''} onClick={close}>{l.label}</Link>
        ))}
      </div>
    </>
  );
}

function Footer() {
  return (
    <footer>
      <div className="container">
        <div className="footer-grid">
          <div className="footer-tagline">
            <div className="display" style={{fontSize: 'clamp(2rem, 4vw, 3.5rem)', marginBottom: 24, maxWidth: '14ch'}}>
              Blending <em>tradition</em> and technology for tomorrow.
            </div>
            <Link to="contact" className="btn btn-accent">
              Start a kōrero <span className="arrow">→</span>
            </Link>
          </div>
          <div>
            <div className="label" style={{marginBottom: 16}}>Services</div>
            <div style={{display:'flex', flexDirection:'column', gap:8, fontSize: 14}}>
              <Link to="organisations">For Organisations</Link>
              <Link to="professionals">For Professionals</Link>
              <Link to="circle">Transformation Circle</Link>
            </div>
          </div>
          <div>
            <div className="label" style={{marginBottom: 16}}>Studio</div>
            <div style={{display:'flex', flexDirection:'column', gap:8, fontSize: 14}}>
              <Link to="about">About</Link>
              <Link to="thesis">Thesis</Link>
              <Link to="articles">Insights</Link>
              <Link to="contact">Contact</Link>
              <a href="#">Newsletter</a>
            </div>
          </div>
          <div>
            <div className="label" style={{marginBottom: 16}}>Newsletter</div>
            <p style={{fontSize: 14, color: 'var(--ink-2)', marginBottom: 16}}>
              Monthly notes on ethical AI, career transitions, and the slow work of change.
            </p>
            <FooterNewsletter />
          </div>
        </div>

        <div className="hair" style={{marginBottom: 24}}/>
        <div className="footer-bottom">
          <div>© 2026 NRX Auaha · Aotearoa New Zealand</div>
          <div>Ngā mihi nui · Thank you for visiting</div>
        </div>
      </div>
    </footer>
  );
}

// Bilingual headline — two lines, te reo + english
function Bilingual({ mi, en, size = 'clamp(3rem, 7vw, 6rem)' }) {
  return (
    <div>
      <div className="display" style={{fontSize: size, fontStyle:'italic', color:'var(--accent)'}}>{mi}</div>
      <div className="display" style={{fontSize: size, marginTop: 4}}>{en}</div>
    </div>
  );
}

// Marquee of values
function ValuesMarquee() {
  const words = ['Whakapapa', 'Connection', 'Tika', 'Integrity', 'Manaakitanga', 'Care', 'Mana', 'Respect', 'Aroha', 'Love in the work'];
  const items = [...words, ...words];
  return (
    <div className="marquee">
      <div className="marquee-track">
        {items.map((w, i) => (
          <React.Fragment key={i}>
            <span>{w}</span>
            <span className="dot">✦</span>
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

// Placeholder image
function Ph({ label, ratio = '4/3', ix, style }) {
  return (
    <div className="ph" style={{aspectRatio: ratio, ...style}}>
      {ix && <span className="ph-ix">[{ix}]</span>}
      <span className="ph-cap">{label}</span>
    </div>
  );
}

// Arrow glyph
const Arrow = ({ rotate = -45 }) => (
  <svg width="14" height="14" viewBox="0 0 14 14" style={{transform: `rotate(${rotate}deg)`, transition:'transform .2s'}}>
    <path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);

function FooterNewsletter() {
  const [email, setEmail] = React.useState('');
  const [done, setDone] = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setErr('');
    try {
      const res = await fetch('/api/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, audience: 'Both', source: 'footer' }),
      });
      const data = await res.json();
      if (data.success) {
        setDone(true);
      } else {
        setErr(data.error || 'Something went wrong.');
      }
    } catch (e) {
      setErr('Could not subscribe. Please try again.');
    }
    setLoading(false);
  };

  if (done) return (
    <p style={{fontSize: 13, color: 'var(--ink-2)'}}>Ngā mihi — you're on the list.</p>
  );

  return (
    <>
      <form onSubmit={handleSubmit} style={{display:'flex', gap:0, border:'1px solid var(--hair)', borderRadius: 999, padding: 4, background:'var(--bg-2)'}}>
        <input
          type="email"
          placeholder="you@kaimahi.co"
          required
          value={email}
          onChange={e => setEmail(e.target.value)}
          style={{flex:1, border:'none', background:'transparent', padding:'8px 14px', fontFamily:'var(--f-body)', fontSize: 13, color: 'var(--ink)', outline:'none'}}
        />
        <button type="submit" disabled={loading} className="btn btn-primary" style={{padding: '8px 14px', fontSize: 12, opacity: loading ? 0.7 : 1}}>
          {loading ? '…' : 'Subscribe'}
        </button>
      </form>
      {err && <p style={{fontSize: 12, color: 'var(--rust)', marginTop: 8}}>{err}</p>}
    </>
  );
}

Object.assign(window, { useRoute, Link, Nav, Footer, Bilingual, ValuesMarquee, Ph, Arrow, FooterNewsletter });
