// ============================
// LELUSA — Mobile Navigation
// src/components/mobile-nav.jsx
// ============================

// Depth levels used to infer transition direction.
const PAGE_DEPTH = { home: 1, catalog: 1, 'deco-detail': 2, customizer: 3, 'quote-form': 4 };

function depthOf(page) { return PAGE_DEPTH[page] || 1; }

// Given previous and next page keys + an explicit hint, return 'forward' | 'back' | 'tab'.
function resolveDirection(prevPage, nextPage, hint) {
  if (hint) return hint;
  const a = depthOf(prevPage), b = depthOf(nextPage);
  if (b > a) return 'forward';
  if (b < a) return 'back';
  return 'tab';
}

// PageTransition: animates between the outgoing and incoming page.
// props: { pageKey (string), direction ('forward'|'back'|'tab'), children }
function PageTransition({ pageKey, direction, children }) {
  const { useReducedMotion, useIsMobile } = window.LelusaGestures;
  const reduced = useReducedMotion();
  const isMobile = useIsMobile();
  const [current, setCurrent] = React.useState({ key: pageKey, node: children });
  const [prev, setPrev] = React.useState(null);
  const childrenRef = React.useRef(children);
  childrenRef.current = children;

  // Keep the displayed node fresh on same-page re-renders without
  // re-running the transition effect (children is a new ref each render).
  React.useEffect(() => {
    if (pageKey !== current.key) return;
    setCurrent(c => (c.node === childrenRef.current ? c : { key: c.key, node: childrenRef.current }));
  });

  React.useEffect(() => {
    if (pageKey === current.key) return;
    const node = childrenRef.current;
    if (reduced) {
      setCurrent({ key: pageKey, node });
      setPrev(null);
      window.scrollTo({ top: 0, behavior: 'instant' });
      return;
    }
    setPrev(current);
    setCurrent({ key: pageKey, node });
    window.scrollTo({ top: 0, behavior: 'instant' });
    const t = setTimeout(() => setPrev(null), 460);
    return () => clearTimeout(t);
  }, [pageKey]);

  // Desktop and reduced-motion: render plain (no animation).
  if (!isMobile || reduced) {
    return <div key={current.key}>{current.node}</div>;
  }

  // Admin sections always use the fade (tab) transition, never a directional slide.
  const isAdmin = String(current.key).startsWith('admin-');
  const mode = isAdmin ? 'tab' : (direction || 'tab');
  return (
    <div style={{ position: 'relative', minHeight: '100vh', overflowX: 'clip' }}>
      {prev && (
        <div key={'prev-' + prev.key} className={`lel-page lel-out-${mode}`} style={{ position: 'absolute', inset: 0 }}>
          {prev.node}
        </div>
      )}
      <div key={'cur-' + current.key} className={`lel-page ${prev ? `lel-in-${mode}` : ''}`}>
        {current.node}
      </div>
    </div>
  );
}

// ─── BottomNav (floating pill + center CTA) ─────────────────────
function BottomNav() {
  const { navigate, currentPage } = React.useContext(window.AppContext);
  const { haptic, useIsMobile } = window.LelusaGestures;
  const isMobile = useIsMobile();
  if (!isMobile) return null;

  // Scroll to a landing section using the existing pageData.section mechanism.
  const goToSection = (section) => {
    haptic(8);
    if (currentPage === 'home') {
      const el = document.querySelector(`[data-section="${section}"]`);
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    } else {
      navigate('home', { section }, 'tab');
    }
  };

  const goHome = () => {
    haptic(8);
    if (currentPage === 'home') window.scrollTo({ top: 0, behavior: 'smooth' });
    else navigate('home', {}, 'tab');
  };

  const item = (label, icon, active, onClick) => (
    <button onClick={onClick} className="lel-bn-item" style={{ color: active ? 'var(--primary)' : 'var(--muted)' }}>
      <Icon name={icon} size={21} color={active ? 'var(--primary)' : 'var(--muted)'} strokeWidth={active ? 2 : 1.6} />
      <span>{label}</span>
    </button>
  );

  return (
    <div className="lel-bn-wrap">
      <div className="lel-bn-pill">
        {item('Inicio', 'home', currentPage === 'home', goHome)}
        {item('Catálogo', 'grid', currentPage === 'catalog' || currentPage === 'deco-detail', () => { haptic(8); navigate('catalog', {}, 'tab'); })}
        <div style={{ flex: 1.2 }} />
        {item('Eventos', 'calendar', false, () => goToSection('eventos'))}
        {item('Contacto', 'mail', false, () => goToSection('contacto'))}
      </div>
      <button
        className="lel-bn-cta"
        onClick={() => { haptic(12); navigate('quote-form', {}, 'forward'); }}
        style={{ background: 'linear-gradient(135deg, var(--primary), var(--primary-dark))' }}
      >
        <Icon name="sparkles" size={22} color="#fff" />
        <span>Cotizar</span>
      </button>
    </div>
  );
}

window.resolveDirection = resolveDirection;
window.PageTransition = PageTransition;
window.BottomNav = BottomNav;
