/**
 * Shared two-tab bottom strip (Power Up · Explore / NuAsk · Explore / etc.). Uses
 * `sf-twin-shell-nav-pulse` on the 60px bar. Explore + Power Up pass `staticTwinEdge`: the **hub–twin
 * hairline** is a static 1px overlay (no animated rim on that seam only); the strip still pulses.
 *
 * **Glyphs by navigation target (same assets / sizing as global `TabButton`):**
 * - **`power-up`** (Flow Profile): `/assets/flow-profile-tab-icon.png`
 * - **`nu-ask-sylvan`** (NuAsk): `/assets/nuask-tab-radar.png`
 * - **`explore`**: `/assets/nuask-tab-icon.png`
 *
 * Legal gate aligned with NuAsk `navigateFromCorridorTab`.
 */
(function () {
  'use strict';

  const { useState, useEffect } = React;

  const TWIN_GLYPH_SRC = {
    'flow-profile': '/assets/flow-profile-tab-icon.png',
    nuask: '/assets/nuask-tab-radar.png',
    'explore-radar': '/assets/nuask-tab-icon.png'
  };

  function glyphKindForTargetView(view) {
    if (view === 'power-up') return 'flow-profile';
    if (view === 'nu-ask-sylvan') return 'nuask';
    if (view === 'explore') return 'explore-radar';
    return null;
  }

  function getShellView() {
    try {
      return window.appState?.get?.()?.view || '';
    } catch {
      return '';
    }
  }

  function twinNavigate(targetView) {
    const legalAgreed = localStorage.getItem('sylvanflow_legal_agreed');
    const restricted = ['explore', 'flow-plan', 'ask-sylvan', 'nu-ask-sylvan'];
    if (restricted.includes(targetView) && !legalAgreed) {
      window.location.href = '/legal?return=/power-up'; // SF_ALLOW_HARDEXIT_REDIRECT
      return;
    }
    if (window.appState?.set) window.appState.set({ view: targetView });
  }

  function tabLabelStyle(active) {
    return {
      display: 'inline-block',
      color: '#5EEAD4',
      textDecoration: 'none',
      animation: active
        ? 'sf-tab-label-glow-active 2s ease-in-out infinite'
        : 'sf-tab-label-glow-inactive 2s ease-in-out infinite'
    };
  }

  /** Same h-14 w-14 · 54px object-contain contract as global shell glyph tabs. */
  function TwinNavGlyph({ kind }) {
    const src = TWIN_GLYPH_SRC[kind];
    if (!src) return null;
    return (
      <span className="relative flex h-14 w-14 shrink-0 items-center justify-center" aria-hidden>
        <img
          src={src}
          alt=""
          width={54}
          height={54}
          className="h-[54px] w-[54px] max-h-[56px] max-w-[56px] object-contain"
          decoding="async"
          draggable={false}
        />
      </span>
    );
  }

  /** Aligns with app shell `isActiveTab` for the Explore tab cluster. */
  function viewIsExploreCluster(v) {
    return (
      v === 'explore' ||
      v === 'flow-plan' ||
      v === 'explore-detail' ||
      v === 'activity-detail'
    );
  }

  /**
   * @param {{ variant: 'nuask' | 'explore' | 'powerup', leftLabel: string, rightLabel: string, ariaLabel?: string, staticTwinEdge?: boolean }} props
   */
  function InternalShellTwinNav({ variant, leftLabel, rightLabel, ariaLabel, staticTwinEdge }) {
    const [v, setV] = useState(getShellView);

    useEffect(() => {
      const onState = () => setV(getShellView());
      window.addEventListener('state-change', onState);
      onState();
      return () => window.removeEventListener('state-change', onState);
    }, []);

    let leftView;
    let rightView;
    let leftActive;
    let rightActive;

    if (variant === 'nuask') {
      leftView = 'power-up';
      rightView = 'explore';
      leftActive = v === 'power-up';
      rightActive = viewIsExploreCluster(v);
    } else if (variant === 'explore') {
      leftView = 'power-up';
      rightView = 'nu-ask-sylvan';
      leftActive = v === 'power-up';
      rightActive = v === 'nu-ask-sylvan';
    } else if (variant === 'powerup') {
      leftView = 'nu-ask-sylvan';
      rightView = 'explore';
      leftActive = v === 'nu-ask-sylvan';
      rightActive = viewIsExploreCluster(v);
    } else {
      return null;
    }

    const aria =
      ariaLabel ||
      (variant === 'explore'
        ? 'Power Up and NuAsk'
        : variant === 'powerup'
          ? 'NuAsk and Explore'
          : 'Power Up and Explore');

    const twinTopBorder = staticTwinEdge ? 'border-t-0' : 'border-t border-cyan-400/40';

    const leftKind = glyphKindForTargetView(leftView);
    const rightKind = glyphKindForTargetView(rightView);

    const glyphBtn =
      'relative z-[2] flex h-full min-h-[44px] w-full min-w-0 flex-col items-center justify-center gap-0 border-b-0 px-0.5 py-0.5 no-underline outline-none transition-colors focus-visible:outline-none';
    const textBtn =
      'relative z-[2] flex h-full min-h-[44px] w-full min-w-0 flex-col items-center justify-center gap-0.5 border-b-0 px-1 py-2 no-underline outline-none transition-colors focus-visible:outline-none';

    return (
      <nav
        data-sf-internal-twin-nav="true"
        data-sf-internal-twin-variant={variant}
        data-sf-internal-twin-static-edge={staticTwinEdge ? 'true' : 'false'}
        className={`sf-twin-shell-nav-pulse relative z-[41] flex h-[60px] min-h-[60px] w-full shrink-0 flex-col overflow-visible ${twinTopBorder} bg-[#030508]/95 backdrop-blur-sm pb-[env(safe-area-inset-bottom,0px)] text-[10px] sm:text-xs`}
        aria-label={aria}
      >
        {staticTwinEdge ? (
          <div
            className="relative z-[30] h-px w-full shrink-0 bg-[#030508] shadow-[0_1px_0_rgba(255,255,255,0.1)]"
            aria-hidden
          />
        ) : null}
        <div className="relative z-[1] grid min-h-0 flex-1 grid-cols-2 items-stretch">
          <button
            type="button"
            data-sf-twin-tab-glyph={leftKind || undefined}
            onClick={() => twinNavigate(leftView)}
            aria-label={leftLabel}
            className={leftKind ? glyphBtn : textBtn}
          >
            {leftKind ? (
              <TwinNavGlyph kind={leftKind} />
            ) : (
              <span
                className="relative z-10 max-w-full overflow-visible text-center font-mono text-[10px] leading-tight sm:text-[11px]"
                style={tabLabelStyle(leftActive)}
              >
                {leftLabel}
              </span>
            )}
          </button>
          <button
            type="button"
            data-sf-twin-tab-glyph={rightKind || undefined}
            onClick={() => twinNavigate(rightView)}
            aria-label={rightLabel}
            className={rightKind ? glyphBtn : textBtn}
          >
            {rightKind ? (
              <TwinNavGlyph kind={rightKind} />
            ) : (
              <span
                className="relative z-10 max-w-full overflow-visible text-center font-mono text-[10px] leading-tight sm:text-[11px]"
                style={tabLabelStyle(rightActive)}
              >
                {rightLabel}
              </span>
            )}
          </button>
        </div>
      </nav>
    );
  }

  if (typeof window !== 'undefined') {
    /** Bump with `index.html` InternalShellTwinNav.jsx `?sfRev=` when twin-nav UI changes (deploy/cache proof). */
    window.__SF_INTERNAL_SHELL_TWIN_NAV_SFREV__ = 6;
    window.InternalShellTwinNav = InternalShellTwinNav;
  }
})();
