function useNavStartFlowComplete() {
  const getIsComplete = () => Boolean(window.ATELA_AUTH?.isSignedIn?.());
  const [isComplete, setIsComplete] = React.useState(getIsComplete);

  React.useEffect(() => {
    const syncState = (event) => {
      const nextValue = event?.detail?.isSignedIn;
      setIsComplete(Boolean(nextValue ?? window.ATELA_AUTH?.isSignedIn?.()));
    };

    window.addEventListener('atela:auth-state-change', syncState);
    return () => {
      window.removeEventListener('atela:auth-state-change', syncState);
    };
  }, []);

  return isComplete;
}

function Nav(props) {
  const page = props.page || 'home';
  const copy = window.atelaGetCopySection('nav');
  const primaryNavCopy = window.atelaGetCopySection('nav');
  const authCopy = window.atelaGetCopySection('auth');
  const currentLocale = window.atelaGetCurrentLocale ? window.atelaGetCurrentLocale() : 'en';
  const buildLocaleUrl = window.atelaBuildLocaleUrl || ((locale) => `/${locale}`);
  const buildHomeUrl = window.atelaBuildHomeUrl || ((locale) => `/${locale || currentLocale}`);
  const buildSectionUrl = window.atelaBuildSectionUrl || ((sectionId) => `#${sectionId}`);
  const handleSectionNavigation = window.atelaHandleSectionNavigation;
  const openStartFlow = window.atelaOpenStartFlow;
  const trackCtaClick = window.atelaTrackCtaClick;
  const trackUiInteraction = window.atelaTrackUiInteraction;
  const isStartFlowComplete = useNavStartFlowComplete();
  const [isHidden, setIsHidden] = React.useState(false);
  const homeHref = buildHomeUrl(currentLocale);
  const nextLocale = currentLocale === 'ko' ? 'en' : 'ko';
  const localeToggleHref = buildLocaleUrl(nextLocale);
  const sectionLinks = Array.isArray(copy.links) ? copy.links : [];
  const menuItems = sectionLinks.length
    ? sectionLinks.map((link) => ({
        id: link.id,
        href: buildSectionUrl(link.id, currentLocale),
        label: link.label,
        isSection: true,
      }))
    : [
        {
          id: 'home',
          href: homeHref,
          label: copy.menuHome || 'STUDIO',
          isActive: true,
        },
      ];
  const usesStartFlow = true;
  const ctaLabel = usesStartFlow && isStartFlowComplete
    ? (authCopy?.completedCta || primaryNavCopy.cta)
    : copy.cta;
  const ctaHref = usesStartFlow ? window.location.pathname : buildSectionUrl('contact', currentLocale);
  const completedIcon = usesStartFlow && isStartFlowComplete ? (
    <span className="atela-cta-complete-check" aria-hidden="true">
      <svg viewBox="0 0 16 16" focusable="false">
        <path d="M3.5 8.5 6.5 11.5 12.5 4.5" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      </svg>
    </span>
  ) : null;

  const scrollToSection = (event, sectionId) => {
    const el = document.getElementById(sectionId);
    if (el) {
      event.preventDefault();
      el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

  const handleLocaleToggle = () => {
    if (trackUiInteraction) {
      trackUiInteraction({
        sectionId: 'nav',
        interactionId: 'locale_switch',
        interactionType: 'locale_switch',
        interactionLabel: currentLocale.toUpperCase(),
        interactionValue: nextLocale,
        previous_locale: currentLocale,
      });
    }

    if (window.atelaSetPreferredLocale) {
      window.atelaSetPreferredLocale(nextLocale);
    }
  };

  const handleCtaClick = (event) => {
    if (trackCtaClick) {
      trackCtaClick({
        sectionId: 'nav',
        ctaId: usesStartFlow ? 'nav_start' : 'nav_cta',
        ctaLabel,
        destination: ctaHref,
        is_start_flow_complete: usesStartFlow ? isStartFlowComplete : undefined,
      });
    }

    if (usesStartFlow && openStartFlow) {
      event.preventDefault();
      if (isStartFlowComplete) return;
      openStartFlow({ source: 'nav' });
      return;
    }

    if (handleSectionNavigation) {
      handleSectionNavigation(event, 'contact');
      return;
    }

    scrollToSection(event, 'contact');
  };

  const handleMenuClick = (event, item) => {
    if (trackUiInteraction) {
      trackUiInteraction({
        sectionId: 'nav',
        interactionId: `nav_link_${item.id}`,
        interactionType: 'click',
        interactionLabel: item.label || item.id,
      });
    }

    if (item.isSection) {
      if (handleSectionNavigation) {
        handleSectionNavigation(event, item.id);
      } else {
        scrollToSection(event, item.id);
      }
      return;
    }

    if (item.id === 'home' && handleSectionNavigation) {
      handleSectionNavigation(event, null);
    }
  };

  React.useEffect(() => {
    if (typeof window === 'undefined') return undefined;

    let frameId = 0;
    let lastScrollY = window.scrollY;
    let scrollDirection = 'none';
    let accumulatedDistance = 0;

    const HERO_ACTIVATION_OFFSET = 24;
    const MIN_SCROLL_DELTA = 2;
    const HIDE_DISTANCE = 54;
    const SHOW_DISTANCE = 28;

    const resetScrollTracking = (nextDirection = 'none') => {
      scrollDirection = nextDirection;
      accumulatedDistance = 0;
    };

    const updateVisibility = () => {
      const currentScrollY = window.scrollY;
      const heroId = page === 'studio' ? 'demo' : 'hero';
      const heroEl = document.getElementById(heroId);
      const heroBottom = heroEl
        ? heroEl.getBoundingClientRect().bottom + currentScrollY
        : 0;
      const hasPassedHero = currentScrollY > heroBottom + HERO_ACTIVATION_OFFSET;
      const deltaY = currentScrollY - lastScrollY;
      const absoluteDeltaY = Math.abs(deltaY);

      if (!hasPassedHero || currentScrollY <= 0) {
        setIsHidden(false);
        resetScrollTracking();
      } else if (absoluteDeltaY >= MIN_SCROLL_DELTA) {
        const nextDirection = deltaY > 0 ? 'down' : 'up';
        if (nextDirection !== scrollDirection) resetScrollTracking(nextDirection);
        accumulatedDistance += absoluteDeltaY;
        if (nextDirection === 'down' && accumulatedDistance >= HIDE_DISTANCE) {
          setIsHidden(true);
          accumulatedDistance = 0;
        } else if (nextDirection === 'up' && accumulatedDistance >= SHOW_DISTANCE) {
          setIsHidden(false);
          accumulatedDistance = 0;
        }
      }

      lastScrollY = currentScrollY;
      frameId = 0;
    };

    const handleScroll = () => {
      if (frameId) return;
      frameId = window.requestAnimationFrame(updateVisibility);
    };

    updateVisibility();
    window.addEventListener('scroll', handleScroll, { passive: true });
    window.addEventListener('resize', handleScroll);

    return () => {
      if (frameId) window.cancelAnimationFrame(frameId);
      window.removeEventListener('scroll', handleScroll);
      window.removeEventListener('resize', handleScroll);
    };
  }, [page]);

  return (
    <nav className={`demo-nav-shell${isHidden ? ' is-hidden' : ''}`} aria-label="Primary">
      <div className="demo-nav-bar">
        <a
          href={homeHref}
          className="demo-nav-logo"
          aria-label="ATELA home"
          onClick={handleSectionNavigation ? (event) => handleSectionNavigation(event, null) : undefined}
        >
          <span className="atela-demo-logo-word">ATELA</span>
          <span className="atela-demo-logo-dot">.</span>
        </a>

        <div className={sectionLinks.length ? 'landing-nav-links' : 'demo-nav-menu'} role="navigation" aria-label="Primary menu">
          {menuItems.map((item) => (
            <a
              key={item.id}
              className={sectionLinks.length ? 'landing-nav-link' : `demo-nav-menu-link${item.isActive ? ' is-active' : ''}`}
              href={item.href}
              onClick={(event) => handleMenuClick(event, item)}
              aria-current={item.isActive ? 'page' : undefined}
            >
              {item.label}
            </a>
          ))}
        </div>

        <div className="demo-nav-actions">
          <a
            href={localeToggleHref}
            className="demo-nav-locale-trigger"
            aria-label={`Switch language to ${nextLocale.toUpperCase()}`}
            onClick={handleLocaleToggle}
          >
            <span className="demo-nav-locale-label">{currentLocale.toUpperCase()}</span>
          </a>
          <span className="demo-nav-sep" aria-hidden="true">/</span>
          <a
            href={ctaHref}
            className={sectionLinks.length ? 'landing-nav-cta-btn' : 'demo-nav-cta'}
            onClick={handleCtaClick}
            aria-disabled={usesStartFlow && isStartFlowComplete ? true : undefined}
          >
            {ctaLabel}
            {completedIcon}
          </a>
        </div>
      </div>
    </nav>
  );
}

window.Nav = Nav;
