// Shared UI components and helpers
const { useState, useEffect, useRef, useMemo } = React;

// ——— simple hash router ———
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);
  }, []);
  return [route, (r) => { window.location.hash = '#/' + r; }];
}

function NavLink({ to, children, activeRoute }) {
  const isActive = activeRoute === to || (to === 'home' && activeRoute === '');
  return (
    <a href={"#/" + to} className={isActive ? 'active' : ''}>{children}</a>
  );
}

function Logo({ white }) {
  return (
    <a href="#/home" className="logo">
      <img src="images/logo.png" alt="Little Smiles" style={{height: 42, width: 42, borderRadius: 10, display: 'block', flexShrink: 0}} />
      <span className="logo-text">Little Smiles</span>
    </a>
  );
}

function Nav({ route, overHero }) {
  const [solid, setSolid] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setSolid(window.scrollY > 40);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => { setMenuOpen(false); }, [route]);

  const showOverHero = overHero && !solid;

  return (
    <header className={`nav ${solid ? 'solid' : ''} ${showOverHero ? 'over-hero' : ''}`}>
      <div className="nav-inner">
        <Logo />
        <nav className={"nav-links " + (menuOpen ? 'open' : '')}>
          <NavLink to="home" activeRoute={route}>Home</NavLink>
          <NavLink to="work" activeRoute={route}>Our Work</NavLink>
          <NavLink to="involved" activeRoute={route}>Get Involved</NavLink>
          <NavLink to="safe" activeRoute={route}>Safe Space</NavLink>
          <a href="#/donate" className="nav-cta">Donate</a>
        </nav>
        <button className="hamburger" onClick={() => setMenuOpen(o => !o)} aria-label="Menu">
          <span></span>
        </button>
      </div>
    </header>
  );
}

function Footer() {
  const [email, setEmail] = useState('');
  const [sent, setSent] = useState(false);
  const submit = (e) => { e.preventDefault(); if (email.includes('@')) { setSent(true); setEmail(''); } };
  return (
    <footer className="footer">
      <div className="wrap">
        <div className="footer-grid">
          <div>
            <Logo white />
            <p className="footer-desc">Bringing joy, connection and opportunity to refugee and vulnerable children across London, through trusted community partners.</p>
            <form className="newsletter-form" onSubmit={submit}>
              <input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder={sent ? 'Thanks, you\u2019re on the list' : 'Email for occasional updates'} />
              <button type="submit">{sent ? 'Sent ✓' : 'Subscribe'}</button>
            </form>
          </div>
          <div>
            <h4>Charity</h4>
            <a href="#/work">Our Work</a>
            <a href="#/safe">Safe Space</a>
          </div>
          <div>
            <h4>Get Involved</h4>
            <a href="#/involved">Ways to help</a>
            <a href="#/volunteer">Volunteer</a>
            <a href="#/donate">Donate</a>
            <a href="mailto:umar.khan@littlesmiles.org.uk">Partner with us</a>
          </div>
          <div>
            <h4>Contact</h4>
            <a href="mailto:umar.khan@littlesmiles.org.uk">umar.khan@littlesmiles.org.uk</a>
            <span style={{display:'block',padding:'5px 0',fontSize:14}}>London, United Kingdom</span>
            <p style={{fontSize:13,color:'rgba(255,255,255,.55)',marginTop:14,lineHeight:1.6}}>
              Registered charity in England &amp; Wales.<br/>
              <span style={{color:'var(--amber)'}}>No. 1212909</span>
            </p>
          </div>
        </div>
        <div className="footer-bot">
          <span>© {new Date().getFullYear()} Little Smiles CIO. Made with care in London.</span>
          <span>
            <a href="#/privacy">Privacy</a> · <a href="#/safeguarding">Safeguarding</a> · <a href="#/accessibility">Accessibility</a>
          </span>
        </div>
      </div>
    </footer>
  );
}

// ——— counter that animates in view ———
function Counter({ to, suffix = '+', duration = 1400 }) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  const [started, setStarted] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const ob = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting && !started) setStarted(true); });
    }, { threshold: .3 });
    ob.observe(ref.current);
    return () => ob.disconnect();
  }, [started]);
  useEffect(() => {
    if (!started) return;
    let start = null;
    const step = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / duration);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(Math.round(to * eased));
      if (p < 1) requestAnimationFrame(step);
    };
    requestAnimationFrame(step);
  }, [started, to, duration]);
  return (
    <span ref={ref} className="stat-num">
      {val}<span className="stat-suffix">{suffix}</span>
    </span>
  );
}

// ——— reveal on scroll wrapper ———
function Reveal({ children, delay = 0, as: Tag = 'div', className = '', ...rest }) {
  const ref = useRef(null);
  const [show, setShow] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const ob = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { setTimeout(() => setShow(true), delay); ob.disconnect(); } });
    }, { threshold: .12 });
    ob.observe(ref.current);
    return () => ob.disconnect();
  }, [delay]);
  return <Tag ref={ref} className={`reveal ${show ? 'in' : ''} ${className}`} {...rest}>{children}</Tag>;
}

// ——— lightbox ———
function useLightbox(images) {
  const [idx, setIdx] = useState(-1);
  const open = (i) => setIdx(i);
  const close = () => setIdx(-1);
  const prev = () => setIdx(i => (i - 1 + images.length) % images.length);
  const next = () => setIdx(i => (i + 1) % images.length);
  useEffect(() => {
    if (idx < 0) return;
    const onKey = (e) => {
      if (e.key === 'Escape') close();
      if (e.key === 'ArrowLeft') prev();
      if (e.key === 'ArrowRight') next();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [idx]);
  const view = idx >= 0 ? (
    <div className="lb open" onClick={close}>
      <button className="lb-close" onClick={(e) => { e.stopPropagation(); close(); }} aria-label="Close">
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
      </button>
      <button className="lb-nav lb-prev" onClick={(e) => { e.stopPropagation(); prev(); }} aria-label="Previous">
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
      </button>
      <img src={images[idx]} onClick={(e) => e.stopPropagation()} alt="" />
      <button className="lb-nav lb-next" onClick={(e) => { e.stopPropagation(); next(); }} aria-label="Next">
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>
      </button>
    </div>
  ) : null;
  return { open, view };
}

// Image catalogue
const IMAGES = {
  heroSign: 'images/hero-umar-sign.jpg',
  bus: 'images/trip-bus.jpg',
  arts: 'images/arts-crafts-group.jpg',
  xmasCom: 'images/xmas-community.jpg',
  volGifts: 'images/vol-gifts.jpg',
  watercolour: 'images/watercolour.jpg',
  facePaint: 'images/face-paint.jpg',
  artwork: 'images/artwork-display.jpg',
  cafe: 'images/cafe-smiles.jpg',
  mentor: 'images/mentor-polaroid.jpg',
  tramp1: 'images/tramp-kids.jpg',
  trampFoam: 'images/tramp-foam.jpg',
  trampAction: 'images/tramp-action.jpg',
  trampExtra: 'images/tramp-extra.jpg',
  sessionOct: 'images/session-oct25.jpg',
  xmas2: 'images/xmas-2.jpg',
  xmas3: 'images/xmas-3.jpg',
  xmas4: 'images/xmas-4.jpg',
  xmas5: 'images/xmas-5.jpg',
  xmas6: 'images/xmas-6.jpg',
};
const ALL_IMAGES = Object.values(IMAGES);

function goToWork(section) {
  sessionStorage.setItem('workSection', section);
  window.location.hash = '#/work';
}

Object.assign(window, {
  useRoute, Nav, Footer, Logo, Counter, Reveal, useLightbox,
  IMAGES, ALL_IMAGES, goToWork
});
