/* global React, Mark, CTAButton */
const { useState: useHS, useEffect: useHE } = React;

const PAGES = [
  { slug: '',           label: 'Home' },
  { slug: 'il-metodo',  label: 'Il Metodo' },
  { slug: 'chi-siamo',  label: 'Chi Siamo' },
  { slug: 'risultati',  label: 'Risultati' },
];

function useRoute() {
  const [route, setRoute] = useHS(() => (window.location.hash.replace(/^#\/?/, '') || ''));
  useHE(() => {
    const onHash = () => {
      setRoute(window.location.hash.replace(/^#\/?/, '') || '');
      // Cambio pagina: salta SUBITO in cima annullando qualsiasi smooth-scroll
      // Lenis ancora in corso (altrimenti la nuova pagina parte già scrollata
      // e continua a rallentare). force:true scrolla anche se Lenis è in stop.
      if (window.__lenis) window.__lenis.scrollTo(0, { immediate: true, force: true });
      else window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return route;
}

/* Scroll fluido in cima — usato quando si clicca il logo o la voce
   della pagina già attiva (hashchange non scatta a hash invariato). */
function scrollToTopSmooth() {
  if (window.__lenis) window.__lenis.scrollTo(0, { duration: 1.2 });
  else window.scrollTo({ top: 0, behavior: 'smooth' });
}

function Header({ onCTA, route }) {
  const [scrolled, setScrolled] = useHS(false);
  const [open, setOpen] = useHS(false);
  useHE(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  useHE(() => { setOpen(false); }, [route]);

  return (
    <>
      <header style={{
        position: 'fixed', top: 0, left: 0, right: 0, zIndex: 50,
        transition: 'border-color 300ms',
        background: '#FFFFFF',
        backdropFilter: 'blur(14px) saturate(150%)',
        WebkitBackdropFilter: 'blur(14px) saturate(150%)',
        borderBottom: scrolled ? '1px solid var(--color-border)' : '1px solid transparent',
      }}>
        <div className="hdr-row" style={{
          maxWidth: 1370, margin: '0 auto',
          padding: '20px 30px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 28,
        }}>
          <a href="#/"
             onClick={(e) => { if (route === '') { e.preventDefault(); scrollToTopSmooth(); } }}
             style={{ display: 'flex', alignItems: 'center', gap: 10, textDecoration: 'none' }}>
            <img src="assets/logo-forma.png" alt="Progetto Forma" style={{ height: 42, width: 'auto', display: 'block' }} />
          </a>

          <nav className="hide-mobile" style={{ display: 'flex', alignItems: 'center', gap: 40 }}>
            {PAGES.map(p => {
              const active = p.slug === route;
              return (
                <a key={p.slug} href={`#/${p.slug}`}
                   onClick={(e) => { if (active) { e.preventDefault(); scrollToTopSmooth(); } }}
                   style={{
                     fontFamily: 'Inter, sans-serif', fontSize: 16, fontWeight: 600,
                     color: active ? 'var(--color-primary)' : '#000000',
                     textDecoration: 'none',
                     position: 'relative', padding: '6px 0',
                     borderBottom: active ? '1px solid var(--color-primary)' : '1px solid transparent',
                     transition: 'color 200ms, border-color 200ms',
                   }}
                   onMouseEnter={e => { if (!active) e.currentTarget.style.color = 'var(--color-primary)'; }}
                   onMouseLeave={e => { if (!active) e.currentTarget.style.color = '#000000'; }}
                >{p.label}</a>
              );
            })}
          </nav>

          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <CTAButton onClick={onCTA} size="md" className="hide-mobile">Prenota la tua consulenza GRATUITA</CTAButton>
            <button
              onClick={() => setOpen(o => !o)}
              className="only-mobile"
              aria-label="Menu"
              style={{
                background: 'transparent', border: '1px solid var(--color-border-strong)',
                borderRadius: 6, padding: 8, cursor: 'pointer',
                display: 'none', alignItems: 'center', justifyContent: 'center',
                color: 'var(--color-text-primary)', WebkitAppearance: 'none', appearance: 'none',
              }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">
                {open
                  ? (<><line x1="6" y1="6" x2="18" y2="18"/><line x1="6" y1="18" x2="18" y2="6"/></>)
                  : (<><line x1="4" y1="7" x2="20" y2="7"/><line x1="4" y1="13" x2="20" y2="13"/><line x1="4" y1="19" x2="20" y2="19"/></>)
                }
              </svg>
            </button>
          </div>
        </div>
      </header>

      {/* Mobile fullscreen menu */}
      <div style={{
        position: 'fixed', inset: 0, zIndex: 49,
        background: 'var(--color-background)',
        opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none',
        transition: 'opacity 280ms cubic-bezier(.22,1,.36,1)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 28, alignItems: 'center' }}>
          {PAGES.map((p, i) => (
            <a key={p.slug} href={`#/${p.slug}`}
               onClick={(e) => { if (p.slug === route) { e.preventDefault(); setOpen(false); scrollToTopSmooth(); } }}
               style={{
                 fontFamily: 'Inter, sans-serif', fontWeight: 600, fontSize: 22,
                 color: p.slug === route ? 'var(--color-primary)' : '#000000',
                 textDecoration: 'none',
                 opacity: open ? 1 : 0,
                 transform: open ? 'translateY(0)' : 'translateY(12px)',
                 transition: `opacity 360ms ${80 + i * 60}ms cubic-bezier(.22,1,.36,1), transform 360ms ${80 + i * 60}ms cubic-bezier(.22,1,.36,1)`,
               }}>{p.label}</a>
          ))}
          <div style={{ marginTop: 16 }}>
            <CTAButton onClick={onCTA} size="md">Prenota la tua consulenza GRATUITA</CTAButton>
          </div>
        </nav>
      </div>
    </>
  );
}

Object.assign(window, { Header, useRoute, PAGES });
