import { motion } from 'framer-motion';
import { QDRing } from '../QDRing';
import styles from './Intelligence.module.css';

/**
 * Intelligence Tab
 * Biometric data expressed as business meaning — never raw scores.
 * Sections: AI Insight (act-able) | Extracted Facts chips | Objections | Biometric sparkline
 */

interface IntelligenceTabProps {
  client: {
    id: string;
    aiInsight?: string;
    extractedFacts?: { budget?: string; timeline?: string; decisionMakers?: string; [key: string]: string | undefined };
    objections?: string[];
    qdHistory?: { date: string; score: number; label?: string }[];
    qdScore: number;
  };
}

export function IntelligenceTab({ client }: IntelligenceTabProps) {
  const facts = client.extractedFacts ?? {};
  const factChips = [
    { label: 'Budget',           value: facts.budget },
    { label: 'Timeline',         value: facts.timeline },
    { label: 'Decision Makers',  value: facts.decisionMakers },
    { label: 'Property Type',    value: facts.propertyType },
    { label: 'Location Pref',    value: facts.locationPreference },
  ].filter(f => f.value);

  return (
    <div className={styles.root}>
      {/* AI Insight — always first */}
      {client.aiInsight && (
        <motion.div
          className={`${styles.insightCard} glass-card glass-violet`}
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3 }}
        >
          <div className={styles.insightHeader}>
            <span className={styles.aiStar}>✦ AI INSIGHT</span>
            <button className="btn-primary">Act</button>
          </div>
          <p className={styles.insightText}>{client.aiInsight}</p>
        </motion.div>
      )}

      {/* Extracted Facts chips */}
      {factChips.length > 0 && (
        <motion.div
          className={styles.section}
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.1, duration: 0.3 }}
        >
          <h3 className={styles.sectionTitle}>EXTRACTED FACTS</h3>
          <div className={styles.chipsGrid}>
            {factChips.map(({ label, value }, i) => (
              <motion.div
                key={label}
                className={`${styles.factChip} glass`}
                initial={{ opacity: 0, scale: 0.94 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ delay: 0.15 + i * 0.05 }}
              >
                <span className={styles.chipLabel}>{label}</span>
                <span className={styles.chipValue}>{value}</span>
              </motion.div>
            ))}
          </div>
        </motion.div>
      )}

      {/* Objections */}
      {client.objections && client.objections.length > 0 && (
        <motion.div
          className={styles.section}
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2, duration: 0.3 }}
        >
          <h3 className={styles.sectionTitle}>OBJECTIONS RAISED</h3>
          <ul className={styles.objectionList}>
            {client.objections.map((obj, i) => (
              <li key={i} className={styles.objectionItem}>· {obj}</li>
            ))}
          </ul>
        </motion.div>
      )}

      {/* Biometric Engagement sparkline */}
      {client.qdHistory && client.qdHistory.length > 0 && (
        <motion.div
          className={`${styles.section} ${styles.biometricSection} glass-card`}
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3, duration: 0.3 }}
        >
          <h3 className={styles.sectionTitle}>BIOMETRIC ENGAGEMENT</h3>
          <QDSparkline history={client.qdHistory} currentScore={client.qdScore} />
          {client.qdHistory.slice(-1)[0]?.label && (
            <p className={styles.peakLabel}>
              Peak: {client.qdHistory.slice(-1)[0].label}
            </p>
          )}
        </motion.div>
      )}
    </div>
  );
}

// ── QD Sparkline (inline SVG, no charting library dependency) ─
function QDSparkline({
  history,
  currentScore,
}: { history: { date: string; score: number; label?: string }[]; currentScore: number }) {
  if (history.length < 2) return null;
  const scores = history.map(h => h.score);
  const min = Math.min(...scores);
  const max = Math.max(...scores);
  const range = max - min || 1;
  const W = 320, H = 64, PAD = 8;
  const step = (W - PAD * 2) / (scores.length - 1);

  const points = scores.map((s, i) => ({
    x: PAD + i * step,
    y: H - PAD - ((s - min) / range) * (H - PAD * 2),
  }));

  const pathD = points.map((p, i) =>
    (i === 0 ? `M ${p.x} ${p.y}` : `L ${p.x} ${p.y}`)
  ).join(' ');

  const qdColor = currentScore >= 70 ? 'var(--color-green)'
                : currentScore >= 40 ? 'var(--color-amber)'
                : 'var(--color-red)';

  return (
    <svg viewBox={`0 0 ${W} ${H}`} className={styles.sparkline}>
      <path d={pathD} fill="none" stroke={qdColor} strokeWidth="2" strokeLinecap="round" />
      {/* Peak dot */}
      {points.map((p, i) => scores[i] === max && (
        <circle key={i} cx={p.x} cy={p.y} r="4"
          fill={qdColor} opacity="0.9" />
      ))}
    </svg>
  );
}
