/**
 * Shared two-tab bottom strip (Power Up · Explore / NuAsk · Explore / etc.). Uses
 * `sf-twin-shell-nav-pulse` on the 60px bar. **Decorative SVG wires** (when both tabs are WebP glyphs): organic S-chain wavy path between icons — LTR + RTL `stroke-dashoffset` pulses (`sf-twin-nav-wire-path` / `sf-twin-nav-wire-path-rtl` in `pages/index.html`, eased with `cubic-bezier`); `TwinNavGlyph` unchanged.
 * **Variants:** **`nuask`** → Power Up · Explore; **`explore`** → Power Up · NuAsk; **`powerup`** → **Explore** (left) · **NuAsk** (right).
 *
 * **Glyphs by navigation target (same assets / sizing as global `TabButton`):**
 * - **`power-up`** (Flow Profile): `/assets/nav-profile-premium.webp?v=…`
 * - **`nu-ask-sylvan`** (NuAsk): `/assets/nav-nuask-premium.webp?v=…`
 * - **`explore`**: `/assets/nav-explore-premium.webp?v=…` (premium WebP; bump `TAB_GLYPH_ASSET_V` with `app.js` when swapping assets)
 *
 * Legal gate aligned with NuAsk `navigateFromCorridorTab`.
 */
(function () {
  'use strict';

  const { useState, useEffect } = React;

  const TAB_GLYPH_ASSET_V = '9';
  const TWIN_GLYPH_SRC = {
    'flow-profile': `/assets/nav-profile-premium.webp?v=${TAB_GLYPH_ASSET_V}`,
    nuask: `/assets/nav-nuask-premium.webp?v=${TAB_GLYPH_ASSET_V}`,
    'explore-radar': `/assets/nav-explore-premium.webp?v=${TAB_GLYPH_ASSET_V}`
  };

  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'
    };
  }

  /** Decorative wavy wire between the two twin WebP glyphs (`TwinNavGlyph` unchanged). */
  function TwinNavGlyphWire({ variant }) {
    const gid = 'sfTwinNavWire-' + String(variant || 'x');
    const gradId = gid + '-stroke';
    const filterId = gid + '-glow';
    return (
      <div
        className="pointer-events-none absolute left-1/2 top-1/2 z-[1] w-[4.85rem] -translate-x-1/2 -translate-y-1/2 sm:w-[5.35rem]"
        aria-hidden
      >
        <svg
          className="block h-[18px] w-full overflow-visible"
          viewBox="0 0 100 22"
          preserveAspectRatio="none"
        >
          <defs>
            <linearGradient id={gradId} x1="0%" y1="50%" x2="100%" y2="50%">
              <stop offset="0%" stopColor="#2DE2C5" stopOpacity="0.18" />
              <stop offset="38%" stopColor="#5EEAD4" stopOpacity="1" />
              <stop offset="62%" stopColor="#5EEAD4" stopOpacity="1" />
              <stop offset="100%" stopColor="#2DE2C5" stopOpacity="0.18" />
            </linearGradient>
            <filter id={filterId} x="-40%" y="-40%" width="180%" height="180%">
              <feGaussianBlur in="SourceGraphic" stdDeviation="0.75" result="blur" />
              <feMerge>
                <feMergeNode in="blur" />
                <feMergeNode in="SourceGraphic" />
              </feMerge>
            </filter>
          </defs>
          <path
            className="sf-twin-nav-wire-path"
            pathLength="100"
            fill="none"
            stroke={'url(#' + gradId + ')'}
            strokeWidth="2.35"
            strokeLinecap="round"
            strokeLinejoin="round"
            vectorEffect="nonScalingStroke"
            filter={'url(#' + filterId + ')'}
            d="M 1.5 11 C 17 2.5, 20 19.5, 34 11 S 52 2.5, 66 11 S 80 19.5, 98.5 11"
          />
          <path
            className="sf-twin-nav-wire-path-rtl"
            pathLength="100"
            fill="none"
            stroke={'url(#' + gradId + ')'}
            strokeWidth="2.35"
            strokeLinecap="round"
            strokeLinejoin="round"
            vectorEffect="nonScalingStroke"
            filter={'url(#' + filterId + ')'}
            d="M 1.5 11 C 17 2.5, 20 19.5, 34 11 S 52 2.5, 66 11 S 80 19.5, 98.5 11"
          />
        </svg>
      </div>
    );
  }

  /** 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 = 'explore';
      rightView = 'nu-ask-sylvan';
      leftActive = viewIsExploreCluster(v);
      rightActive = v === 'nu-ask-sylvan';
    } else {
      return null;
    }

    const aria =
      ariaLabel ||
      (variant === 'explore'
        ? 'Power Up and NuAsk'
        : variant === 'powerup'
          ? 'Explore and NuAsk'
          : '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">
          {leftKind && rightKind ? <TwinNavGlyphWire variant={variant} /> : null}
          <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__ = 17;
    window.InternalShellTwinNav = InternalShellTwinNav;
  }
})();
