// Deezer-aware Nav with auto-inverting color (floating pill).
// Detects which section is currently behind the nav and inverts colors.
function NavDeezer() {
  const [open, setOpen] = React.useState(false);
  const [overDark, setOverDark] = React.useState(false);
  const navRef = React.useRef(null);

  const isHome = React.useMemo(() => {
    if (typeof window === 'undefined') return true;
    const p = window.location.pathname;
    return p.endsWith('/index-deezer.html') || p.endsWith('/');
  }, []);
  const base = (typeof window !== 'undefined' && window.SITE_HOME) ? window.SITE_HOME : (isHome ? '' : 'e-commerce/index.html');
  const link = (hash) => base + hash;

  React.useEffect(() => {
    const close = () => setOpen(false);
    const onResize = () => { if (window.innerWidth > 880) setOpen(false); };
    window.addEventListener('hashchange', close);
    window.addEventListener('resize', onResize);
    return () => {
      window.removeEventListener('hashchange', close);
      window.removeEventListener('resize', onResize);
    };
  }, []);

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

  React.useEffect(() => { if (window.lucide) lucide.createIcons(); }, [open, overDark]);

  // ── Color-invert behaviour: detect which section sits behind the nav ────────
  React.useEffect(() => {
    if (typeof window === 'undefined') return;

    // selectors that produce dark surfaces in our Deezer theme
    const darkSel = [
      '.is-dark', '#dlakogo', '#problemy', '#opinie', '#proces', '#faq',
      '.g-footer', '.cs-cta-card', '.sb-section', '.g-contact-form'
    ].join(',');

    let nodes = Array.from(document.querySelectorAll(darkSel));
    // Re-scan once the page has fully hydrated (React mounts components asynchronously)
    const rescan = () => { nodes = Array.from(document.querySelectorAll(darkSel)); check(); };

    const check = () => {
      const navEl = navRef.current;
      if (!navEl) return;
      const navRect = navEl.getBoundingClientRect();
      const probeY = navRect.top + navRect.height / 2;
      let hit = false;
      for (const el of nodes) {
        const r = el.getBoundingClientRect();
        if (r.top <= probeY && r.bottom > probeY) { hit = true; break; }
      }
      setOverDark(hit);
    };

    // initial + delayed (give other components time to mount)
    check();
    const t1 = setTimeout(rescan, 50);
    const t2 = setTimeout(rescan, 400);

    let raf = 0;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => { raf = 0; check(); });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);

    return () => {
      clearTimeout(t1); clearTimeout(t2);
      if (raf) cancelAnimationFrame(raf);
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, []);

  const items = [
    { href: link('#problemy'),       label: 'Dla kogo' },
    { href: link('#pomagam'),        label: 'Jak pomagam' },
    { href: link('#portfolio'), label: 'Portfolio' },
    { href: link('#proces'),         label: 'Współpraca' },
    { href: link('#omnie'),          label: 'O mnie' },
    { href: link('#faq'),            label: 'FAQ' },
  ];

  return (
    <React.Fragment>
      <nav ref={navRef} className={"g-nav g-nav--pill" + (overDark ? ' is-over-dark' : '')}>
        <a className="g-brand" href={isHome ? '#' : 'e-commerce/index.html'}>
          <span className="g-brand-mark" aria-hidden="true">
            <svg viewBox="0 0 32 32" fill="none">
              <rect x="1" y="1" width="30" height="30" rx="9" stroke="currentColor" strokeWidth="2"/>
              <path d="M8 23 L8 9 L16 18 L24 9 L24 23"
                    stroke="currentColor" strokeWidth="2.6"
                    strokeLinecap="round" strokeLinejoin="round" fill="none"/>
            </svg>
          </span>
          <span>Maciej Matera</span>
        </a>
        <div className="g-nav-links">
          {items.map((it) => (<a key={it.label} href={it.href}>{it.label}</a>))}
        </div>
        <div className="g-nav-cta">
          <a className="g-btn g-btn--nav" href={link('#kontakt')}>
            Darmowy audyt <i data-lucide="arrow-up-right"></i>
          </a>
          <button
            className="g-nav-burger"
            aria-label={open ? 'Zamknij menu' : 'Otwórz menu'}
            aria-expanded={open}
            onClick={() => setOpen(o => !o)}
          >
            <i data-lucide={open ? 'x' : 'menu'}></i>
          </button>
        </div>
      </nav>

      <div className={"g-nav-scrim" + (open ? ' open' : '')} onClick={() => setOpen(false)}></div>
      <div className={"g-nav-mobile" + (open ? ' open' : '')} role="dialog" aria-label="Menu">
        {items.map((it) => (
          <a key={it.label} href={it.href} onClick={() => setOpen(false)}>{it.label}</a>
        ))}
        <div className="g-nav-mobile-cta">
          <a className="g-btn g-btn--accent" href={link('#kontakt')} onClick={() => setOpen(false)}>
            Umów darmowy audyt <i data-lucide="arrow-right"></i>
          </a>
        </div>
      </div>
    </React.Fragment>
  );
}
window.NavDeezer = NavDeezer;
