import { NavLink, useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { useAuthStore } from '../../store/authStore';
import styles from './NavRail.module.css';

/**
 * NavRail
 * The three-pillar navigation rail.
 * Spatial model: Command (top) → Pipeline (mid) → Studio (bottom).
 * Control Room gear icon at very bottom for admins only.
 * Active indicator: animated pill that slides between positions.
 */

const PILLARS = [
  {
    path: '/command',
    label: 'Command',
    sublabel: 'Morning Briefing',
    icon: CommandIcon,
  },
  {
    path: '/pipeline',
    label: 'Pipeline',
    sublabel: 'Deal Intelligence',
    icon: PipelineIcon,
  },
  {
    path: '/studio',
    label: 'Studio',
    sublabel: 'Asset Hub',
    icon: StudioIcon,
  },
] as const;

export function NavRail() {
  const { user } = useAuthStore();
  const role = String(user?.role ?? '').trim().toUpperCase();
  const isAdmin = role === 'ADMIN' || role === 'SALES_DIRECTOR' || role === 'SUPERADMIN';

  return (
    <nav className={styles.rail} aria-label="Main navigation">
      {/* Brand mark */}
      <div className={styles.brand}>
        <VelocityLogomark />
      </div>

      {/* Pillar links */}
      <div className={styles.pillars}>
        {PILLARS.map(({ path, label, sublabel, icon: Icon }) => (
          <NavLink
            key={path}
            to={path}
            className={({ isActive }) =>
              `${styles.pillarLink} ${isActive ? styles.active : ''}`
            }
            aria-label={`${label}: ${sublabel}`}
          >
            {({ isActive }) => (
              <>
                {isActive && (
                  <motion.div
                    layoutId="nav-active-pill"
                    className={styles.activePill}
                    transition={{ type: 'spring', stiffness: 400, damping: 35 }}
                  />
                )}
                <span className={styles.iconWrap}>
                  <Icon active={isActive} />
                </span>
                <span className={styles.labelWrap}>
                  <span className={styles.label}>{label}</span>
                  <span className={styles.sublabel}>{sublabel}</span>
                </span>
              </>
            )}
          </NavLink>
        ))}
      </div>

      {/* Bottom: User avatar + Admin gear */}
      <div className={styles.bottom}>
        {isAdmin && (
          <NavLink
            to="/control-room"
            className={styles.adminLink}
            aria-label="Control Room (Admin)"
            title="Control Room"
          >
            <GearIcon />
          </NavLink>
        )}
        <UserAvatar user={user} />
      </div>
    </nav>
  );
}

// ── Icon components ───────────────────────────────────────────
function CommandIcon({ active }: { active: boolean }) {
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
      <path
        d="M3 5h14M3 10h14M3 15h8"
        stroke={active ? 'var(--color-violet-light)' : 'currentColor'}
        strokeWidth="1.5"
        strokeLinecap="round"
      />
      <circle
        cx="16"
        cy="15"
        r="2"
        fill={active ? 'var(--color-violet)' : 'transparent'}
        stroke={active ? 'var(--color-violet-light)' : 'currentColor'}
        strokeWidth="1.5"
      />
    </svg>
  );
}

function PipelineIcon({ active }: { active: boolean }) {
  const c = active ? 'var(--color-violet-light)' : 'currentColor';
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
      <rect x="2" y="4" width="4" height="12" rx="1"
        fill={active ? 'var(--color-violet-glow)' : 'transparent'}
        stroke={c} strokeWidth="1.5" />
      <rect x="8" y="7" width="4" height="9" rx="1"
        fill={active ? 'var(--color-violet-glow)' : 'transparent'}
        stroke={c} strokeWidth="1.5" />
      <rect x="14" y="2" width="4" height="14" rx="1"
        fill={active ? 'var(--color-violet)' : 'transparent'}
        stroke={c} strokeWidth="1.5" />
    </svg>
  );
}

function StudioIcon({ active }: { active: boolean }) {
  const c = active ? 'var(--color-violet-light)' : 'currentColor';
  return (
    <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
      <rect x="2" y="2" width="7" height="7" rx="1.5" stroke={c} strokeWidth="1.5" />
      <rect x="11" y="2" width="7" height="7" rx="1.5"
        fill={active ? 'var(--color-violet)' : 'transparent'}
        stroke={c} strokeWidth="1.5" />
      <rect x="2" y="11" width="7" height="7" rx="1.5" stroke={c} strokeWidth="1.5" />
      <rect x="11" y="11" width="7" height="7" rx="1.5" stroke={c} strokeWidth="1.5" />
    </svg>
  );
}

function GearIcon() {
  return (
    <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
      <circle cx="9" cy="9" r="2.5" stroke="currentColor" strokeWidth="1.5" />
      <path
        d="M9 1.5v2M9 14.5v2M1.5 9h2M14.5 9h2M3.6 3.6l1.4 1.4M13 13l1.4 1.4M3.6 14.4l1.4-1.4M13 5l1.4-1.4"
        stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"
      />
    </svg>
  );
}

function VelocityLogomark() {
  return (
    <div style={{
      width: 32, height: 32,
      borderRadius: 'var(--radius-md)',
      background: 'var(--color-violet)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      boxShadow: 'var(--glass-shadow-violet)',
    }}>
      <span style={{ color: 'white', fontWeight: 700, fontSize: 14 }}>V</span>
    </div>
  );
}

function UserAvatar({ user }: { user: any }) {
  const initials = user
    ? (user.name ?? user.email ?? '?').slice(0, 1).toUpperCase()
    : '?';
  return (
    <button className={styles.avatarBtn} aria-label="User profile" title={user?.email}>
      {user?.avatar_url
        ? <img src={user.avatar_url} alt={initials} />
        : <span>{initials}</span>
      }
    </button>
  );
}
