// Shared shell: logo, nav, footer
const { useEffect, useState } = React;

function ScrambleWordmark() {
  const ref = React.useRef(null);

  const handleHover = () => {
    if (!window.gsap || !ref.current) return;
    const chars = Array.from(ref.current.querySelectorAll('.wm-char'));
    const cursor = ref.current.querySelector('.wm-cursor');

    gsap.killTweensOf([...chars, cursor]);

    const tl = gsap.timeline();

    // show cursor
    tl.set(cursor, { autoAlpha: 1 });

    // delete right → left (backspace feel)
    tl.to([...chars].reverse(), {
      autoAlpha: 0,
      duration: 0.001,
      stagger: 0.045,
    });

    tl.to({}, { duration: 0.12 });

    // type left → right
    chars.forEach(char => {
      tl.set(char, { autoAlpha: 1 });
      tl.to({}, { duration: 0.075 });
    });

    // cursor blinks then disappears
    tl.to(cursor, { autoAlpha: 0, duration: 0.28, repeat: 5, yoyo: true, ease: 'steps(1)' })
      .set(cursor, { autoAlpha: 0 });
  };

  return (
    <div
      ref={ref}
      className="display footer-mark"
      onMouseEnter={handleHover}
      style={{
        fontSize: 'clamp(48px, 10vw, 180px)',
        lineHeight: 0.9,
        letterSpacing: '-0.04em',
        marginBottom: 80,
        color: 'var(--ink)',
        cursor: 'default',
        userSelect: 'none',
      }}
    >
      {'ATOM.FORGE'.split('').map((c, i) => (
        <span key={i} className="wm-char" style={{ color: c === '.' ? 'var(--crimson)' : 'inherit', display: 'inline-block' }}>
          {c}
        </span>
      ))}
      <span className="wm-cursor" style={{
        display: 'inline-block',
        width: '0.055em',
        minWidth: 5,
        height: '0.82em',
        background: 'var(--crimson)',
        verticalAlign: 'top',
        position: 'relative',
        top: '11%',
        marginLeft: '0.04em',
        visibility: 'hidden',
      }} />
    </div>
  );
}

function HammerLogo({ size = 30, color = 'currentColor' }) {
  // Delegates to the vectorized founder's logo
  if (window.AtomLogo) return <AtomLogo size={size * 0.85} color={color} />;
  return <span style={{ width: size, height: size, display: 'inline-block', background: color }} />;
}

function LogoMark({ size = 30 }) { return <HammerLogo size={size} />; }

function Nav({ page, setPage }) {
  const t = useT();
  const [open, setOpen] = React.useState(false);
  const links = [
    ['home', t('nav.home')],
    ['servicos', t('nav.servicos')],
    ['industrias', t('nav.industrias')],
    ['insights', t('nav.insights')],
    ['carreiras', t('nav.carreiras')],
    ['sobre', t('nav.sobre')],
    ['acessibilidade', t('footer.accessibility')],
  ];
  const go = (id) => { setPage(id); setOpen(false); };

  React.useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  return (
    <>
      <nav className="nav">
        <div className="shell-wide nav-inner">
          <a className="logo" onClick={(e) => { e.preventDefault(); go('home'); }} href="#home">
            <HammerLogo />
            <span>ATOM FORGE</span>
          </a>
          <div className="nav-links">
            {links.map(([id, label]) => (
              <a key={id} href={`#${id}`}
                 onClick={(e) => { e.preventDefault(); go(id); }}
                 className={`nav-link ${page === id ? 'active' : ''}`}>
                {label}
              </a>
            ))}
          </div>
          <a href="#contato" onClick={(e) => { e.preventDefault(); go('contato'); }} className="nav-cta nav-cta-desktop">
            {t('nav.cta')}
            <svg className="arrow" viewBox="0 0 14 14" fill="none" width="14" height="14"><path d="M3 11L11 3M11 3H5M11 3V9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
          </a>
          <button className="nav-burger" onClick={() => setOpen(o => !o)} aria-label="Menu">
            <span className={open ? 'burger-x' : ''}/>
            <span className={open ? 'burger-x' : ''}/>
          </button>
        </div>
      </nav>

      {/* Mobile overlay */}
      {open && (
        <div className="nav-mobile-overlay" onClick={() => setOpen(false)}>
          <div className="nav-mobile-panel" onClick={e => e.stopPropagation()}>
            {links.map(([id, label]) => (
              <a key={id} href={`#${id}`}
                 onClick={(e) => { e.preventDefault(); go(id); }}
                 className={`nav-mobile-link ${page === id ? 'active' : ''}`}>
                {label}
              </a>
            ))}
            <a href="#contato" onClick={(e) => { e.preventDefault(); go('contato'); }} className="btn btn-primary" style={{ marginTop: 8, justifyContent: 'center' }}>
              {t('nav.cta')}
              <svg viewBox="0 0 14 14" fill="none" width="14" height="14"><path d="M3 11L11 3M11 3H5M11 3V9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
            </a>
          </div>
        </div>
      )}
    </>
  );
}

function Footer({ setPage }) {
  const t = useT();
  const { lang, setLang } = useLang();

  const col = (title, items) => (
    <div>
      <div className="eyebrow" style={{ marginBottom: 16 }}>{title}</div>
      <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map(([id, label]) => (
          <li key={label}>
            <a href={`#${id}`} onClick={(e) => { e.preventDefault(); if (id) setPage(id); }} style={{ fontSize: 14 }}>{label}</a>
          </li>
        ))}
      </ul>
    </div>
  );

  return (
    <footer className="footer">
      <div className="shell-wide">
        <ScrambleWordmark />

        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr 1fr', gap: 48, marginBottom: 80 }} className="footer-grid">
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
              <HammerLogo size={32} />
              <span style={{ fontFamily: 'var(--display)', fontSize: 18, fontWeight: 700, letterSpacing: '-0.01em' }}>ATOM FORGE</span>
            </div>
            <p style={{ fontSize: 15, opacity: 0.7, lineHeight: 1.55, maxWidth: 320, margin: 0 }}>
              {t('footer.tagline')}
            </p>
            <div style={{ marginTop: 28, display: 'none', gap: 8 }}>
              {['Linkedin', 'Github', 'Dribbble', 'Instagram'].map(s => (
                <a key={s} href="#" className="social-pill" style={{
                  width: 38, height: 38, borderRadius: '50%',
                  border: '1px solid var(--line)',
                  display: 'grid', placeItems: 'center',
                  fontFamily: 'var(--mono)', fontSize: 11,
                  transition: 'all 0.25s'
                }}>{s[0]}</a>
              ))}
            </div>
          </div>
          {col(t('footer.nav_col'), [
            ['servicos', t('footer.nav1')],
            ['industrias', t('footer.nav2')],
            ['insights', t('nav.insights')],
            ['carreiras', t('footer.nav4')],
            ['sobre', t('footer.nav5')],
            ['contato', t('footer.nav6')],
            ['acessibilidade', t('footer.accessibility')],
          ])}
          {col(t('footer.svc_col'), [
            ['servicos', t('footer.svc1')],
            ['servicos', t('footer.svc2')],
            ['servicos', t('footer.svc3')],
            ['servicos', t('footer.svc4')],
            ['servicos', t('footer.svc5')],
          ])}
          {col(t('footer.ind_col'), [
            ['industrias', t('footer.ind1')],
            ['industrias', t('footer.ind2')],
            ['industrias', t('footer.ind3')],
            ['industrias', t('footer.ind4')],
            ['industrias', t('footer.ind5')],
          ])}
          {col(t('footer.off_col'), [
            ['', 'São Paulo — SP'],
            ['', 'Recife — PE'],
            ['', 'Lisboa — PT'],
            ['', 'Berlin — DE'],
          ])}
        </div>

        <div style={{
          display: 'flex', justifyContent: 'space-between',
          alignItems: 'center', paddingTop: 32,
          borderTop: '1px solid var(--line)',
          fontFamily: 'var(--mono)', fontSize: 11,
          textTransform: 'uppercase', letterSpacing: '0.08em',
          opacity: 0.6, flexWrap: 'wrap', gap: 16,
        }}>
          <div>{t('footer.copyright')}</div>
          <div style={{ display: 'flex', gap: 24, alignItems: 'center', flexWrap: 'wrap' }}>
            <a href="#">{t('footer.privacy')}</a>
            <a href="#">{t('footer.cookies')}</a>
            <a href="#">{t('footer.terms')}</a>
            <a href="#" onClick={(e) => { e.preventDefault(); setPage('acessibilidade'); }}>{t('footer.accessibility')}</a>
            <div style={{ display: 'flex', gap: 4 }}>
              {LANGS.map(code => (
                <button key={code} onClick={() => setLang(code)} style={{
                  padding: '4px 8px', borderRadius: 6,
                  background: lang === code ? 'var(--crimson)' : 'transparent',
                  color: lang === code ? '#fff' : 'inherit',
                  border: lang === code ? 'none' : '1px solid var(--line)',
                  fontFamily: 'var(--mono)', fontSize: 10,
                  letterSpacing: '0.08em', cursor: 'pointer',
                  opacity: lang === code ? 1 : 0.7,
                  transition: 'all 0.2s',
                }}>{LANG_LABELS[code]}</button>
              ))}
            </div>
          </div>
        </div>
      </div>
      <style>{`
        .social-pill:hover { border-color: var(--crimson) !important; color: var(--crimson); }
        @media (max-width: 980px) {
          .footer-grid { grid-template-columns: 1fr 1fr !important; }
        }
      `}</style>
    </footer>
  );
}

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