import { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useSentinelStore } from "../store/sentinelStore";
import styles from './IntelligenceRail.module.css';

/**
 * IntelligenceRail
 * Always-visible 48px vertical strip on the far right of the shell.
 * Present across all three pillars — never navigates away.
 *
 * Icons (top to bottom):
 *   ✦ AI pulse    — breathing when insights available
 *   🔔 Alerts     — Sentinel events + intent signals
 *   📊 KPI        — sparkline on hover
 *   ◉ Showroom    — green when CCTV session active
 *
 * Tapping any icon: 40%-width slide-in panel from right edge.
 * Dismisses by clicking away. No modal. No new page.
 */

type RailPanel = 'ai' | 'alerts' | 'kpi' | 'showroom' | null;

export function IntelligenceRail() {
  const [openPanel, setOpenPanel] = useState<RailPanel>(null);
  const { isShowroomActive, alertCount, hasInsights } = useSentinelStore();
  const panelRef = useRef<HTMLDivElement>(null);

  // Click-away dismiss
  useEffect(() => {
    if (!openPanel) return;
    const handler = (e: MouseEvent) => {
      if (panelRef.current && !panelRef.current.contains(e.target as Node)) {
        setOpenPanel(null);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [openPanel]);

  const toggle = (panel: RailPanel) =>
    setOpenPanel(prev => prev === panel ? null : panel);

  return (
    <>
      {/* ── Fixed right rail ─────────────────────────────── */}
      <aside
        className={styles.rail}
        aria-label="Intelligence Rail"
        style={{ zIndex: 'var(--z-intelligence-rail)' }}
      >
        {/* AI Insights */}
        <button
          className={`${styles.railBtn} ${hasInsights ? styles.aiBreathing : ''}`}
          onClick={() => toggle('ai')}
          aria-label="AI Insights"
          title="AI Insights"
        >
          <span>✦</span>
          {hasInsights && <span className={styles.activeDot} />}
        </button>

        {/* Alert count */}
        <button
          className={styles.railBtn}
          onClick={() => toggle('alerts')}
          aria-label={`${alertCount} alerts`}
          title="Alerts"
        >
          <span>🔔</span>
          {alertCount > 0 && (
            <span className={styles.alertBadge}>{alertCount}</span>
          )}
        </button>

        {/* KPI sparkline */}
        <button
          className={styles.railBtn}
          onClick={() => toggle('kpi')}
          aria-label="KPI Overview"
          title="KPI Overview"
        >
          <span>📊</span>
        </button>

        {/* Showroom live indicator */}
        <button
          className={`${styles.railBtn} ${isShowroomActive ? styles.showroomActive : ''}`}
          onClick={() => toggle('showroom')}
          aria-label={isShowroomActive ? 'Showroom: Live' : 'Showroom: Idle'}
          title="Showroom"
        >
          <span className={isShowroomActive ? 'live-dot pulse-green' : styles.showroomDotIdle} />
        </button>
      </aside>

      {/* ── Slide-in panel ────────────────────────────────── */}
      <AnimatePresence>
        {openPanel && (
          <>
            {/* Blurred backdrop (partial, does not cover nav) */}
            <motion.div
              className={styles.backdrop}
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.15 }}
            />

            {/* Panel */}
            <motion.div
              ref={panelRef}
              className={`${styles.panel} glass-heavy`}
              initial={{ x: '100%', opacity: 0 }}
              animate={{ x: 0, opacity: 1 }}
              exit={{ x: '100%', opacity: 0 }}
              transition={{ type: 'spring', stiffness: 320, damping: 32 }}
            >
              <div className={styles.panelHeader}>
                <span className={styles.panelTitle}>
                  {openPanel === 'ai'       && '✦ AI Insights'}
                  {openPanel === 'alerts'   && '🔔 Alerts'}
                  {openPanel === 'kpi'      && '📊 KPI Overview'}
                  {openPanel === 'showroom' && '◉ Showroom'}
                </span>
                <button
                  className={styles.closeBtn}
                  onClick={() => setOpenPanel(null)}
                  aria-label="Close panel"
                >✕</button>
              </div>

              <div className={styles.panelContent}>
                {openPanel === 'ai'       && <AIInsightsPanel />}
                {openPanel === 'alerts'   && <AlertsPanel />}
                {openPanel === 'kpi'      && <KPIPanel />}
                {openPanel === 'showroom' && <ShowroomPanel />}
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </>
  );
}

// ── Panel content stubs (expanded in P9 integration phase) ───
function AIInsightsPanel() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
      <p style={{ color: 'var(--color-text-secondary)', fontSize: 'var(--text-sm)' }}>
        AI is analyzing your pipeline...
      </p>
    </div>
  );
}

function AlertsPanel() {
  return (
    <div style={{ color: 'var(--color-text-secondary)', fontSize: 'var(--text-sm)' }}>
      No active alerts.
    </div>
  );
}

function KPIPanel() {
  return (
    <div style={{ color: 'var(--color-text-secondary)', fontSize: 'var(--text-sm)' }}>
      Loading KPI data...
    </div>
  );
}

function ShowroomPanel() {
  const { isShowroomActive, currentSessionDuration } = useSentinelStore();
  return (
    <div style={{ color: 'var(--color-text-secondary)', fontSize: 'var(--text-sm)' }}>
      {isShowroomActive
        ? `Live session: ${currentSessionDuration}`
        : 'No active showroom session.'}
    </div>
  );
}
