/* Nav + Footer */

const { useState: useStateNF, useEffect: useEffectNF } = React;

const Nav = ({ current, onNavigate, onDonateClick }) => {
  const items = [
  { id: 'home', label: 'Home' },
  { id: 'issues', label: 'Solutions' },
  { id: 'about', label: 'About' },
  { id: 'events', label: 'Events' }];

  const [scrolled, setScrolled] = useStateNF(false);
  const [mobileOpen, setMobileOpen] = useStateNF(false);
  useEffectNF(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 100,
      background: scrolled ? 'rgba(255,255,255,0.88)' : 'rgba(255,255,255,0.72)',
      backdropFilter: 'saturate(180%) blur(18px)',
      WebkitBackdropFilter: 'saturate(180%) blur(18px)',
      borderBottom: scrolled ? '1px solid var(--divider)' : '1px solid transparent',
      transition: 'background 200ms var(--ease-standard), border-color 200ms var(--ease-standard)'
    }}>
      <div style={{
        maxWidth: 1160, margin: '0 auto',
        padding: '14px 32px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24
      }}>
        <a href="#home" className="clean"
        onClick={(e) => {e.preventDefault();onNavigate('home');}}
        style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <img src="assets/logo-color.png" alt="Chuck West for Pierce County Council, District Seven"
          style={{ height: 40, width: 'auto', display: 'block' }} />
        </a>

        <nav className="nav-links" style={{ display: 'flex', gap: 30, alignItems: 'center' }}>
          {items.map((it) => {
            const active = current === it.id;
            return (
              <a key={it.id} href={`#${it.id}`}
              className="clean nav-link"
              onClick={(e) => {e.preventDefault();onNavigate(it.id);}}
              style={{
                fontFamily: 'var(--font-sans)', fontSize: 14, fontWeight: 600,
                color: active ? 'var(--brand-primary)' : 'var(--color-ink-soft)',
                position: 'relative', padding: '6px 2px',
                letterSpacing: '0.01em',
                transition: 'color 120ms var(--ease-standard)'
              }}>
                {it.label}
                <span style={{
                  position: 'absolute', left: 0, right: 0, bottom: -1, height: 2,
                  background: active ? 'var(--color-gold-base)' : 'transparent',
                  transition: 'background 160ms var(--ease-standard)'
                }} />
              </a>);

          })}
          <Button
            variant="primary"
            onClick={() => onDonateClick ? onDonateClick() : onNavigate('donate')}
            style={{ padding: '10px 18px', fontSize: 14 }}>
            Donate
          </Button>
          <button
            className="nav-mobile-toggle"
            onClick={() => setMobileOpen(true)}
            aria-label="Open navigation"
            style={{
              background: 'none', border: '1px solid var(--divider)',
              borderRadius: 4, padding: '8px 10px', cursor: 'pointer',
              alignItems: 'center', justifyContent: 'center'
            }}>
            <svg width="20" height="14" viewBox="0 0 20 14" fill="none" aria-hidden="true">
              <path d="M0 1h20M0 7h20M0 13h20" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
            </svg>
          </button>
        </nav>
      </div>
      {mobileOpen && ReactDOM.createPortal(
        <div className="mobile-drawer" onClick={() => setMobileOpen(false)}>
          <button className="mobile-drawer-close" onClick={() => setMobileOpen(false)} aria-label="Close">×</button>
          {items.map((it) =>
          <a key={it.id} href={`#${it.id}`}
          className={current === it.id ? 'active' : ''}
          onClick={(e) => {e.preventDefault();setMobileOpen(false);onNavigate(it.id);}}>
              {it.label}
            </a>
          )}
          <a href="#donate" className={current === 'donate' ? 'active' : ''}
          onClick={(e) => {e.preventDefault();setMobileOpen(false); onDonateClick ? onDonateClick() : onNavigate('donate');}}
          style={{ color: 'var(--brand-primary)' }}>
            Donate &nbsp;›
          </a>
        </div>,
        document.body
      )}
    </header>);

};

const Footer = ({ onNavigate }) => {
  const [email, setEmail] = useStateNF('');
  const [ok, setOk] = useStateNF(false);
  const [err, setErr] = useStateNF('');
  const [honeypotN, setHoneypotN] = useStateNF('');
  const [openedAt, setOpenedAt] = useStateNF(0);
  useEffectNF(() => { setOpenedAt(Date.now()); }, []);
  const submit = async (e) => {
    e.preventDefault();
    if (honeypotN) { setOk(true); setEmail(''); setTimeout(() => setOk(false), 3200); return; }
    if (Date.now() - openedAt < 2000) { setOk(true); setEmail(''); setTimeout(() => setOk(false), 3200); return; }
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) { setErr('Please enter a valid email.'); return; }

    if (!window.supabaseClient) {
      setErr('Connection issue. Please try again.');
      return;
    }

    const { error } = await window.supabaseClient
      .from('newsletter_subscribers')
      .insert({ email: email.trim().toLowerCase() });

    // 23505 = unique constraint violation = already subscribed. Treat as success.
    if (error && error.code !== '23505') {
      console.error('[newsletter insert]', error);
      setErr('Something went wrong. Please try again.');
      return;
    }

    setErr('');
    setOk(true);
    setEmail('');
    setTimeout(() => setOk(false), 3200);
  };

  return (
    <footer style={{
      background: '#0B2A00', color: 'rgba(255,255,255,0.78)',
      padding: '88px 32px 36px',
      fontFamily: 'var(--font-sans)'
    }}>
      <div style={{ maxWidth: 1160, margin: '0 auto' }}>
        {/* Email signup strip */}
        <div className="footer-top">
          <div>
            <Eyebrow color="var(--color-gold-500)">Stay in touch</Eyebrow>
            <div style={{
              fontFamily: 'var(--font-display)', fontSize: 34, fontWeight: 700,
              color: '#fff', lineHeight: 1.15, letterSpacing: '-0.015em',
              margin: '10px 0 8px', maxWidth: '18ch'
            }}>
              One email a week. No noise.
            </div>
            <div style={{ fontFamily: 'var(--font-serif)', fontSize: 16, fontStyle: 'italic', color: 'rgba(255,255,255,0.7)', maxWidth: '44ch' }}>
              Where Chuck&rsquo;s going this week, what&rsquo;s on the ballot, and how Pierce County families can help.
            </div>
          </div>
          <form onSubmit={submit} style={{ display: 'grid', gap: 10 }}>
            <input
              type="text"
              name="website"
              tabIndex={-1}
              autoComplete="off"
              value={honeypotN}
              onChange={e => setHoneypotN(e.target.value)}
              aria-hidden="true"
              style={{
                position: 'absolute',
                left: '-9999px',
                width: 1,
                height: 1,
                opacity: 0,
                pointerEvents: 'none',
              }}
            />
            <div style={{ display: 'flex', gap: 8 }}>
              <input
                type="email" value={email} onChange={(e) => setEmail(e.target.value)}
                placeholder="your@email.com"
                style={{
                  flex: 1, padding: '14px 16px',
                  background: 'rgba(255,255,255,0.06)',
                  border: '1px solid rgba(255,255,255,0.18)',
                  color: '#fff', borderRadius: 4, fontSize: 15,
                  outline: 'none'
                }} />
              
              <Button variant="gold" type="submit" style={{ padding: '13px 20px' }}>Subscribe</Button>
            </div>
            {err && <div style={{ fontSize: 13, color: 'var(--color-gold-300)' }}>{err}</div>}
            {ok && <div style={{ fontSize: 13, color: 'var(--color-gold-300)' }}>✓ You're on the list. Talk soon.</div>}
          </form>
        </div>

        {/* Link grid */}
        <div className="footer-grid">
          <div>
            <img src="assets/logo-white.png" alt="Chuck West"
            style={{ height: 44, marginBottom: 14, opacity: 0.92 }} />
            <p style={{ fontSize: 13, lineHeight: 1.6, color: 'rgba(255,255,255,0.64)', maxWidth: '34ch', margin: 0 }}>For Pierce County Council, District 7.<br />34 years of service. One Pierce County.
            </p>
          </div>
          {[
          { head: 'Campaign', links: [
            { l: 'Solutions', id: 'issues' },
            { l: 'About Chuck', id: 'about' },
            { l: 'Events', id: 'events' }]
          },
          { head: 'Get Involved', links: [
            { l: 'Donate', id: 'donate' },
            { l: 'Volunteer', id: 'donate' },
            { l: 'Request a yard sign', id: 'donate' }]
          },
          { head: 'Contact', links: [
            { l: 'PO Box 856, Vaughn, WA 98394', id: null },
            { l: 'info@votechuckwest.com', id: null }]
          }].
          map((col, i) =>
          <div key={i}>
              <div style={{
              fontSize: 11, fontWeight: 700, letterSpacing: '0.18em',
              textTransform: 'uppercase', color: 'var(--color-gold-500)', marginBottom: 14
            }}>{col.head}</div>
              <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 10, fontSize: 14 }}>
                {col.links.map((lk, j) =>
              <li key={j}>
                    {lk.id ?
                <a href={`#${lk.id}`} className="clean"
                onClick={(e) => {e.preventDefault();onNavigate(lk.id);}}
                style={{ color: 'rgba(255,255,255,0.78)' }}>{lk.l}</a> :
                <span style={{ color: 'rgba(255,255,255,0.56)' }}>{lk.l}</span>}
                  </li>
              )}
              </ul>
            </div>
          )}
        </div>

        {/* Legal */}
        <div className="footer-legal" style={{
          paddingTop: 24, fontSize: 12,
          color: 'rgba(255,255,255,0.46)',
          display: 'flex', justifyContent: 'space-between',
          flexWrap: 'wrap', gap: 8
        }}>
          <div>Paid for by Friends of Chuck West (NP) | PO Box 856, Vaughn, WA 98394</div>
          <div>© 2026 Friends of Chuck West · All rights reserved.</div>
        </div>
      </div>
    </footer>);

};

Object.assign(window, { Nav, Footer });