// Shared UI: Nav, Footer, Logo, Reveal, Icons
const { useState, useEffect, useRef, useMemo } = React;

// ============ LOGO ============
function LogoMark({ color = '#1A2B3C', dot = '#00C9A7', size = 32 }) {
  return (
    <svg width={size} height={size * (56/56)} viewBox="0 0 56 56" aria-hidden>
      <rect width="56" height="56" rx="12" fill={color} />
      <g stroke="#fff" strokeWidth="2.5">
        <circle cx="21" cy="28" r="10" fill="none" />
        <path d="M28 28h15" strokeLinecap="round" />
        <path d="M36 28v6" strokeLinecap="round" />
        <path d="M41 28v3" strokeLinecap="round" />
      </g>
      <circle cx="21" cy="28" r="4" fill={dot} />
    </svg>
  );
}

function LogoWord({ variant = 'dark' }) {
  const stroke = variant === 'light' ? '#FFFFFF' : '#1A2B3C';
  const fill = variant === 'light' ? '#FFFFFF' : '#1A2B3C';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <svg width="40" height="40" viewBox="0 0 56 56" aria-hidden>
        <g stroke={stroke} strokeWidth="3" fill="none">
          <circle cx="21" cy="28" r="10" />
          <path d="M31 28h16" strokeLinecap="round" />
          <path d="M39 28v7" strokeLinecap="round" />
          <path d="M44 28v4" strokeLinecap="round" />
        </g>
        <circle cx="21" cy="28" r="4.5" fill="#00C9A7" />
      </svg>
      <span style={{ fontFamily: "'DM Sans', sans-serif", fontWeight: 400, fontSize: 24, letterSpacing: '-0.02em', color: fill }}>
        keynara
      </span>
    </div>
  );
}

// ============ ICONS ============
const Icon = {
  arrow: (p) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14M13 5l7 7-7 7"/></svg>,
  chevron: (p) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M6 9l6 6 6-6"/></svg>,
  send: (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M22 2L11 13"/><path d="M22 2l-7 20-4-9-9-4 20-7z"/></svg>,
  check: (p) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 6L9 17l-5-5"/></svg>,
  x: (p) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M18 6L6 18M6 6l12 12"/></svg>,
  plus: (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 5v14M5 12h14"/></svg>,
  minus: (p) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12h14"/></svg>,
  sparkle: (p) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 3l1.6 5.4L19 10l-5.4 1.6L12 17l-1.6-5.4L5 10l5.4-1.6L12 3z"/></svg>,
  map: (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 1 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>,
  euro: (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M4 10h12M4 14h12M18 6a7 7 0 1 0 0 12"/></svg>,
  bed: (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 18v-8h18v8M3 14h18M7 10V7h4v3"/></svg>,
  area: (p) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="3" width="18" height="18" rx="1"/><path d="M3 9h18M9 3v18"/></svg>,
  globe: (p) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c2.5 3 2.5 15 0 18M12 3c-2.5 3-2.5 15 0 18"/></svg>,
};

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

// ============ NAV ============
function Nav({ t, lang, setLang, page, setPage, onStartChat }) {
  const [scrolled, setScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const links = [
    { id: 'how', label: t.nav.how },
    { id: 'pricing', label: t.nav.pricing },
    { id: 'investors', label: t.nav.investors },
    { id: 'about', label: t.nav.about },
    { id: 'blog', label: t.nav.blog },
    { id: 'contact', label: t.nav.contact },
    { id: 'agent', label: t.nav.agentTool, highlight: true },
  ];

  return (
    <header style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 50,
      backdropFilter: scrolled ? 'saturate(180%) blur(14px)' : 'none',
      background: scrolled ? 'rgba(255,255,255,0.82)' : 'rgba(255,255,255,0)',
      borderBottom: scrolled ? '1px solid var(--line)' : '1px solid transparent',
      transition: 'all 200ms ease',
    }}>
      <div className="container" style={{ height: 72, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <a onClick={(e) => { e.preventDefault(); setPage('home'); }} href="#" aria-label="Keynara" style={{ display: 'flex', alignItems: 'center' }}>
          <LogoWord />
        </a>
        <nav className="nav-links" style={{ display: 'flex', alignItems: 'center', gap: 28 }}>
          {links.map(l => (
            l.highlight
              ? (
                <a
                  key={l.id}
                  href={`#${l.id}`}
                  onClick={(e) => { e.preventDefault(); setPage(l.id); }}
                  style={{
                    fontSize: 13, fontWeight: 700,
                    letterSpacing: '0.04em',
                    color: page === l.id ? 'white' : 'var(--navy)',
                    background: page === l.id ? 'var(--mint-dark)' : 'var(--mint)',
                    border: '2px solid var(--mint-dark)',
                    borderRadius: 999,
                    padding: '7px 16px',
                    transition: 'all 180ms',
                    whiteSpace: 'nowrap',
                  }}
                >{l.label}</a>
              ) : (
                <a
                  key={l.id}
                  href={`#${l.id}`}
                  onClick={(e) => { e.preventDefault(); setPage(l.id); }}
                  style={{
                    fontSize: 14, fontWeight: 500,
                    color: page === l.id ? 'var(--navy)' : 'var(--slate)',
                    borderBottom: page === l.id ? '1.5px solid var(--mint)' : '1.5px solid transparent',
                    paddingBottom: 2,
                    transition: 'color 180ms',
                  }}
                >{l.label}</a>
              )
          ))}
        </nav>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <LangToggle lang={lang} setLang={setLang} />
          <button className="btn btn--primary" onClick={onStartChat}>{t.nav.startChat} <Icon.arrow /></button>
          <button
            className="mobile-menu-btn"
            onClick={() => setMobileOpen(v => !v)}
            style={{ display: 'none', width: 40, height: 40, borderRadius: 8, background: 'var(--fog)', alignItems: 'center', justifyContent: 'center' }}
            aria-label="Menu"
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d={mobileOpen ? "M18 6L6 18M6 6l12 12" : "M3 6h18M3 12h18M3 18h18"}/></svg>
          </button>
        </div>
      </div>
      {mobileOpen && (
        <div style={{ background: 'white', borderTop: '1px solid var(--line)', padding: '16px 24px' }}>
          {links.map(l => (
            <a key={l.id} href={`#${l.id}`}
               onClick={(e) => { e.preventDefault(); setPage(l.id); setMobileOpen(false); }}
               style={{
                 display: 'block', padding: '12px 0',
                 borderBottom: '1px solid var(--line)',
                 fontWeight: l.highlight ? 600 : 500,
                 color: l.highlight ? 'var(--mint-dark)' : 'inherit',
               }}>{l.label}</a>
          ))}
        </div>
      )}
      <style>{`
        @media (max-width: 900px) {
          .nav-links { display: none !important; }
          .mobile-menu-btn { display: flex !important; }
        }
      `}</style>
    </header>
  );
}

function LangToggle({ lang, setLang }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center',
      background: 'var(--fog)', borderRadius: 999, padding: 3, gap: 2,
    }}>
      {['de', 'en'].map(l => (
        <button key={l}
          onClick={() => setLang(l)}
          style={{
            padding: '6px 12px',
            borderRadius: 999,
            fontSize: 12,
            fontWeight: 600,
            letterSpacing: '0.08em',
            textTransform: 'uppercase',
            color: lang === l ? 'var(--navy)' : 'var(--slate)',
            background: lang === l ? 'white' : 'transparent',
            boxShadow: lang === l ? '0 1px 4px rgba(26,43,60,0.08)' : 'none',
            transition: 'all 180ms',
          }}
        >{l}</button>
      ))}
    </div>
  );
}

// ============ FOOTER ============
function Footer({ t, setPage }) {
  const cols = [
    { title: t.footer.cols.product, links: [
      { k: 'how', label: t.footer.links.how },
      { k: 'pricing', label: t.footer.links.pricing },
      { k: 'investors', label: t.footer.links.investors },
      { k: 'contact', label: t.footer.links.api },
    ]},
    { title: t.footer.cols.company, links: [
      { k: 'about', label: t.footer.links.about },
      { k: 'about', label: t.footer.links.careers },
      { k: 'blog', label: t.footer.links.press },
      { k: 'contact', label: t.footer.links.contact },
    ]},
    { title: t.footer.cols.resources, links: [
      { k: 'blog', label: t.footer.links.blog },
      { k: 'contact', label: t.footer.links.help },
      { k: 'contact', label: t.footer.links.status },
      { k: 'about', label: t.footer.links.security },
    ]},
    { title: t.footer.cols.legal, links: [
      { k: 'contact', label: t.footer.links.imprint },
      { k: 'contact', label: t.footer.links.privacy },
      { k: 'contact', label: t.footer.links.terms },
      { k: 'contact', label: t.footer.links.cookies },
    ]},
  ];

  return (
    <footer style={{ background: 'var(--navy)', color: 'white', paddingTop: 96, paddingBottom: 40, marginTop: 0 }}>
      <div className="container">
        <NewsletterBlock t={t} />
        <div className="footer-grid" style={{
          display: 'grid',
          gridTemplateColumns: '1.4fr 1fr 1fr 1fr 1fr',
          gap: 48,
          paddingTop: 72,
          borderTop: '1px solid rgba(255,255,255,0.08)',
        }}>
          <div>
            <LogoWord variant="light" />
            <p style={{ marginTop: 20, color: 'rgba(255,255,255,0.6)', fontSize: 14, maxWidth: 280, lineHeight: 1.6 }}>
              {t.footer.tag}
            </p>
            <div style={{ marginTop: 24, display: 'flex', gap: 8 }}>
              {['Wien', 'Berlin', 'Milano'].map(c => (
                <span key={c} style={{
                  fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase',
                  padding: '4px 10px', borderRadius: 999,
                  background: 'rgba(255,255,255,0.06)', color: 'rgba(255,255,255,0.7)',
                }}>{c}</span>
              ))}
            </div>
          </div>
          {cols.map((col, i) => (
            <div key={i}>
              <div style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.5)', marginBottom: 20 }}>
                {col.title}
              </div>
              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
                {col.links.map((l, j) => (
                  <li key={j}>
                    <a href={`#${l.k}`}
                       onClick={(e) => { e.preventDefault(); setPage(l.k); window.scrollTo(0, 0); }}
                       style={{ color: 'rgba(255,255,255,0.78)', fontSize: 14, transition: 'color 180ms' }}
                       onMouseEnter={e => e.target.style.color = '#00C9A7'}
                       onMouseLeave={e => e.target.style.color = 'rgba(255,255,255,0.78)'}
                    >{l.label}</a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div style={{
          marginTop: 72, paddingTop: 32,
          borderTop: '1px solid rgba(255,255,255,0.08)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16,
        }}>
          <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.5)' }}>{t.footer.copy}</div>
          <div style={{ display: 'flex', gap: 24, fontSize: 13, color: 'rgba(255,255,255,0.5)' }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#00C9A7', boxShadow: '0 0 0 3px rgba(0,201,167,0.15)' }}></span>
              All systems operational
            </span>
            <span>DSGVO · GDPR · EU data</span>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 900px) {
          .footer-grid { grid-template-columns: 1fr 1fr !important; }
        }
        @media (max-width: 500px) {
          .footer-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </footer>
  );
}

function NewsletterBlock({ t }) {
  const [email, setEmail] = useState('');
  const [sent, setSent] = useState(false);
  return (
    <div style={{
      display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 48, alignItems: 'center',
      paddingBottom: 64,
    }} className="news-block">
      <div>
        <div className="h2" style={{ color: 'white' }}>{t.newsletter.title}</div>
        <p style={{ marginTop: 16, color: 'rgba(255,255,255,0.68)', fontSize: 17, lineHeight: 1.6, maxWidth: 520 }}>
          {t.newsletter.sub}
        </p>
      </div>
      <form onSubmit={(e) => { e.preventDefault(); if (email) setSent(true); }}>
        <div style={{
          display: 'flex', background: 'rgba(255,255,255,0.06)',
          border: '1px solid rgba(255,255,255,0.12)',
          borderRadius: 999, padding: 6, alignItems: 'center',
        }}>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder={t.newsletter.placeholder}
            disabled={sent}
            style={{
              flex: 1, padding: '14px 20px', background: 'transparent',
              border: 'none', color: 'white', fontSize: 15, fontFamily: 'inherit', outline: 'none',
            }}
          />
          <button type="submit" className="btn btn--primary" style={{ margin: 0 }}>
            {sent ? <><Icon.check /> OK</> : t.newsletter.cta}
          </button>
        </div>
        <p style={{ marginTop: 12, fontSize: 12, color: 'rgba(255,255,255,0.4)' }}>{t.newsletter.consent}</p>
      </form>
      <style>{`@media (max-width: 760px) { .news-block { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
}

Object.assign(window, { LogoMark, LogoWord, Icon, Reveal, Nav, Footer });
