import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { NavRail } from './NavRail';
import { IntelligenceRail } from '../../intelligence-rail/IntelligenceRail';
import { SentinelAlertBanner } from '../../intelligence-rail/SentinelAlertBanner';
import styles from './AuthenticatedShell.module.css';

/**
 * AuthenticatedShell
 * The persistent chrome for all authenticated broker views.
 * Contains: NavRail (left) | Main content area | IntelligenceRail (right)
 * SentinelAlertBanner slides in from top on CCTV events.
 */
export function AuthenticatedShell() {
  const location = useLocation();
  const prevPath = useRef(location.pathname);

  // Determine spatial direction for pillar transitions
  const getPillarIndex = (path: string): number => {
    if (path.startsWith('/command'))  return 0;
    if (path.startsWith('/pipeline')) return 1;
    if (path.startsWith('/studio'))   return 2;
    return -1;
  };

  const prevIdx = getPillarIndex(prevPath.current);
  const currIdx = getPillarIndex(location.pathname);
  const isDrillIn = currIdx === -1; // non-pillar route = drill-in

  // Directional slide variants
  const direction = currIdx > prevIdx ? 1 : -1;
  const variants = isDrillIn
    ? {
        // Drill into entity: scale + fade
        initial:  { opacity: 0, scale: 0.96 },
        animate:  { opacity: 1, scale: 1 },
        exit:     { opacity: 0.6, scale: 0.97 },
      }
    : {
        // Pillar-to-pillar: directional slide
        initial:  { opacity: 0, x: direction * 60 },
        animate:  { opacity: 1, x: 0 },
        exit:     { opacity: 0, x: direction * -40 },
      };

  useEffect(() => {
    prevPath.current = location.pathname;
  }, [location.pathname]);

  return (
    <div className={styles.shell}>
      {/* Left: Navigation rail (3 pillars + control-room gear) */}
      <NavRail />

      {/* Center: Main content with transition choreography */}
      <main className={styles.main}>
        {/* Showroom alert banner — slides from top, non-blocking */}
        <SentinelAlertBanner />

        <AnimatePresence mode="wait" initial={false}>
          <motion.div
            key={location.pathname}
            className={styles.page}
            variants={variants}
            initial="initial"
            animate="animate"
            exit="exit"
            transition={{
              duration: 0.3,
              ease: [0.4, 0, 0.2, 1],
            }}
          >
            <Outlet />
          </motion.div>
        </AnimatePresence>
      </main>

      {/* Right: Persistent Intelligence Rail */}
      <IntelligenceRail />
    </div>
  );
}
