import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { QDRing } from './client360/QDRing';
import { useKanban } from '../../shared/hooks/useKanban';
import styles from './PipelinePillar.module.css';

/**
 * PipelinePillar — Pillar 2: Deal Intelligence
 * Merges: CRM + Comms + Sentinel
 * Default view: KanbanBoard of lead cards by pipeline stage.
 * Tapping a card → /pipeline/:personId → Client360 (no full-page nav,
 * depth choreography handled by AuthenticatedShell).
 */
export default function PipelinePillar() {
  const [viewMode, setViewMode] = useState<'board' | 'list'>('board');
  const { stages, isLoading } = useKanban();

  return (
    <div className={styles.root}>
      {/* Header */}
      <div className={styles.header}>
        <div>
          <h1 className={styles.title}>Pipeline</h1>
          <p className={styles.subtitle}>Deal Intelligence</p>
        </div>
        <div className={styles.viewToggle}>
          <button
            className={viewMode === 'board' ? styles.toggleActive : styles.toggleBtn}
            onClick={() => setViewMode('board')}
            aria-pressed={viewMode === 'board'}
          >⊞ Board</button>
          <button
            className={viewMode === 'list' ? styles.toggleActive : styles.toggleBtn}
            onClick={() => setViewMode('list')}
            aria-pressed={viewMode === 'list'}
          >≡ List</button>
        </div>
      </div>

      {/* Board */}
      {isLoading ? <KanbanSkeleton /> : (
        <KanbanBoard stages={stages} />
      )}
    </div>
  );
}

// ── KanbanBoard ───────────────────────────────────────────────
interface Stage {
  id: string;
  label: string;
  emoji: string;
  leads: Lead[];
}

interface Lead {
  id: string;
  name: string;
  location?: string;
  qdScore: number;
  qdDelta?: number;
  lastContactRelative: string;
  lastContactChannel: string;
  isVaultActive?: boolean;  // brochure currently being reviewed
}

function KanbanBoard({ stages }: { stages: Stage[] }) {
  return (
    <div className={styles.board}>
      {stages.map((stage, si) => (
        <motion.div
          key={stage.id}
          className={styles.column}
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: si * 0.06, duration: 0.35, ease: [0.4, 0, 0.2, 1] }}
        >
          {/* Column header */}
          <div className={styles.colHeader}>
            <span>{stage.emoji}</span>
            <span className={styles.colLabel}>{stage.label}</span>
            <span className={styles.colCount}>{stage.leads.length}</span>
          </div>

          {/* Lead cards */}
          <div className={styles.cards}>
            {stage.leads.map((lead, li) => (
              <LeadCard key={lead.id} lead={lead} delay={si * 0.06 + li * 0.04} />
            ))}
          </div>
        </motion.div>
      ))}
    </div>
  );
}

function LeadCard({ lead, delay }: { lead: Lead; delay: number }) {
  const navigate = useNavigate();
  const isHighIntent = lead.qdScore >= 70;
  const isVaultLive = lead.isVaultActive;

  return (
    <motion.button
      className={`${styles.card} glass-card`}
      onClick={() => navigate(`/pipeline/${lead.id}`)}
      initial={{ opacity: 0, scale: 0.96 }}
      animate={{
        opacity: 1,
        scale: 1,
        // Amber glow on vault engagement
        boxShadow: isVaultLive
          ? '0 0 16px rgba(245,158,11,0.40)'
          : 'var(--glass-shadow)',
      }}
      transition={{ delay, duration: 0.3 }}
      whileHover={{ scale: 1.02, y: -2 }}
      whileTap={{ scale: 0.99 }}
      aria-label={`View ${lead.name}'s profile`}
    >
      <div className={styles.cardTop}>
        {/* Avatar initial */}
        <div className={styles.avatar}>
          <span>{lead.name.slice(0, 1)}</span>
        </div>
        {/* Identity */}
        <div className={styles.identity}>
          <span className={styles.cardName}>{lead.name}</span>
          {lead.location && (
            <span className={styles.cardMeta}>{lead.location}</span>
          )}
        </div>
        {/* QD Ring */}
        <div className={styles.qdWrap}>
          <QDRing score={lead.qdScore} size={36} strokeWidth={3} />
        </div>
      </div>

      <div className={styles.cardBottom}>
        <span className={styles.lastContact}>
          {lead.lastContactRelative} · {lead.lastContactChannel}
        </span>
        {/* Vault live indicator */}
        {isVaultLive && (
          <span className="badge badge-high-intent" style={{ fontSize: '0.65rem' }}>
            <span className="live-dot" style={{ width: 5, height: 5 }} />
            Reviewing
          </span>
        )}
      </div>
    </motion.button>
  );
}

function KanbanSkeleton() {
  return (
    <div className={styles.board}>
      {[0, 1, 2, 3].map(i => (
        <div key={i} className={styles.column}>
          <div className={`${styles.skeletonHeader} shimmer`} />
          {[0, 1].map(j => (
            <div key={j} className={`${styles.skeletonCard} shimmer`} />
          ))}
        </div>
      ))}
    </div>
  );
}
