// Blast Events — shared chrome (Nav, Footer, hooks, helpers)
// Loaded BEFORE the page-specific app.jsx. Exposes everything on window.

const { useEffect, useState, useRef } = React;

// ============ Cross-page link helper ============
function currentPage() {
  const f = (window.location.pathname.split('/').pop() || 'index.html').toLowerCase();
  if (!f || f === '' || f === 'index.html') return 'home';
  return f.replace('.html', '');
}
function homeLink(anchor) {
  return currentPage() === 'home' ? '#' + anchor : 'index.html#' + anchor;
}
// Page link helpers — return '#top' if already on that page, else the .html.
// 'home' is special: the file is index.html, not home.html.
function pageLink(page) {
  if (currentPage() === page) return '#top';
  return page === 'home' ? 'index.html' : page + '.html';
}

// ============ TR — mask-slide title reveal ============
function TR({ children, className }) {
  return <span className={`title-reveal ${className || ''}`}><span className="tr-inner">{children}</span></span>;
}

// ============ Animated counter ============
function Counter({ to, duration = 1800, decimals = 0 }) {
  const ref = useRef(null);
  const [val, setVal] = useState(0);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let raf = 0;
    const io = new IntersectionObserver((entries) => {
      for (const e of entries) {
        if (e.isIntersecting) {
          const start = performance.now();
          const tick = (now) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            setVal(to * eased);
            if (t < 1) raf = requestAnimationFrame(tick);
          };
          raf = requestAnimationFrame(tick);
          io.unobserve(el);
        }
      }
    }, { threshold: 0.4 });
    io.observe(el);
    return () => {io.disconnect();cancelAnimationFrame(raf);};
  }, [to, duration]);
  return <span ref={ref}>{decimals > 0 ? val.toFixed(decimals) : Math.round(val)}</span>;
}

// ============ Hero h1 reveal ============
function useHeroReveal() {
  useEffect(() => {
    const h = document.querySelector('.hero h1');
    if (!h) return;
    const t = setTimeout(() => {
      h.classList.add('go');
      document.body.classList.add('hero-animated');
    }, 80);
    return () => clearTimeout(t);
  }, []);
}

// ============ Custom cursor ============
function useCursor() {
  useEffect(() => {
    if (!window.matchMedia('(hover: hover) and (pointer: fine)').matches) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    const el = document.getElementById('cursor');
    if (!el) return;
    let raf = 0,x = 0,y = 0,tx = 0,ty = 0;
    const move = (e) => {tx = e.clientX;ty = e.clientY;if (!raf) raf = requestAnimationFrame(loop);};
    const loop = () => {
      x += (tx - x) * 0.25;y += (ty - y) * 0.25;
      el.style.transform = `translate(${x}px, ${y}px) translate(-50%,-50%)`;
      if (Math.abs(tx - x) > 0.1 || Math.abs(ty - y) > 0.1) raf = requestAnimationFrame(loop);else raf = 0;
    };
    const over = (e) => {
      const t = e.target.closest('a, button, .svc, .pf-item, .team-slot, .chapter, [data-cursor=lg]');
      if (t) el.classList.add('lg');else el.classList.remove('lg');
    };
    const leave = () => el.classList.add('hide');
    const enter = () => el.classList.remove('hide');
    window.addEventListener('mousemove', move);
    window.addEventListener('mouseover', over);
    document.addEventListener('mouseleave', leave);
    document.addEventListener('mouseenter', enter);
    return () => {
      window.removeEventListener('mousemove', move);
      window.removeEventListener('mouseover', over);
      document.removeEventListener('mouseleave', leave);
      document.removeEventListener('mouseenter', enter);
      cancelAnimationFrame(raf);
    };
  }, []);
}

// ============ Reveal on scroll ============
function useReveal() {
  useEffect(() => {
    let io = null;
    let safety = 0;

    const setup = () => {
      const els = Array.from(document.querySelectorAll('.reveal, .reveal-children'));
      els.forEach((el) => {
        el.classList.add('is-hidden');
        el.classList.remove('in');
      });
      if (!('IntersectionObserver' in window)) {
        els.forEach((el) => {el.classList.remove('is-hidden');el.classList.add('in');});
        return null;
      }
      const obs = new IntersectionObserver((entries) => {
        for (const e of entries) {
          if (e.isIntersecting) {
            e.target.classList.remove('is-hidden');
            e.target.classList.add('in');
            obs.unobserve(e.target);
          }
        }
      }, { threshold: 0.18, rootMargin: '0px 0px -80px 0px' });
      els.forEach((el) => obs.observe(el));
      return obs;
    };

    const start = () => {
      if (io) return;
      io = setup();
      safety = setTimeout(() => {
        document.querySelectorAll('.reveal.is-hidden, .reveal-children.is-hidden').forEach((el) => {
          el.classList.remove('is-hidden');el.classList.add('in');
        });
      }, 25000);
    };

    if (document.readyState === 'complete') {
      requestAnimationFrame(() => requestAnimationFrame(start));
    } else {
      window.addEventListener('load', () => requestAnimationFrame(() => requestAnimationFrame(start)), { once: true });
    }

    return () => {if (io) io.disconnect();if (safety) clearTimeout(safety);};
  }, []);
}

// ============ Nav scroll state ============
function useNavScroll() {
  useEffect(() => {
    const nav = document.querySelector('.nav');
    if (!nav) return;
    const onScroll = () => {
      if (window.scrollY > 40) nav.classList.add('scrolled');else
      nav.classList.remove('scrolled');
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
}

// ============ Star icon ============
function Star({ size = 18 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" className="star" aria-hidden>
      <path d="M12 0 L14 9 L24 12 L14 15 L12 24 L10 15 L0 12 L10 9 Z" />
    </svg>);

}

// ============ Pulse line ============
function PulseLine() {
  return (
    <svg className="pulse-line" viewBox="0 0 800 28" preserveAspectRatio="none" aria-hidden>
      <path d="M0 14 L80 14 L96 14 L104 4 L112 24 L120 8 L128 20 L136 14 L300 14 L320 14 L328 6 L336 22 L344 14 L500 14 L520 14 L528 4 L536 24 L544 14 L800 14" />
    </svg>);

}

// ============ Nav (cross-page aware) ============
function Nav({ onMenu }) {
  const page = currentPage();
  const cls = (p) => 'nav-link' + (page === p ? ' active' : '');
  return (
    <nav className="nav" data-comment-anchor="414e660e16-nav-186-5">
      <a href={page === 'home' ? '#top' : 'index.html'} className="brand">
        <img src="assets/logo-wordmark.png" alt="Blast Events" />
      </a>
      <div className="navlinks">
        <a className={cls('home')}     href={pageLink('home')}>Home</a>
        <a className={cls('about')}    href={pageLink('about')}>Chi siamo</a>
        <a className={cls('servizi')}  href={pageLink('servizi')}>Servizi</a>
        <a className={cls('portfolio')} href={pageLink('portfolio')}>Lavori</a>
        <a className={cls('contatti')} href={pageLink('contatti')}>Contatti</a>
      </div>
      <a href={homeLink('contact')} className="cta">Contattaci →</a>
      <button className="menu-btn" onClick={onMenu} aria-label="Menu"><span></span></button>
    </nav>);

}

// ============ Mobile menu ============
function MobileMenu({ open, onClose }) {
  const page = currentPage();
  const aCls = (p) => page === p ? 'active' : '';
  return (
    <div className={`mob-menu ${open ? 'open' : ''}`}>
      <button className="close" onClick={onClose} aria-label="Chiudi">×</button>
      <a onClick={onClose} href={pageLink('home')}     className={aCls('home')}>Home</a>
      <a onClick={onClose} href={pageLink('about')} className={aCls('about')}>Chi siamo</a>
      <a onClick={onClose} href={pageLink('servizi')} className={aCls('servizi')}>Servizi</a>
      <a onClick={onClose} href={pageLink('portfolio')} className={aCls('portfolio')}>Lavori</a>
      <a onClick={onClose} href={pageLink('contatti')} className={aCls('contatti')}>Contatti</a>
      <div className="info">
        <div className="row"><span>TEL</span><span><a href="tel:+393402622355">+39 340 262 2355</a></span></div>
        <div className="row"><span>EMAIL</span><span>info@blasteventservice.com</span></div>
        <div className="row"><span>SEDE</span><span>Belluno, 32100</span></div>
        <div className="row"><span>EST.</span><span>2019</span></div>
      </div>
    </div>);

}

// ============ Footer (cross-page aware) ============
function Footer() {
  return (
    <footer className="footer wrap">
      <div className="word-row">
        <img className="word-mark" src="assets/logo-wordmark.png" alt="Blast Events" />
      </div>

      <div className="cols">
        <div className="col">
          <h4>Sede</h4>
          <span>Belluno, 32100</span>
          <span>Italia</span>
        </div>
        <div className="col">
          <h4>Contatti</h4>
          <a href="tel:+393402622355">+39 340 262 2355</a>
          <a href="tel:+393491186039">+39 349 118 6039</a>
          <a href="mailto:info@blasteventservice.com">info@blasteventservice.com</a>
        </div>
        <div className="col">
          <h4>Social</h4>
          <a href="#">Facebook</a>
          <a href="#">Instagram</a>
        </div>
        <div className="col">
          <h4>Navigazione</h4>
          <a href={pageLink('home')}>Home</a>
          <a href={pageLink('about')}>Chi siamo</a>
          <a href={pageLink('servizi')}>Servizi</a>
          <a href={pageLink('portfolio')}>Lavori</a>
          <a href={pageLink('contatti')}>Contatti</a>
        </div>
      </div>

      <div className="legal">
        <div>© 2026 Blast Events di Lorenzo De Moliner · P.IVA 01303010258</div>
        <div>Belluno, IT · EST. 2019</div>
        <div>
          <a href="https://www.iubenda.com/privacy-policy/59618259" target="_blank" rel="noopener noreferrer">Privacy</a>
          {' · '}
          <a href="https://www.iubenda.com/privacy-policy/59618259/cookie-policy" target="_blank" rel="noopener noreferrer">Cookie</a>
          {' · '}
          <a href="#" className="iubenda-cs-preferences-link">Preferenze cookie</a>
        </div>
      </div>
    </footer>);

}

// ============ Invio form contatti (Web3Forms) ============
// Chiave d'accesso da web3forms.com, associata a info@blasteventservice.com.
// Le richieste arrivano via email a quell'indirizzo. Nessun dato salvato da noi.
const WEB3FORMS_KEY = 'be567183-29d9-4161-9a10-672b8f197615';

async function submitContactForm(formEl) {
  const data = new FormData(formEl);
  data.append('access_key', WEB3FORMS_KEY);
  data.append('subject', 'Nuova richiesta dal sito Blast Events');
  data.append('from_name', 'Sito Blast Events');
  // honeypot lato server di Web3Forms (oltre al nostro campo "website")
  const res = await fetch('https://api.web3forms.com/submit', {
    method: 'POST',
    headers: { Accept: 'application/json' },
    body: data
  });
  const json = await res.json().catch(() => ({}));
  return json.success === true;
}

// Expose everything to window
Object.assign(window, {
  TR, Counter, Star, PulseLine,
  Nav, MobileMenu, Footer,
  useCursor, useReveal, useNavScroll, useHeroReveal,
  currentPage, homeLink, pageLink,
  submitContactForm
});