import React, { useState, useMemo } from 'react';
import {
  BarChart, Bar, LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip,
  Legend, ResponsiveContainer, RadarChart, Radar, PolarGrid, PolarAngleAxis,
  Cell,
} from 'recharts';
import { useProject } from '../../context/ProjectContext';

// ── Mock Data ──────────────────────────────────────────────────────────────────
const MOCK_PROJECTS_NPS = [
  { id: 'p4', code: 'PRY-2026-004', name: 'Construcción AR-ProjectManagement Norte', client: 'Inmobiliaria Del Valle' },
  { id: 'p4', code: 'PRY-2026-004', name: 'AR-ProjectManagement "Horizontes"', client: 'Sony Music Latin' },
  { id: 'p4', code: 'PRY-2026-004', name: 'Implementación AR-ProjectManagement', client: 'Grupo Empresarial XYZ' },
  { id: 'p4', code: 'PRY-2026-004', name: 'AR-ProjectManagement — Plataforma ERP', client: 'AR Electronics' },
];

const MOCK_SURVEYS = [
  {
    id: 'enc-001', projectId: 'p4', project: 'PRY-2026-004', client: 'Inmobiliaria Del Valle',
    contact: 'Carlos Mendoza', email: 'cmendoza@delvalle.com',
    sentDate: '2026-04-15', responseDate: '2026-04-17', npsScore: 9, status: 'RESPONDIDA',
    type: 'POST_HITO',
    answers: { comunicacion: 5, calidad: 4, plazos: 4, presupuesto: 5, satisfaccion: 5 },
    openText: 'El equipo ha demostrado gran profesionalismo. Las reuniones de seguimiento son muy útiles. Nos gustaría ver mejoras en el reporte de avance semanal.',
  },
  {
    id: 'enc-002', projectId: 'p4', project: 'PRY-2026-004', client: 'Inmobiliaria Del Valle',
    contact: 'Ana Ríos', email: 'arios@delvalle.com',
    sentDate: '2026-05-10', responseDate: '2026-05-12', npsScore: 8, status: 'RESPONDIDA',
    type: 'TRIMESTRAL',
    answers: { comunicacion: 4, calidad: 5, plazos: 4, presupuesto: 4, satisfaccion: 4 },
    openText: 'La calidad de los materiales es excelente. Mejorar la comunicación ante imprevistos sería ideal.',
  },
  {
    id: 'enc-003', projectId: 'p4', project: 'PRY-2026-004', client: 'Sony Music Latin',
    contact: 'Diego Fuentes', email: 'dfuentes@sonymusic.com',
    sentDate: '2026-04-20', responseDate: '2026-04-22', npsScore: 8, status: 'RESPONDIDA',
    type: 'POST_ENTREGABLE',
    answers: { comunicacion: 4, calidad: 5, plazos: 4, presupuesto: 3, satisfaccion: 4 },
    openText: 'La producción musical supera expectativas. El presupuesto tuvo algunas variaciones no comunicadas a tiempo.',
  },
  {
    id: 'enc-004', projectId: 'p4', project: 'PRY-2026-004', client: 'Sony Music Latin',
    contact: 'Laura Pinto', email: 'lpinto@sonymusic.com',
    sentDate: '2026-05-28', responseDate: null, npsScore: null, status: 'SIN_RESPONDER',
    type: 'CIERRE',
    answers: null, openText: null,
  },
  {
    id: 'enc-005', projectId: 'p4', project: 'PRY-2026-004', client: 'Grupo Empresarial XYZ',
    contact: 'Roberto Salas', email: 'rsalas@grupoxyz.com',
    sentDate: '2026-03-15', responseDate: '2026-03-18', npsScore: 6, status: 'RESPONDIDA',
    type: 'POST_HITO',
    answers: { comunicacion: 3, calidad: 3, plazos: 2, presupuesto: 3, satisfaccion: 3 },
    openText: 'La implementación del ERP ha tenido retrasos importantes. El soporte técnico no responde con agilidad. Esperamos mejoras urgentes en cumplimiento de plazos y comunicación proactiva.',
  },
  {
    id: 'enc-006', projectId: 'p4', project: 'PRY-2026-004', client: 'Grupo Empresarial XYZ',
    contact: 'Mónica Vega', email: 'mvega@grupoxyz.com',
    sentDate: '2026-04-01', responseDate: null, npsScore: null, status: 'VENCIDA',
    type: 'TRIMESTRAL',
    answers: null, openText: null,
  },
  {
    id: 'enc-007', projectId: 'p4', project: 'PRY-2026-004', client: 'AR Electronics',
    contact: 'Álvaro Romero', email: 'alro65@gmail.com',
    sentDate: '2026-05-01', responseDate: '2026-05-02', npsScore: 10, status: 'RESPONDIDA',
    type: 'POST_ENTREGABLE',
    answers: { comunicacion: 5, calidad: 5, plazos: 4, presupuesto: 5, satisfaccion: 5 },
    openText: 'El equipo ha entregado exactamente lo que necesitábamos. La plataforma es intuitiva y poderosa. Me gustaría ver más opciones de personalización en los dashboards.',
  },
  {
    id: 'enc-008', projectId: 'p4', project: 'PRY-2026-004', client: 'AR Electronics',
    contact: 'Sofía Castro', email: 'scastro@arelectronics.com',
    sentDate: '2026-06-01', responseDate: null, npsScore: null, status: 'ENVIADA',
    type: 'CIERRE',
    answers: null, openText: null,
  },
];

const NPS_TREND = [
  { month: 'Ene', nps: 28 },
  { month: 'Feb', nps: 33 },
  { month: 'Mar', nps: 30 },
  { month: 'Abr', nps: 38 },
  { month: 'May', nps: 44 },
  { month: 'Jun', nps: 42 },
];

const PROJECT_NPS_DATA = [
  { name: 'AR-ProjectManagement', nps: 58, projectId: 'p4' },
  { name: 'Álbum Horizontes', nps: 45, projectId: 'p4' },
  { name: 'AR-ProjectManagement', nps: 18, projectId: 'p4' },
  { name: 'ARPM Plataforma', nps: 67, projectId: 'p4' },
];

const WORD_CLOUD_WORDS = [
  { word: 'comunicación', size: 'text-2xl', weight: 'font-bold', color: 'text-blue-600 dark:text-blue-400' },
  { word: 'calidad', size: 'text-3xl', weight: 'font-black', color: 'text-green-600 dark:text-green-400' },
  { word: 'plazos', size: 'text-xl', weight: 'font-bold', color: 'text-red-500 dark:text-red-400' },
  { word: 'profesionalismo', size: 'text-lg', weight: 'font-semibold', color: 'text-purple-600 dark:text-purple-400' },
  { word: 'seguimiento', size: 'text-base', weight: 'font-medium', color: 'text-slate-600 dark:text-slate-300' },
  { word: 'soporte', size: 'text-xl', weight: 'font-bold', color: 'text-amber-600 dark:text-amber-400' },
  { word: 'retrasos', size: 'text-lg', weight: 'font-semibold', color: 'text-red-400 dark:text-red-300' },
  { word: 'entregables', size: 'text-base', weight: 'font-medium', color: 'text-teal-600 dark:text-teal-400' },
  { word: 'presupuesto', size: 'text-xl', weight: 'font-bold', color: 'text-orange-500 dark:text-orange-400' },
  { word: 'reuniones', size: 'text-sm', weight: 'font-medium', color: 'text-slate-500 dark:text-slate-400' },
  { word: 'dashboards', size: 'text-base', weight: 'font-medium', color: 'text-blue-500 dark:text-blue-300' },
  { word: 'implementación', size: 'text-lg', weight: 'font-semibold', color: 'text-purple-500 dark:text-purple-300' },
  { word: 'materiales', size: 'text-sm', weight: 'font-normal', color: 'text-slate-400 dark:text-slate-500' },
  { word: 'producción', size: 'text-base', weight: 'font-medium', color: 'text-green-500 dark:text-green-300' },
  { word: 'personalización', size: 'text-sm', weight: 'font-medium', color: 'text-indigo-500 dark:text-indigo-400' },
];

const ACTION_ITEMS = [
  { dimension: 'Cumplimiento de plazos', current: 3.2, target: 4.0, action: 'Implementar alertas tempranas de riesgo de retraso', owner: 'Gerente de Proyecto' },
  { dimension: 'Gestión del presupuesto', current: 3.8, target: 4.5, action: 'Establecer comunicación proactiva ante variaciones', owner: 'Director Financiero' },
  { dimension: 'Comunicación del equipo', current: 4.1, target: 4.5, action: 'Reporte semanal de avance estructurado', owner: 'Coordinador de Proyecto' },
  { dimension: 'Calidad de entregables', current: 4.4, target: 4.8, action: 'Checklist de calidad pre-entrega obligatorio', owner: 'Control de Calidad' },
  { dimension: 'Satisfacción general', current: 4.2, target: 4.6, action: 'Encuestas intermedias de satisfacción', owner: 'Gestión de Clientes' },
];

// ── Helpers ────────────────────────────────────────────────────────────────────
function npsColor(score) {
  if (score === null || score === undefined) return 'text-slate-400';
  if (score < 0) return 'text-red-500';
  if (score < 30) return 'text-amber-500';
  if (score < 70) return 'text-green-500';
  return 'text-blue-500';
}

function npsBarColor(score) {
  if (score < 0) return '#ef4444';
  if (score < 30) return '#f59e0b';
  if (score < 70) return '#10b981';
  return '#3b82f6';
}

function npsLabel(score) {
  if (score < 0) return 'Crítico';
  if (score < 30) return 'Mejorable';
  if (score < 70) return 'Bueno';
  return 'Excelente';
}

function npsScoreColor(s) {
  if (s >= 9) return 'text-green-500';
  if (s >= 7) return 'text-amber-500';
  return 'text-red-500';
}

function scoreBarColor(s) {
  if (s >= 4) return 'bg-green-500';
  if (s >= 3) return 'bg-amber-500';
  return 'bg-red-500';
}

const STATUS_STYLE = {
  ENVIADA:      'bg-blue-100 text-blue-700 dark:bg-blue-500/20 dark:text-blue-300',
  RESPONDIDA:   'bg-green-100 text-green-700 dark:bg-green-500/20 dark:text-green-300',
  SIN_RESPONDER:'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-300',
  VENCIDA:      'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-300',
};

const STATUS_LABEL = {
  ENVIADA: 'Enviada', RESPONDIDA: 'Respondida', SIN_RESPONDER: 'Sin responder', VENCIDA: 'Vencida',
};

const SURVEY_TYPE_LABEL = {
  POST_HITO: 'Post-Hito', POST_ENTREGABLE: 'Post-Entregable', CIERRE: 'Cierre', TRIMESTRAL: 'Trimestral',
};

// ── Icons ──────────────────────────────────────────────────────────────────────
function IconX({ className = 'w-5 h-5' }) {
  return <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" /></svg>;
}
function IconPlus({ className = 'w-4 h-4' }) {
  return <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" /></svg>;
}
function IconEye({ className = 'w-4 h-4' }) {
  return <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /><path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.477 0 8.268 2.943 9.542 7-1.274 4.057-5.065 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" /></svg>;
}

// ── NPS Gauge ─────────────────────────────────────────────────────────────────
function NPSGauge({ score }) {
  const clamped = Math.max(-100, Math.min(100, score));
  const pct = (clamped + 100) / 200;
  const angle = -140 + pct * 280;
  const r = 80;
  const cx = 100, cy = 100;
  const rad = (deg) => (deg * Math.PI) / 180;
  const arcPath = (startDeg, endDeg, radius, color) => {
    const s = rad(startDeg - 90);
    const e = rad(endDeg - 90);
    const x1 = cx + radius * Math.cos(s);
    const y1 = cy + radius * Math.sin(s);
    const x2 = cx + radius * Math.cos(e);
    const y2 = cy + radius * Math.sin(e);
    const large = endDeg - startDeg > 180 ? 1 : 0;
    return (
      <path
        d={`M ${x1} ${y1} A ${radius} ${radius} 0 ${large} 1 ${x2} ${y2}`}
        fill="none" stroke={color} strokeWidth={14} strokeLinecap="round"
      />
    );
  };
  const needleAngle = rad(angle - 90);
  const nx = cx + 60 * Math.cos(needleAngle);
  const ny = cy + 60 * Math.sin(needleAngle);

  const colorMap = score < 0 ? '#ef4444' : score < 30 ? '#f59e0b' : score < 70 ? '#10b981' : '#3b82f6';

  return (
    <div className="flex flex-col items-center">
      <svg viewBox="20 30 160 100" className="w-56 h-32">
        {arcPath(-140, -47, r, '#ef4444')}
        {arcPath(-47, 0, r, '#f59e0b')}
        {arcPath(0, 70, r, '#10b981')}
        {arcPath(70, 140, r, '#3b82f6')}
        <line x1={cx} y1={cy} x2={nx} y2={ny} stroke={colorMap} strokeWidth={3} strokeLinecap="round" />
        <circle cx={cx} cy={cy} r={5} fill={colorMap} />
      </svg>
      <div className={`text-5xl font-black -mt-4 ${npsColor(score)}`}>{score}</div>
      <div className={`text-sm font-semibold mt-1 ${npsColor(score)}`}>{npsLabel(score)}</div>
      <div className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">NPS del Portafolio</div>
    </div>
  );
}

// ── NewSurveyModal ─────────────────────────────────────────────────────────────
function NewSurveyModal({ onClose }) {
  const [form, setForm] = useState({
    projectId: 'p4', clientName: '', email: '', type: 'POST_HITO', scheduledDate: '',
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 w-full max-w-md shadow-2xl">
        <div className="flex items-center justify-between p-6 border-b border-slate-200 dark:border-slate-700">
          <h3 className="text-slate-900 dark:text-white font-bold text-lg">Nueva Encuesta NPS</h3>
          <button onClick={onClose} className="p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-500 dark:text-slate-400">
            <IconX />
          </button>
        </div>
        <div className="p-6 space-y-4">
          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase mb-1.5 block">Proyecto</label>
            <select value={form.projectId} onChange={e => set('projectId', e.target.value)}
              className="w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-3 py-2 text-sm text-slate-900 dark:text-white">
              {MOCK_PROJECTS_NPS.map(p => <option key={p.id} value={p.id}>{p.code} — {p.client}</option>)}
            </select>
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase mb-1.5 block">Nombre del contacto</label>
            <input value={form.clientName} onChange={e => set('clientName', e.target.value)} placeholder="Ej: Carlos Mendoza"
              className="w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-3 py-2 text-sm text-slate-900 dark:text-white placeholder-slate-400" />
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase mb-1.5 block">Email</label>
            <input type="email" value={form.email} onChange={e => set('email', e.target.value)} placeholder="contacto@empresa.com"
              className="w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-3 py-2 text-sm text-slate-900 dark:text-white placeholder-slate-400" />
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase mb-1.5 block">Tipo de encuesta</label>
            <select value={form.type} onChange={e => set('type', e.target.value)}
              className="w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-3 py-2 text-sm text-slate-900 dark:text-white">
              {Object.entries(SURVEY_TYPE_LABEL).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
            </select>
          </div>
          <div>
            <label className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase mb-1.5 block">Fecha programada</label>
            <input type="date" value={form.scheduledDate} onChange={e => set('scheduledDate', e.target.value)}
              className="w-full bg-slate-50 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl px-3 py-2 text-sm text-slate-900 dark:text-white" />
          </div>
        </div>
        <div className="flex gap-3 p-6 border-t border-slate-200 dark:border-slate-700">
          <button onClick={onClose}
            className="flex-1 border border-slate-200 dark:border-slate-700 text-slate-700 dark:text-slate-300 rounded-xl px-4 py-2.5 text-sm font-medium hover:bg-slate-50 dark:hover:bg-slate-800">
            Cancelar
          </button>
          <button onClick={onClose}
            className="flex-1 bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300 rounded-xl px-4 py-2.5 text-sm font-medium hover:bg-slate-200 dark:hover:bg-slate-700">
            Programar
          </button>
          <button onClick={onClose}
            className="flex-1 bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2.5 text-sm font-medium">
            Enviar ahora
          </button>
        </div>
      </div>
    </div>
  );
}

// ── SurveyDetailModal ──────────────────────────────────────────────────────────
function SurveyDetailModal({ survey, onClose }) {
  const radarData = survey.answers ? [
    { subject: 'Comunicación', value: survey.answers.comunicacion },
    { subject: 'Calidad', value: survey.answers.calidad },
    { subject: 'Plazos', value: survey.answers.plazos },
    { subject: 'Presupuesto', value: survey.answers.presupuesto },
    { subject: 'Satisfacción', value: survey.answers.satisfaccion },
  ] : [];

  const dims = [
    { key: 'comunicacion', label: 'Comunicación del equipo' },
    { key: 'calidad', label: 'Calidad de los entregables' },
    { key: 'plazos', label: 'Cumplimiento de plazos' },
    { key: 'presupuesto', label: 'Gestión del presupuesto' },
    { key: 'satisfaccion', label: 'Satisfacción general' },
  ];

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 overflow-y-auto">
      <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 w-full max-w-2xl shadow-2xl my-4">
        <div className="flex items-center justify-between p-6 border-b border-slate-200 dark:border-slate-700">
          <div>
            <h3 className="text-slate-900 dark:text-white font-bold text-lg">Respuesta de Encuesta</h3>
            <p className="text-slate-500 dark:text-slate-400 text-sm mt-0.5">{survey.contact} · {survey.project}</p>
          </div>
          <button onClick={onClose} className="p-1.5 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 text-slate-500 dark:text-slate-400">
            <IconX />
          </button>
        </div>
        <div className="p-6 space-y-6">
          {/* NPS score */}
          <div className="bg-slate-50 dark:bg-slate-800 rounded-xl p-4 flex items-center gap-4">
            <div className={`text-5xl font-black ${npsScoreColor(survey.npsScore)}`}>{survey.npsScore}</div>
            <div>
              <p className="text-slate-900 dark:text-white font-semibold">¿Qué tan probable es que recomiendes nuestros servicios?</p>
              <p className="text-slate-500 dark:text-slate-400 text-sm">Escala del 0 al 10</p>
              <div className={`inline-block mt-1 rounded-full px-2.5 py-0.5 text-xs font-medium ${survey.npsScore >= 9 ? 'bg-green-100 text-green-700 dark:bg-green-500/20 dark:text-green-300' : survey.npsScore >= 7 ? 'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-300' : 'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-300'}`}>
                {survey.npsScore >= 9 ? 'Promotor' : survey.npsScore >= 7 ? 'Pasivo' : 'Detractor'}
              </div>
            </div>
          </div>

          {/* Dimensions */}
          <div>
            <h4 className="text-slate-900 dark:text-white font-semibold text-sm mb-3">Dimensiones de evaluación (1–5)</h4>
            <div className="space-y-3">
              {dims.map(d => {
                const val = survey.answers?.[d.key] ?? 0;
                return (
                  <div key={d.key} className="flex items-center gap-3">
                    <span className="text-slate-600 dark:text-slate-300 text-sm w-44 shrink-0">{d.label}</span>
                    <div className="flex-1 bg-slate-100 dark:bg-slate-800 rounded-full h-2">
                      <div className={`h-2 rounded-full ${scoreBarColor(val)}`} style={{ width: `${(val / 5) * 100}%` }} />
                    </div>
                    <span className="text-slate-900 dark:text-white font-bold text-sm w-6 text-right">{val}</span>
                  </div>
                );
              })}
            </div>
          </div>

          {/* Radar chart */}
          <div>
            <h4 className="text-slate-900 dark:text-white font-semibold text-sm mb-3">Radar de Satisfacción</h4>
            <ResponsiveContainer width="100%" height={220}>
              <RadarChart data={radarData} cx="50%" cy="50%" outerRadius={80}>
                <PolarGrid stroke="#e2e8f0" />
                <PolarAngleAxis dataKey="subject" tick={{ fill: '#94a3b8', fontSize: 11 }} />
                <Radar name="Score" dataKey="value" stroke="#3b82f6" fill="#3b82f6" fillOpacity={0.25} />
              </RadarChart>
            </ResponsiveContainer>
          </div>

          {/* Open text */}
          {survey.openText && (
            <div>
              <h4 className="text-slate-900 dark:text-white font-semibold text-sm mb-2">¿Qué podríamos mejorar?</h4>
              <p className="bg-slate-50 dark:bg-slate-800 rounded-xl p-4 text-slate-600 dark:text-slate-300 text-sm italic">
                "{survey.openText}"
              </p>
            </div>
          )}
        </div>
        <div className="p-6 border-t border-slate-200 dark:border-slate-700">
          <button onClick={onClose}
            className="w-full bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2.5 text-sm font-medium">
            Cerrar
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Custom Bar shape for colored NPS bars ──────────────────────────────────────
function CustomNPSBar(props) {
  const { x, y, width, height, nps } = props;
  return <rect x={x} y={y} width={width} height={height} fill={npsBarColor(nps)} rx={4} />;
}

// ── Main Component ─────────────────────────────────────────────────────────────
export default function NPSPage() {
  const { selectedProjectId } = useProject();
  const [activeTab, setActiveTab] = useState('dashboard');
  const [showNewSurvey, setShowNewSurvey] = useState(false);
  const [detailSurvey, setDetailSurvey] = useState(null);

  const surveys = useMemo(() =>
    MOCK_SURVEYS.filter(s => !selectedProjectId || s.projectId === selectedProjectId),
    [selectedProjectId]
  );

  const projectNpsData = useMemo(() =>
    PROJECT_NPS_DATA.filter(p => !selectedProjectId || p.projectId === selectedProjectId),
    [selectedProjectId]
  );

  const respondidas = surveys.filter(s => s.status === 'RESPONDIDA');
  const portfolioNPS = useMemo(() => {
    if (respondidas.length === 0) return 42;
    const scores = respondidas.map(s => s.npsScore);
    const promoters = scores.filter(s => s >= 9).length / scores.length * 100;
    const detractors = scores.filter(s => s <= 6).length / scores.length * 100;
    return Math.round(promoters - detractors);
  }, [respondidas]);

  const promotoresPct = respondidas.length
    ? Math.round(respondidas.filter(s => s.npsScore >= 9).length / respondidas.length * 100) : 0;
  const pasivosPct = respondidas.length
    ? Math.round(respondidas.filter(s => s.npsScore >= 7 && s.npsScore <= 8).length / respondidas.length * 100) : 0;
  const detractoresPct = respondidas.length
    ? Math.round(respondidas.filter(s => s.npsScore <= 6).length / respondidas.length * 100) : 0;

  const avgRadarData = useMemo(() => {
    const defs = ['comunicacion', 'calidad', 'plazos', 'presupuesto', 'satisfaccion'];
    const labels = { comunicacion: 'Comunicación', calidad: 'Calidad', plazos: 'Plazos', presupuesto: 'Presupuesto', satisfaccion: 'Satisfacción' };
    const rs = respondidas.filter(s => s.answers);
    if (!rs.length) return defs.map(k => ({ subject: labels[k], value: 0 }));
    return defs.map(k => ({
      subject: labels[k],
      value: +(rs.reduce((acc, s) => acc + (s.answers[k] || 0), 0) / rs.length).toFixed(1),
    }));
  }, [respondidas]);

  const responseRateData = useMemo(() => {
    return MOCK_PROJECTS_NPS
      .filter(p => !selectedProjectId || p.id === selectedProjectId)
      .map(p => {
        const ps = MOCK_SURVEYS.filter(s => s.projectId === p.id);
        const resp = ps.filter(s => s.status === 'RESPONDIDA').length;
        return { name: p.code.replace('PRY-2026-', 'PRY-'), rate: ps.length ? Math.round((resp / ps.length) * 100) : 0 };
      });
  }, [selectedProjectId]);

  const tabs = [
    { key: 'dashboard', label: 'Dashboard NPS' },
    { key: 'encuestas', label: 'Encuestas' },
    { key: 'analisis', label: 'Análisis' },
  ];

  return (
    <div className="min-h-screen bg-slate-50 dark:bg-slate-950 p-4 md:p-6 lg:p-8">
      <div className="max-w-7xl mx-auto space-y-6">

        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-slate-900 dark:text-white">NPS y Satisfacción del Cliente</h1>
            <p className="text-slate-500 dark:text-slate-400 text-sm mt-0.5">Seguimiento de satisfacción y Net Promoter Score</p>
          </div>
          <button onClick={() => setShowNewSurvey(true)}
            className="flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2.5 text-sm font-medium">
            <IconPlus /> Nueva Encuesta
          </button>
        </div>

        {/* Tabs */}
        <div className="flex gap-0 border-b border-slate-200 dark:border-slate-700">
          {tabs.map(t => (
            <button key={t.key} onClick={() => setActiveTab(t.key)}
              className={`px-5 py-3 text-sm font-medium transition-colors ${activeTab === t.key
                ? 'border-b-2 border-blue-600 text-blue-600 dark:text-blue-400'
                : 'text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-300'}`}>
              {t.label}
            </button>
          ))}
        </div>

        {/* ── Tab: Dashboard NPS ── */}
        {activeTab === 'dashboard' && (
          <div className="space-y-6">
            {/* Top row: gauge + KPIs */}
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              {/* Gauge */}
              <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6 flex flex-col items-center justify-center">
                <NPSGauge score={portfolioNPS} />
                <div className="mt-3 text-xs text-slate-500 dark:text-slate-400 text-center">
                  Basado en {surveys.length} encuestas · {respondidas.length} respondidas
                </div>
              </div>

              {/* KPI cards */}
              <div className="lg:col-span-2 grid grid-cols-2 gap-4">
                {[
                  { label: 'Promotores', value: `${promotoresPct}%`, sub: 'Score 9-10', color: 'text-green-500', bg: 'bg-green-50 dark:bg-green-500/10' },
                  { label: 'Pasivos', value: `${pasivosPct}%`, sub: 'Score 7-8', color: 'text-amber-500', bg: 'bg-amber-50 dark:bg-amber-500/10' },
                  { label: 'Detractores', value: `${detractoresPct}%`, sub: 'Score 0-6', color: 'text-red-500', bg: 'bg-red-50 dark:bg-red-500/10' },
                  { label: 'Tasa de respuesta', value: `${respondidas.length}/${surveys.length}`, sub: `${surveys.length ? Math.round(respondidas.length / surveys.length * 100) : 0}% respondidas`, color: 'text-blue-500', bg: 'bg-blue-50 dark:bg-blue-500/10' },
                ].map(k => (
                  <div key={k.label} className={`rounded-2xl border border-slate-200 dark:border-slate-700 p-5 ${k.bg}`}>
                    <p className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase">{k.label}</p>
                    <p className={`text-3xl font-black mt-1 ${k.color}`}>{k.value}</p>
                    <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5">{k.sub}</p>
                  </div>
                ))}
              </div>
            </div>

            {/* Charts row */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* NPS by project */}
              <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
                <h3 className="text-slate-900 dark:text-white font-bold mb-4">NPS por Proyecto</h3>
                <ResponsiveContainer width="100%" height={220}>
                  <BarChart data={projectNpsData} margin={{ top: 4, right: 8, left: -20, bottom: 0 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                    <XAxis dataKey="name" tick={{ fill: '#94a3b8', fontSize: 11 }} />
                    <YAxis domain={[-20, 80]} tick={{ fill: '#94a3b8', fontSize: 11 }} />
                    <Tooltip formatter={(v) => [v, 'NPS']} contentStyle={{ background: '#1e293b', border: 'none', borderRadius: 8, color: '#f1f5f9' }} />
                    <Bar dataKey="nps" radius={[4, 4, 0, 0]}>
                      {projectNpsData.map((entry, i) => (
                        <Cell key={i} fill={npsBarColor(entry.nps)} />
                      ))}
                    </Bar>
                  </BarChart>
                </ResponsiveContainer>
              </div>

              {/* NPS trend */}
              <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
                <h3 className="text-slate-900 dark:text-white font-bold mb-4">Tendencia NPS — Últimos 6 meses</h3>
                <ResponsiveContainer width="100%" height={220}>
                  <LineChart data={NPS_TREND} margin={{ top: 4, right: 8, left: -20, bottom: 0 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                    <XAxis dataKey="month" tick={{ fill: '#94a3b8', fontSize: 11 }} />
                    <YAxis domain={[0, 60]} tick={{ fill: '#94a3b8', fontSize: 11 }} />
                    <Tooltip formatter={(v) => [v, 'NPS']} contentStyle={{ background: '#1e293b', border: 'none', borderRadius: 8, color: '#f1f5f9' }} />
                    <Line type="monotone" dataKey="nps" stroke="#3b82f6" strokeWidth={2.5} dot={{ fill: '#3b82f6', r: 4 }} activeDot={{ r: 6 }} />
                  </LineChart>
                </ResponsiveContainer>
              </div>
            </div>

            {/* Recent responses */}
            <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
              <h3 className="text-slate-900 dark:text-white font-bold mb-4">Respuestas Recientes</h3>
              <div className="space-y-3">
                {respondidas.slice(0, 5).map(s => (
                  <div key={s.id} className="flex items-start gap-4 p-3 rounded-xl hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors">
                    <div className={`text-2xl font-black w-12 text-center mt-0.5 ${npsScoreColor(s.npsScore)}`}>{s.npsScore}</div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span className="text-slate-900 dark:text-white font-semibold text-sm">{s.contact}</span>
                        <span className="text-slate-400 dark:text-slate-500 text-xs">·</span>
                        <span className="text-slate-500 dark:text-slate-400 text-xs">{s.project}</span>
                        <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${s.npsScore >= 9 ? 'bg-green-100 text-green-700 dark:bg-green-500/20 dark:text-green-300' : s.npsScore >= 7 ? 'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-300' : 'bg-red-100 text-red-700 dark:bg-red-500/20 dark:text-red-300'}`}>
                          {s.npsScore >= 9 ? 'Promotor' : s.npsScore >= 7 ? 'Pasivo' : 'Detractor'}
                        </span>
                      </div>
                      {s.openText && (
                        <p className="text-slate-500 dark:text-slate-400 text-xs mt-0.5 line-clamp-1 italic">"{s.openText}"</p>
                      )}
                    </div>
                    <span className="text-slate-400 dark:text-slate-500 text-xs shrink-0">{s.responseDate}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* ── Tab: Encuestas ── */}
        {activeTab === 'encuestas' && (
          <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
            <div className="p-6 border-b border-slate-200 dark:border-slate-700 flex items-center justify-between">
              <h3 className="text-slate-900 dark:text-white font-bold">Encuestas NPS</h3>
              <button onClick={() => setShowNewSurvey(true)}
                className="flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white rounded-xl px-4 py-2 text-sm font-medium">
                <IconPlus className="w-3.5 h-3.5" /> Nueva Encuesta
              </button>
            </div>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-slate-50 dark:bg-slate-800/50">
                  <tr>
                    {['ID', 'Proyecto', 'Cliente', 'Tipo', 'Enviada', 'Respondida', 'Score NPS', 'Estado', 'Acción'].map(h => (
                      <th key={h} className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left whitespace-nowrap">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
                  {surveys.map(s => (
                    <tr key={s.id} className="hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors">
                      <td className="px-4 py-3 text-xs font-mono text-slate-500 dark:text-slate-400">{s.id}</td>
                      <td className="px-4 py-3">
                        <span className="text-xs font-medium text-slate-700 dark:text-slate-300">{s.project}</span>
                      </td>
                      <td className="px-4 py-3">
                        <div className="text-sm text-slate-900 dark:text-white font-medium">{s.contact}</div>
                        <div className="text-xs text-slate-500 dark:text-slate-400">{s.email}</div>
                      </td>
                      <td className="px-4 py-3">
                        <span className="rounded-full px-2.5 py-0.5 text-xs font-medium bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300">
                          {SURVEY_TYPE_LABEL[s.type]}
                        </span>
                      </td>
                      <td className="px-4 py-3 text-sm text-slate-600 dark:text-slate-300 whitespace-nowrap">{s.sentDate}</td>
                      <td className="px-4 py-3 text-sm text-slate-600 dark:text-slate-300 whitespace-nowrap">{s.responseDate || '—'}</td>
                      <td className="px-4 py-3">
                        {s.npsScore !== null
                          ? <span className={`text-lg font-black ${npsScoreColor(s.npsScore)}`}>{s.npsScore}</span>
                          : <span className="text-slate-400 text-sm">—</span>}
                      </td>
                      <td className="px-4 py-3">
                        <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${STATUS_STYLE[s.status]}`}>
                          {STATUS_LABEL[s.status]}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        {s.status === 'RESPONDIDA' && (
                          <button onClick={() => setDetailSurvey(s)}
                            className="flex items-center gap-1.5 text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 text-xs font-medium">
                            <IconEye className="w-3.5 h-3.5" /> Ver respuestas
                          </button>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {surveys.length === 0 && (
                <div className="text-center py-12 text-slate-500 dark:text-slate-400 text-sm">
                  No hay encuestas para el proyecto seleccionado.
                </div>
              )}
            </div>
          </div>
        )}

        {/* ── Tab: Análisis ── */}
        {activeTab === 'analisis' && (
          <div className="space-y-6">
            {/* Radar + Response rate */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
                <h3 className="text-slate-900 dark:text-white font-bold mb-4">Radar de Satisfacción Promedio</h3>
                <ResponsiveContainer width="100%" height={260}>
                  <RadarChart data={avgRadarData} cx="50%" cy="50%" outerRadius={90}>
                    <PolarGrid stroke="#e2e8f0" />
                    <PolarAngleAxis dataKey="subject" tick={{ fill: '#94a3b8', fontSize: 12 }} />
                    <Radar name="Promedio" dataKey="value" stroke="#3b82f6" fill="#3b82f6" fillOpacity={0.25} />
                    <Tooltip contentStyle={{ background: '#1e293b', border: 'none', borderRadius: 8, color: '#f1f5f9' }} />
                  </RadarChart>
                </ResponsiveContainer>
              </div>

              <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
                <h3 className="text-slate-900 dark:text-white font-bold mb-4">Tasa de Respuesta por Proyecto</h3>
                <ResponsiveContainer width="100%" height={260}>
                  <BarChart data={responseRateData} margin={{ top: 4, right: 8, left: -20, bottom: 0 }}>
                    <CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" />
                    <XAxis dataKey="name" tick={{ fill: '#94a3b8', fontSize: 11 }} />
                    <YAxis domain={[0, 100]} tick={{ fill: '#94a3b8', fontSize: 11 }} unit="%" />
                    <Tooltip formatter={(v) => [`${v}%`, 'Tasa de respuesta']} contentStyle={{ background: '#1e293b', border: 'none', borderRadius: 8, color: '#f1f5f9' }} />
                    <Bar dataKey="rate" fill="#8b5cf6" radius={[4, 4, 0, 0]} />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </div>

            {/* Word cloud */}
            <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 p-6">
              <h3 className="text-slate-900 dark:text-white font-bold mb-4">Palabras más frecuentes en respuestas abiertas</h3>
              <div className="flex flex-wrap items-center justify-center gap-x-4 gap-y-3 min-h-28 p-4">
                {WORD_CLOUD_WORDS.map((w, i) => (
                  <span key={i} className={`${w.size} ${w.weight} ${w.color} leading-tight cursor-default select-none hover:opacity-80 transition-opacity`}>
                    {w.word}
                  </span>
                ))}
              </div>
            </div>

            {/* Insight box */}
            <div className="bg-blue-50 dark:bg-blue-500/10 border border-blue-200 dark:border-blue-500/30 rounded-2xl p-6">
              <div className="flex items-start gap-3">
                <span className="text-2xl mt-0.5">📊</span>
                <div>
                  <h4 className="text-blue-900 dark:text-blue-300 font-bold mb-2">Insights Clave</h4>
                  <ul className="space-y-1.5 text-blue-800 dark:text-blue-200 text-sm">
                    <li>La dimensión <strong>"Cumplimiento de plazos"</strong> tiene el score más bajo (3.2/5) — requiere atención inmediata.</li>
                    <li>Los proyectos de construcción tienen mejor NPS (<strong>58</strong>) que los de software (<strong>31</strong> promedio).</li>
                    <li>La tasa de respuesta del 63% está por encima del promedio de la industria (50%). Objetivo: 75%.</li>
                    <li>El proyecto <strong>PRY-2026-004</strong> (AR-ProjectManagement) es el más crítico con NPS de 18 y una encuesta vencida sin responder.</li>
                  </ul>
                </div>
              </div>
            </div>

            {/* Action items */}
            <div className="bg-white dark:bg-slate-900 rounded-2xl border border-slate-200 dark:border-slate-700 overflow-hidden">
              <div className="p-6 border-b border-slate-200 dark:border-slate-700">
                <h3 className="text-slate-900 dark:text-white font-bold">Plan de Acción por Dimensión</h3>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-slate-50 dark:bg-slate-800/50">
                    <tr>
                      {['Dimensión', 'Score Actual', 'Objetivo', 'Acción', 'Responsable'].map(h => (
                        <th key={h} className="text-xs font-semibold text-slate-500 dark:text-slate-400 uppercase px-4 py-3 text-left whitespace-nowrap">{h}</th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100 dark:divide-slate-800">
                    {ACTION_ITEMS.map((a, i) => (
                      <tr key={i} className="hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors">
                        <td className="px-4 py-3 text-sm font-medium text-slate-900 dark:text-white">{a.dimension}</td>
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-2">
                            <span className={`text-sm font-bold ${a.current < 3.5 ? 'text-red-500' : a.current < 4 ? 'text-amber-500' : 'text-green-500'}`}>{a.current}</span>
                            <div className="w-16 bg-slate-100 dark:bg-slate-800 rounded-full h-1.5">
                              <div className={`h-1.5 rounded-full ${scoreBarColor(a.current)}`} style={{ width: `${(a.current / 5) * 100}%` }} />
                            </div>
                          </div>
                        </td>
                        <td className="px-4 py-3 text-sm font-bold text-green-600 dark:text-green-400">{a.target}</td>
                        <td className="px-4 py-3 text-sm text-slate-600 dark:text-slate-300 max-w-xs">{a.action}</td>
                        <td className="px-4 py-3">
                          <span className="rounded-full px-2.5 py-0.5 text-xs font-medium bg-purple-100 text-purple-700 dark:bg-purple-500/20 dark:text-purple-300 whitespace-nowrap">
                            {a.owner}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Modals */}
      {showNewSurvey && <NewSurveyModal onClose={() => setShowNewSurvey(false)} />}
      {detailSurvey && <SurveyDetailModal survey={detailSurvey} onClose={() => setDetailSurvey(null)} />}
    </div>
  );
}
