// shared.jsx — logo, header, footer, router helpers

const { useState, useEffect, useMemo, useRef, createContext, useContext } = React;

// ── Context ──────────────────────────
const AppCtx = createContext(null);

function useApp() { return useContext(AppCtx); }

// ── SPA Link — real <a href> for crawlers + SPA navigation ──────────────────────────
function Link({ to, className, style, children, ...rest }) {
  const { go } = useApp();
  return (
    <a
      href={to}
      className={className}
      style={style}
      onClick={(e) => { e.preventDefault(); go(to); }}
      {...rest}
    >
      {children}
    </a>
  );
}

// ── Logo: the Natharia wordmark (SVG recreation) ──────────────────────────
function NatharialLogo({ height = 32, color = "currentColor", accent = "var(--accent)" }) {
  const w = height * 3.125;
  return (
    <svg height={height} width={w} viewBox="0 0 1000 320" fill="none" xmlns="http://www.w3.org/2000/svg" aria-label="Natharia">
      <g stroke={color} strokeWidth="5" fill="none" strokeLinecap="square">
        {/* N */}
        <line x1="60" y1="80" x2="60" y2="240" />
        <line x1="60" y1="80" x2="180" y2="240" />
        <line x1="180" y1="80" x2="180" y2="240" />
        {/* A */}
        <line x1="210" y1="240" x2="270" y2="80" />
        <line x1="270" y1="80" x2="330" y2="240" />
        <line x1="232" y1="190" x2="308" y2="190" />
        {/* T */}
        <line x1="360" y1="80" x2="450" y2="80" />
        <line x1="405" y1="80" x2="405" y2="240" />
        {/* H */}
        <line x1="480" y1="80" x2="480" y2="240" />
        <line x1="580" y1="80" x2="580" y2="240" />
        <line x1="480" y1="160" x2="580" y2="160" />
        {/* A */}
        <line x1="610" y1="240" x2="670" y2="80" />
        <line x1="670" y1="80" x2="730" y2="240" />
        <line x1="632" y1="190" x2="708" y2="190" />
        {/* R */}
        <line x1="760" y1="80" x2="760" y2="240" />
        <path d="M760 80 C 830 80, 840 160, 760 160" />
        <line x1="780" y1="160" x2="840" y2="240" />
        {/* I */}
        <line x1="870" y1="80" x2="870" y2="240" />
        {/* A */}
        <line x1="900" y1="240" x2="945" y2="105" />
        <line x1="945" y1="105" x2="975" y2="195" />
      </g>
      {/* Violet diagonal stroke from logo: under the 'A' of NA */}
      <line x1="60" y1="260" x2="940" y2="260" stroke={accent} strokeWidth="2.5" opacity="0.4" />
      <line x1="60" y1="260" x2="330" y2="260" stroke={accent} strokeWidth="2.5" />
      {/* The thick violet diagonal that sits inside the first A like the original */}
      <line x1="270" y1="80" x2="210" y2="240" stroke={accent} strokeWidth="6" />
    </svg>
  );
}

// Minimal icon mark
function NatharialMark({ size = 28 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 100 100" fill="none">
      <line x1="20" y1="20" x2="20" y2="80" stroke="currentColor" strokeWidth="3" />
      <line x1="20" y1="20" x2="80" y2="80" stroke="currentColor" strokeWidth="3" />
      <line x1="80" y1="20" x2="80" y2="80" stroke="currentColor" strokeWidth="3" />
      <line x1="50" y1="20" x2="35" y2="80" stroke="var(--accent)" strokeWidth="4" />
    </svg>
  );
}

// ── Header ─────────────────────────────────
function Header() {
  const { route, go, t } = useApp();
  return (
    <header className="hdr">
      <div className="hdr-inner">
        <Link to="/" style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <NatharialLogo height={34} />
          <span className="sparkle" style={{ marginLeft: 4 }}></span>
        </Link>
        <nav className="hdr-nav">
          <Link to="/blog" className={route === '/blog' || route.startsWith('/blog/') ? 'active' : ''}>{t.nav.blog}</Link>
          <Link to="/tools" className={route === '/tools' || route.startsWith('/tools/') ? 'active' : ''}>{t.nav.tools}</Link>
          <Link to="/field-guide" className={route === '/field-guide' ? 'active' : ''}>{t.nav.resource}</Link>
          <Link to="/about" className={route === '/about' ? 'active' : ''}>{t.nav.about}</Link>
        </nav>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <Link to="/newsletter" className="btn btn-accent">
            {t.subscribe} <span className="arr"></span>
          </Link>
        </div>
      </div>
    </header>
  );
}

// ── Footer ─────────────────────────────────
function Footer() {
  const { t, go } = useApp();
  return (
    <footer className="ftr">
      <div className="ftr-inner">
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr', gap: 48, alignItems: 'start' }}>
          <div>
            <NatharialLogo height={26} />
            <p style={{ color: 'var(--ink-50)', fontSize: 14, lineHeight: 1.6, marginTop: 20, maxWidth: 320 }}>
              {t.tagline}
            </p>
            <p className="mono" style={{ color: 'var(--ink-30)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', marginTop: 24 }}>
              {t.footer.independent} · Est. MMXXVI
            </p>
          </div>
          <div>
            <p className="mono" style={{ color: 'var(--ink-30)', fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', marginBottom: 16 }}>01 · Read</p>
            <ul style={{ listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 10 }}>
              <li><Link to="/blog" style={{ fontSize: 14, color: 'var(--ink-70)' }}>{t.nav.blog}</Link></li>
              <li><Link to="/tools" style={{ fontSize: 14, color: 'var(--ink-70)' }}>{t.nav.tools}</Link></li>
              <li><Link to="/field-guide" style={{ fontSize: 14, color: 'var(--ink-70)' }}>{t.nav.resource}</Link></li>
            </ul>
          </div>
          <div>
            <p className="mono" style={{ color: 'var(--ink-30)', fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', marginBottom: 16 }}>02 · Connect</p>
            <ul style={{ listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 10 }}>
              <li><Link to="/newsletter" style={{ fontSize: 14, color: 'var(--ink-70)' }}>{t.nav.newsletter}</Link></li>
              <li><a style={{ cursor: 'pointer', fontSize: 14, color: 'var(--ink-70)' }}>Twitter / X</a></li>
              <li><a href="/sitemap.xml" style={{ fontSize: 14, color: 'var(--ink-70)' }}>{t.footer.rss}</a></li>
            </ul>
          </div>
          <div>
            <p className="mono" style={{ color: 'var(--ink-30)', fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', marginBottom: 16 }}>03 · House</p>
            <ul style={{ listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 10 }}>
              <li><Link to="/about" style={{ fontSize: 14, color: 'var(--ink-70)' }}>{t.nav.about}</Link></li>
              <li><a style={{ cursor: 'pointer', fontSize: 14, color: 'var(--ink-70)' }}>{t.footer.colophon}</a></li>
              <li><a style={{ cursor: 'pointer', fontSize: 14, color: 'var(--ink-70)' }}>{t.footer.ethics}</a></li>
            </ul>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 24, marginTop: 40, flexWrap: 'wrap' }}>
          <Link to="/privacy-policy" className="mono" style={{ fontSize: 11, color: 'var(--ink-50)', letterSpacing: '0.1em' }}>{t.footer.privacy || 'Privacy Policy'}</Link>
          <span style={{ color: 'var(--ink-15)' }}>|</span>
          <Link to="/terms-of-service" className="mono" style={{ fontSize: 11, color: 'var(--ink-50)', letterSpacing: '0.1em' }}>{t.footer.terms || 'Terms of Service'}</Link>
          <span style={{ color: 'var(--ink-15)' }}>|</span>
          <Link to="/affiliate-disclosure" className="mono" style={{ fontSize: 11, color: 'var(--ink-50)', letterSpacing: '0.1em' }}>{t.footer.affiliate || 'Affiliate Disclosure'}</Link>
        </div>
        <div className="rule" style={{ margin: '60px 0 24px' }}></div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16 }}>
          <p className="mono" style={{ fontSize: 11, color: 'var(--ink-30)', letterSpacing: '0.1em' }}>
            © 2026 Natharia · {t.footer.rights}
          </p>
          <p className="mono" style={{ fontSize: 11, color: 'var(--ink-30)', letterSpacing: '0.1em' }}>
            Crafted in Switzerland · 47.3769°N 8.5417°E
          </p>
        </div>
      </div>
    </footer>
  );
}

// ── Ticker ─────────────────────────────────
function Ticker() {
  const items = ['Issue 28 · Live', 'Make vs Zapier · 12 min read', '4,217 readers this week', 'Wednesday dispatch', 'Tools reviewed: 147', 'Avg research: 9.4 hours/piece', 'No affiliate inflation', 'Reader-supported'];
  return (
    <div className="ticker">
      <div className="marquee-track">
        {[...items, ...items, ...items].map((it, i) => (
          <React.Fragment key={i}>
            <span style={{ margin: '0 40px' }}>{it}</span>
            <span className="dot"></span>
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

// ── Funnel event tracking ─────────────────────────────────
function getFunnelSessionId() {
  try {
    let sid = sessionStorage.getItem('_nf_sid');
    if (!sid) {
      sid = Math.random().toString(36).slice(2) + Date.now().toString(36);
      sessionStorage.setItem('_nf_sid', sid);
    }
    return sid;
  } catch (_) { return 'unknown'; }
}

function trackFunnelEvent(event_type, extra = {}) {
  try {
    fetch('/api/newsletter/subscribers', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        event_type,
        page_path: window.location.pathname,
        session_id: getFunnelSessionId(),
        ...extra,
      }),
    }).catch(() => {});
  } catch (_) {}
}

// ── Newsletter form ─────────────────────────────────
function NewsletterForm({ compact = false, source = 'inline' }) {
  const { t } = useApp();
  const [email, setEmail] = useState('');
  const [sent, setSent] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [emailTouched, setEmailTouched] = useState(false);
  const formRef = useRef(null);

  // Fire popup_shown when the form scrolls into view
  useEffect(() => {
    const el = formRef.current;
    if (!el) return;
    const io = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          trackFunnelEvent('popup_shown', { status_code: null });
          io.disconnect();
        }
      },
      { threshold: 0.5 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  const onEmailChange = (e) => {
    setEmail(e.target.value);
    if (!emailTouched && e.target.value.length > 0) {
      setEmailTouched(true);
      trackFunnelEvent('popup_email_entered');
    }
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!email || submitting) return;
    trackFunnelEvent('popup_submit_clicked');
    setSubmitting(true);
    setError('');
    try {
      const res = await fetch('/api/newsletter/subscribers', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email })
      });
      if (res.ok) {
        trackFunnelEvent('beehiiv_api_200');
        setSent(true);
      } else {
        trackFunnelEvent('beehiiv_api_error', { status_code: res.status });
        setError('Something went wrong — try again.');
      }
    } catch {
      trackFunnelEvent('beehiiv_api_error', { status_code: 0 });
      setError('Network error — try again.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div ref={formRef}>
      <form className="mail-row" onSubmit={onSubmit}>
        <input
          type="email"
          placeholder={t.placeholderEmail}
          value={email}
          onChange={onEmailChange}
          required
          disabled={submitting || sent}
        />
        <button type="submit" aria-label="Subscribe" disabled={submitting || sent}>
          {sent ? '✓ Subscribed' : submitting ? '...' : 'Join →'}
        </button>
      </form>
      {error && <p className="mono" style={{ fontSize: 11, color: '#c44', marginTop: 8, letterSpacing: '0.08em' }}>{error}</p>}
      {!compact && <p className="mono" style={{ fontSize: 11, color: 'var(--ink-30)', marginTop: 14, letterSpacing: '0.08em' }}>{t.joinLine}</p>}
    </div>
  );
}

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

// ── SEO helpers ─────────────────────────────────
function setMetaTag(name, content) {
  let el = document.querySelector(`meta[name="${name}"]`) || document.querySelector(`meta[property="${name}"]`);
  if (!el) {
    el = document.createElement('meta');
    if (name.startsWith('og:') || name.startsWith('article:')) {
      el.setAttribute('property', name);
    } else {
      el.setAttribute('name', name);
    }
    document.head.appendChild(el);
  }
  el.setAttribute('content', content);
}

function setCanonical(url) {
  let link = document.querySelector('link[rel="canonical"]');
  if (!link) { link = document.createElement('link'); link.rel = 'canonical'; document.head.appendChild(link); }
  link.href = url;
}

function setJsonLd(data) {
  let script = document.getElementById('json-ld');
  if (!script) { script = document.createElement('script'); script.id = 'json-ld'; script.type = 'application/ld+json'; document.head.appendChild(script); }
  script.textContent = JSON.stringify(data);
}

function clearJsonLd() {
  const el = document.getElementById('json-ld');
  if (el) el.remove();
}

Object.assign(window, { AppCtx, useApp, Link, NatharialLogo, NatharialMark, Header, Footer, Ticker, NewsletterForm, Reveal, setMetaTag, setCanonical, setJsonLd, clearJsonLd });
