// Shared components: Nav, Footer, Reveal, Icons, Router hooks

const { useState, useEffect, useRef, useCallback, useMemo } = React;

// --- Hash router ---
function useHashRoute() {
  const [route, setRoute] = useState(() => window.location.hash.slice(1) || '/');
  useEffect(() => {
    const onHash = () => {
      setRoute(window.location.hash.slice(1) || '/');
      window.scrollTo({ top: 0, behavior: 'auto' });
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return route;
}

function navigate(path) {
  window.location.hash = path;
}

function Link({ to, children, className = '', onClick, ...rest }) {
  const route = useHashRoute();
  const active = route === to || (to !== '/' && route.startsWith(to));
  return (
    <a
      href={`#${to}`}
      className={`${className} ${active ? 'active' : ''}`}
      onClick={(e) => { if (onClick) onClick(e); }}
      {...rest}
    >
      {children}
    </a>
  );
}

// --- Pixel heart ---
function PixelHeart({ style, className = '' }) {
  return <span className={`pixel-heart ${className}`} style={style} aria-hidden="true" />;
}

// --- Floating hearts background ---
function FloatingHearts({ count = 6 }) {
  const positions = useMemo(() => Array.from({ length: count }).map((_, i) => ({
    left: (i * 17 + 10) % 90 + '%',
    top: (i * 23 + 5) % 80 + '%',
    delay: (i * 0.7) + 's',
    scale: 0.6 + ((i * 13) % 7) / 10,
    color: i % 3 === 0 ? '#F472B6' : i % 3 === 1 ? '#FCD34D' : '#C4B5FD',
  })), [count]);
  return (
    <>
      {positions.map((p, i) => (
        <span
          key={i}
          className="float-heart"
          aria-hidden="true"
          style={{
            left: p.left, top: p.top,
            animationDelay: p.delay,
            transform: `scale(${p.scale})`,
            color: p.color,
          }}
        >
          {i % 2 === 0
            ? <PixelHeart style={{ width: 28, height: 24 }} />
            : <Sparkle size={24} />}
        </span>
      ))}
    </>
  );
}

function Sparkle({ size = 20, color = 'currentColor' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={color} aria-hidden="true">
      <path d="M12 0 L14 10 L24 12 L14 14 L12 24 L10 14 L0 12 L10 10 Z" />
    </svg>
  );
}

// --- Reveal on scroll ---
function Reveal({ children, delay = 0, className = '' }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setVisible(true); io.disconnect(); }
    }, { threshold: 0.1 });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return (
    <div ref={ref} className={`reveal ${visible ? 'in' : ''} ${className}`} style={{ transitionDelay: `${delay}ms` }}>
      {children}
    </div>
  );
}

// --- Global live counter ---
function useLiftedCounter(start = 2848) {
  const [count, setCount] = useState(start);
  useEffect(() => {
    let mounted = true;
    const tick = () => {
      if (!mounted) return;
      setCount(c => c + 1);
      setTimeout(tick, 3500 + Math.random() * 4000);
    };
    const t = setTimeout(tick, 2500);
    return () => { mounted = false; clearTimeout(t); };
  }, []);
  return count;
}

// --- Nav ---
function Nav() {
  const [mobileOpen, setMobileOpen] = useState(false);
  const close = () => setMobileOpen(false);
  return (
    <>
      <nav className="nav" aria-label="Primary">
        <div className="nav-inner">
          <Link to="/" className="nav-logo" aria-label="Unspoken home">
            <PixelHeart />
            unspoken
          </Link>
          <div className="nav-links" role="navigation">
            <Link to="/" className="nav-link">Home</Link>
            <Link to="/features" className="nav-link">Features</Link>
            <Link to="/pricing" className="nav-link">Pricing</Link>
            <Link to="/blog" className="nav-link">Blog</Link>
            <Link to="/about" className="nav-link">About</Link>
            <Link to="/contact" className="nav-link">Contact</Link>
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <a href="#/pricing" className="btn btn-primary nav-cta nav-cta-desktop" aria-label="Start free trial">
              <PixelHeart /> Start Free Trial
            </a>
            <button
              className="nav-hamburger"
              aria-label="Open menu"
              aria-expanded={mobileOpen}
              onClick={() => setMobileOpen(true)}
            >
              <span></span>
            </button>
          </div>
        </div>
      </nav>
      <div className={`mobile-menu ${mobileOpen ? 'open' : ''}`} aria-hidden={!mobileOpen}>
        <div className="mobile-menu-header">
          <Link to="/" className="nav-logo" style={{ color: 'white' }} onClick={close}>
            <PixelHeart /> unspoken
          </Link>
          <button className="mobile-menu-close" onClick={close} aria-label="Close menu">×</button>
        </div>
        <div className="mobile-menu-links">
          <Link to="/" className="mobile-menu-link" onClick={close}>Home</Link>
          <Link to="/features" className="mobile-menu-link" onClick={close}>Features</Link>
          <Link to="/pricing" className="mobile-menu-link" onClick={close}>Pricing</Link>
          <Link to="/blog" className="mobile-menu-link" onClick={close}>Blog</Link>
          <Link to="/about" className="mobile-menu-link" onClick={close}>About</Link>
          <Link to="/contact" className="mobile-menu-link" onClick={close}>Contact</Link>
        </div>
        <div className="mobile-menu-cta">
          <a href="#/pricing" className="btn btn-primary" onClick={close} style={{ width: '100%' }}>
            <PixelHeart /> Start Free Trial
          </a>
        </div>
      </div>
    </>
  );
}

// --- Footer ---
function Footer() {
  const count = useLiftedCounter(2848);
  return (
    <footer className="footer" role="contentinfo">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="footer-logo"><PixelHeart /> unspoken</div>
            <div className="footer-tag">for right where you are.</div>
            <div className="footer-socials">
              <a href="#" className="footer-social" aria-label="TikTok">♪</a>
              <a href="#" className="footer-social" aria-label="Instagram">◉</a>
              <a href="#" className="footer-social" aria-label="Email">✉</a>
            </div>
          </div>
          <div className="footer-col">
            <h4>Product</h4>
            <ul>
              <li><Link to="/features">Features</Link></li>
              <li><Link to="/pricing">Pricing</Link></li>
              <li><Link to="/#prayer-wall">Prayer Wall</Link></li>
              <li><Link to="/#plans">Prayer Plans</Link></li>
              <li><Link to="/#love-letter">Love Letter</Link></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Company</h4>
            <ul>
              <li><Link to="/about">About</Link></li>
              <li><Link to="/blog">Blog</Link></li>
              <li><Link to="/contact">Contact</Link></li>
              <li><a href="#">Privacy</a></li>
              <li><a href="#">Terms</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Get the app</h4>
            <ul>
              <li><a href="#">Download on iOS</a></li>
              <li><a href="#">Get it on Android</a></li>
              <li><Link to="/contact">Press inquiries</Link></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <div>© 2026 Soleo Technologies · built with prayer and caffeine in austin, tx</div>
          <div className="footer-counter">
            <span className="live-dot" style={{ width: 8, height: 8, borderRadius: '50%', background: '#FCD34D', display: 'inline-block' }}></span>
            <strong>{count.toLocaleString()}</strong> prayers lifted today
          </div>
        </div>
      </div>
    </footer>
  );
}

// --- Phone mockup ---
function PhoneMockup({ mood = 0 }) {
  const moods = [
    { emoji: '💭', label: 'ANXIOUS', color: 'linear-gradient(165deg, #DBEAFE, #93C5FD)' },
    { emoji: '💧', label: 'SAD', color: 'linear-gradient(165deg, #DBEAFE, #60A5FA)' },
    { emoji: '🔥', label: 'ANGRY', color: 'linear-gradient(165deg, #FECACA, #FB7185)' },
    { emoji: '☺️', label: 'LONELY', color: 'linear-gradient(165deg, #FEF3C7, #FCD34D)' },
  ];
  const active = mood % moods.length;
  return (
    <div className="phone" role="img" aria-label="Unspoken app preview showing mood check and today's prayer">
      <div className="phone-screen">
        <div className="phone-notch"></div>
        <div className="phone-status">
          <span>9:41</span>
          <span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
            <span style={{ fontSize: 10 }}>●●●</span>
            <span>◩</span>
          </span>
        </div>
        <div style={{ padding: '8px 20px 0' }}>
          <div style={{ fontSize: 13, fontWeight: 800, letterSpacing: '0.14em', color: 'rgba(255,255,255,0.7)', textTransform: 'uppercase' }}>Tuesday · 9:41 am</div>
          <h3 style={{ color: 'white', fontSize: 26, fontWeight: 900, marginTop: 4 }}>mood check?</h3>
          <div style={{ display: 'flex', gap: 10, marginTop: 16, overflow: 'hidden' }}>
            {moods.map((m, i) => (
              <div key={i} style={{ flex: '0 0 auto', textAlign: 'center', opacity: i === active ? 1 : 0.55, transform: i === active ? 'scale(1.05)' : 'scale(1)', transition: 'all 0.4s' }}>
                <div style={{
                  width: 62, height: 62, borderRadius: '50%',
                  background: m.color,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 28,
                  boxShadow: '0 4px 0 rgba(0,0,0,0.2)',
                  border: '2px solid white',
                }}>{m.emoji}</div>
                <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: '0.1em', color: 'white', marginTop: 6 }}>{m.label}</div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ padding: '20px 16px 0' }}>
          <div style={{
            background: 'linear-gradient(165deg, rgba(76,29,149,0.8), rgba(30,27,75,0.95))',
            borderRadius: 18, padding: 20,
            border: '2px solid rgba(255,255,255,0.1)',
            boxShadow: '0 6px 0 rgba(0,0,0,0.25)',
          }}>
            <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: '0.16em', color: 'white', textTransform: 'uppercase' }}>Today's Prayer</div>
            <div style={{ fontFamily: 'Fraunces, serif', fontStyle: 'italic', color: '#F5F3FF', fontSize: 17, lineHeight: 1.3, marginTop: 8, fontWeight: 500 }}>
              for right where you are
            </div>
            <div style={{
              marginTop: 14,
              padding: '10px 14px',
              background: 'linear-gradient(180deg, #F472B6, #FB7185)',
              borderRadius: 12,
              color: 'white', fontSize: 13, fontWeight: 800, letterSpacing: '0.12em',
              textAlign: 'center', textTransform: 'uppercase',
              boxShadow: '0 3px 0 #9d174d',
              border: '1.5px solid rgba(255,255,255,0.3)',
            }}>
              <PixelHeart style={{ width: 11, height: 10, marginRight: 6, display: 'inline-block' }} /> pray now
            </div>
            <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.5)', marginTop: 10, textAlign: 'center', fontWeight: 500 }}>3 min · read or listen</div>
          </div>
        </div>
        <div style={{ padding: '14px 16px' }}>
          <div style={{
            background: 'linear-gradient(135deg, #2e1065, #4c1d95 60%, #7c3aed)',
            borderRadius: 16, padding: 14,
            display: 'flex', gap: 12, alignItems: 'center',
            border: '2px solid rgba(244,114,182,0.3)',
          }}>
            <div style={{
              width: 40, height: 40, borderRadius: 10,
              background: 'linear-gradient(180deg, #F472B6, #9d174d)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 18,
              border: '1.5px solid rgba(255,255,255,0.25)',
            }}>✉</div>
            <div>
              <div style={{ fontSize: 12, fontWeight: 900, color: 'white', lineHeight: 1.1 }}>LOVE LETTER FROM GOD</div>
              <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.7)', marginTop: 2 }}>a note written just for you today</div>
            </div>
          </div>
        </div>
        {/* Tab bar */}
        <div style={{
          marginTop: 'auto',
          background: 'rgba(46, 16, 101, 0.8)',
          borderTop: '1px solid rgba(255,255,255,0.1)',
          padding: '10px 12px 16px',
          display: 'flex', justifyContent: 'space-around',
          backdropFilter: 'blur(10px)',
        }}>
          {['🏠 home', '✨ explore', '♡ wall', '◉ groups', '☺ you'].map((l, i) => (
            <div key={i} style={{ fontSize: 9, color: i === 0 ? '#FCD34D' : 'rgba(255,255,255,0.55)', fontWeight: 700, letterSpacing: '0.04em' }}>{l}</div>
          ))}
        </div>
      </div>
    </div>
  );
}

// --- CTA block (used across pages) ---
function CTABlock({ title = "try unspoken free for 7 days.", sub = "one price. everything unlocked. cancel anytime." }) {
  return (
    <section style={{
      padding: '96px 0',
      background: 'linear-gradient(165deg, #4c1d95 0%, #7C3AED 50%, #F472B6 150%)',
      color: 'white', textAlign: 'center',
      position: 'relative', overflow: 'hidden',
    }}>
      <FloatingHearts count={8} />
      <div className="container" style={{ position: 'relative' }}>
        <h2 style={{ fontSize: 'clamp(36px, 5vw, 64px)', letterSpacing: '-0.035em', lineHeight: 1 }}>
          {title.split('.').map((part, i, arr) => (
            <React.Fragment key={i}>
              {i > 0 && <>.<br /></>}
              {i === 0 ? <>{part}</> : <em style={{ fontFamily: 'Fraunces, serif', fontStyle: 'italic', fontWeight: 500, color: '#FCD34D' }}>{part}</em>}
            </React.Fragment>
          ))}
        </h2>
        <p style={{ marginTop: 20, fontSize: 19, color: 'rgba(255,255,255,0.85)', maxWidth: 560, margin: '20px auto 0' }}>{sub}</p>
        <div style={{ marginTop: 32 }}>
          <a href="#/pricing" className="btn btn-primary" style={{ fontSize: 16, padding: '18px 32px' }}>
            <PixelHeart /> Start Praying — Free For 7 Days
          </a>
        </div>
      </div>
    </section>
  );
}

// Export globally
Object.assign(window, {
  useHashRoute, navigate, Link,
  PixelHeart, Sparkle, FloatingHearts, Reveal,
  useLiftedCounter, Nav, Footer, PhoneMockup, CTABlock,
});
