// Modals — SOFIA Chat send, SOFIA Call launch, Schedule call, Submit to client,
// Interview kit, Bulk campaign. LIGHT theme.

const { useEffect: ueM, useState: usM } = React;

// ---------- SOFIA Chat — send WhatsApp ----------
function SofiaChatModal({ open, onClose, candidate, defaultTemplate }) {
  const toast = useToast();
  const [template, setTemplate] = usM(defaultTemplate?.id || 't1');
  const [body, setBody] = usM('');
  const [phase, setPhase] = usM('compose');

  ueM(() => {
    if (!open) return;
    const t = DATA.TEMPLATES.find((x) => x.id === template);
    if (!candidate || !t) return;
    const text = t.body
      .replace('{{nombre}}', candidate.name.split(' ')[0])
      .replace('{{rol}}', 'Asesor Bilingüe')
      .replace('{{cliente}}', 'Acme Retail')
      .replace('{{salario}}', 'USD $950')
      .replace('{{modalidad}}', 'Híbrido')
      .replace('{{fecha}}', 'mañana 10:00 am');
    setBody(text);
  }, [open, template, candidate]);

  ueM(() => { if (open) setPhase('compose'); }, [open]);

  const send = () => {
    setPhase('sending');
    setTimeout(() => {
      setPhase('sent');
      toast?.push({
        title: 'Mensaje enviado vía SOFIA Chat',
        body: `WhatsApp entregado a ${candidate?.name}.`,
        tone: 'success',
      });
      setTimeout(() => onClose?.(), 950);
    }, 1100);
  };

  if (!candidate) return null;

  return (
    <Modal open={open} onClose={onClose} size="lg">
      <ModalHeader
        icon={<Icon.WhatsApp size={18} />}
        title="Enviar mensaje vía SOFIA Chat"
        subtitle={`WhatsApp Business · destinatario: ${candidate.name}`}
        onClose={onClose}
      />
      <div className="p-6 grid grid-cols-12 gap-6">
        <div className="col-span-5 space-y-2">
          <div className="text-[10px] uppercase tracking-[0.18em] text-ink-500 mb-1 font-medium">Plantilla</div>
          {DATA.TEMPLATES.map((t) => (
            <button
              key={t.id}
              onClick={() => setTemplate(t.id)}
              className={`w-full text-left p-3 rounded-lg border text-sm transition-colors ${
                template === t.id
                  ? 'border-brand-300 bg-brand-50/60 ring-2 ring-brand-100'
                  : 'border-line bg-white hover:border-ink-200'
              }`}
            >
              <div className="flex items-center gap-2">
                <Icon.File size={13} className="text-brand-500" />
                <span className="font-medium text-ink-900">{t.name}</span>
              </div>
              <div className="text-xs text-ink-500 mt-1 line-clamp-2">{t.body}</div>
            </button>
          ))}
        </div>
        <div className="col-span-7">
          <div className="text-[10px] uppercase tracking-[0.18em] text-ink-500 mb-1 font-medium">Vista previa</div>
          <div className="rounded-xl border border-line wa-pattern p-4 min-h-[280px] relative">
            <div className="flex items-center gap-2 mb-3 pb-3 border-b border-line">
              <Avatar name={candidate.name} color={candidate.avatarColor} size={32} />
              <div>
                <div className="text-sm text-ink-900 font-medium">{candidate.name}</div>
                <div className="text-[11px] text-emerald-700 flex items-center gap-1">
                  <Icon.WhatsApp size={10} /> WhatsApp · en línea
                </div>
              </div>
            </div>
            <textarea
              value={body}
              onChange={(e) => setBody(e.target.value)}
              rows={6}
              className="w-full bg-white/80 border border-line rounded-lg p-2 outline-none text-sm text-ink-900 resize-none focus:border-brand-400"
            />
            <div className="flex justify-end mt-3 mb-2">
              <div className="relative bg-emerald-600 text-white rounded-2xl rounded-tr-sm px-3 py-2 max-w-[80%] text-sm shadow-sm">
                {body}
                <div className="text-[10px] text-emerald-100 mt-1 flex justify-end items-center gap-1">
                  ahora <Icon.CheckCheck size={12} />
                </div>
              </div>
            </div>
          </div>

          <div className="flex items-center justify-between mt-4">
            <div className="flex items-center gap-2 text-xs text-ink-500">
              <Icon.SofiaMark size={14} />
              <span>Personalizado por SOFIA · variables auto-rellenadas</span>
            </div>
            <div className="flex gap-2">
              <Button variant="ghost" size="md" onClick={onClose}>Cancelar</Button>
              <Button
                variant="whatsapp"
                size="md"
                icon={phase === 'sending' ? <Icon.Loader size={14} className="animate-spin" /> : <Icon.Send size={14} />}
                onClick={send}
                disabled={phase !== 'compose'}
              >
                {phase === 'compose' ? 'Enviar vía SOFIA Chat' : phase === 'sending' ? 'Enviando…' : 'Enviado'}
              </Button>
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
}

// ---------- SOFIA Call — launch ----------
function SofiaCallModal({ open, onClose, candidate }) {
  const toast = useToast();
  const [phase, setPhase] = usM('idle');
  const [seconds, setSeconds] = usM(0);
  const [waveform, setWaveform] = usM(Array.from({ length: 28 }, () => Math.random()));

  ueM(() => { if (open) { setPhase('idle'); setSeconds(0); } }, [open]);

  ueM(() => {
    if (phase !== 'live') return;
    const i = setInterval(() => {
      setSeconds((s) => s + 1);
      setWaveform(() => Array.from({ length: 28 }, () => Math.random()));
    }, 700);
    return () => clearInterval(i);
  }, [phase]);

  const dial = () => {
    setPhase('dialing');
    setTimeout(() => setPhase('live'), 1400);
  };
  const hangup = () => {
    setPhase('done');
    toast?.push({
      title: 'Screening guardado',
      body: `SOFIA Call generó transcripción y recomendación para ${candidate?.name}.`,
      tone: 'brand',
    });
    setTimeout(() => onClose?.(), 1100);
  };

  if (!candidate) return null;
  const mm = String(Math.floor(seconds / 60)).padStart(2, '0');
  const ss = String(seconds % 60).padStart(2, '0');

  return (
    <Modal open={open} onClose={onClose} size="md">
      <ModalHeader
        icon={<Icon.PhoneCall size={18} />}
        title="SOFIA Call · screening AI"
        subtitle="Llamada saliente automatizada · español/inglés"
        onClose={onClose}
      />
      <div className="p-6">
        <div className="flex items-center gap-4 p-4 rounded-xl bg-ink-50 border border-line">
          <Avatar name={candidate.name} color={candidate.avatarColor} size={48} />
          <div className="flex-1">
            <div className="text-base font-semibold text-ink-900">{candidate.name}</div>
            <div className="text-xs text-ink-500 mt-0.5 flex items-center gap-3">
              <span className="flex items-center gap-1"><Icon.Phone size={11} /> +503 7•••-2{candidate.id.slice(-2)}1</span>
              <span className="flex items-center gap-1"><Icon.MapPin size={11} /> {candidate.city}</span>
            </div>
          </div>
          <Pill tone="brand" icon={<Icon.SofiaMark size={11} />}>SOFIA MCP</Pill>
        </div>

        <div className="mt-6 rounded-xl border border-line bg-white p-5">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2 text-xs text-ink-700 font-medium">
              <span className={`h-2 w-2 rounded-full ${phase === 'live' ? 'bg-emerald-500 animate-pulse-soft' : phase === 'dialing' ? 'bg-ai-500 animate-pulse-soft' : 'bg-ink-300'}`} />
              {phase === 'idle' && 'Listo para marcar'}
              {phase === 'dialing' && 'Marcando…'}
              {phase === 'live' && 'En llamada con SOFIA'}
              {phase === 'done' && 'Llamada finalizada'}
            </div>
            <div className="tabular text-sm text-ink-900 font-mono">{mm}:{ss}</div>
          </div>

          <div className="h-20 flex items-end gap-1 justify-center">
            {waveform.map((v, i) => (
              <div
                key={i}
                className="w-1.5 rounded-full transition-all duration-500"
                style={{
                  height: `${(phase === 'live' ? v : 0.15) * 100}%`,
                  background: `linear-gradient(180deg, #4f46e5, #a855f7)`,
                  opacity: phase === 'live' ? 0.55 + v * 0.45 : 0.25,
                }}
              />
            ))}
          </div>

          <div className="mt-4 space-y-2 max-h-[140px] overflow-y-auto pr-1">
            <div className="text-[10px] uppercase tracking-[0.18em] text-ink-500 font-medium">Script · 5 preguntas</div>
            {DATA.SCREENING_QUESTIONS.map((q, i) => (
              <div key={i} className="flex items-start gap-2 text-xs">
                <span className="tabular text-ink-400 mt-0.5">{i + 1}.</span>
                <span className="text-ink-700">{q}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="mt-5 flex items-center justify-between">
          <div className="flex items-center gap-2 text-xs text-ink-500">
            <Icon.Shield size={12} /> Llamada grabada y con consentimiento
          </div>
          <div className="flex gap-2">
            {phase === 'idle' && (
              <>
                <Button variant="ghost" onClick={onClose}>Cancelar</Button>
                <Button variant="primary" icon={<Icon.PhoneCall size={14} />} onClick={dial}>Iniciar llamada</Button>
              </>
            )}
            {phase === 'dialing' && (
              <Button variant="default" icon={<Icon.Loader size={14} className="animate-spin" />} disabled>Conectando…</Button>
            )}
            {phase === 'live' && (
              <Button variant="danger" icon={<Icon.Phone size={14} className="rotate-[135deg]" />} onClick={hangup}>Finalizar</Button>
            )}
            {phase === 'done' && (
              <Button variant="success" icon={<Icon.CheckCircle size={14} />} onClick={onClose}>Listo</Button>
            )}
          </div>
        </div>
      </div>
    </Modal>
  );
}

// ---------- Schedule call ----------
function ScheduleCallModal({ open, onClose, candidate }) {
  const toast = useToast();
  const [day, setDay] = usM('Mañana');
  const [time, setTime] = usM('10:00');
  const days = ['Hoy', 'Mañana', 'Jue 15', 'Vie 16', 'Lun 19'];
  const times = ['09:00', '10:00', '11:00', '14:00', '15:30', '17:00'];

  const confirm = () => {
    toast?.push({
      title: 'Screening agendado',
      body: `SOFIA Call llamará a ${candidate?.name} ${day} a las ${time}.`,
      tone: 'brand',
    });
    onClose?.();
  };

  if (!candidate) return null;
  return (
    <Modal open={open} onClose={onClose} size="md">
      <ModalHeader
        icon={<Icon.CalendarClock size={18} />}
        title="Agendar screening con SOFIA Call"
        subtitle={candidate.name}
        onClose={onClose}
      />
      <div className="p-6 space-y-4">
        <div>
          <div className="text-xs text-ink-500 mb-2 font-medium">Día</div>
          <div className="flex flex-wrap gap-2">
            {days.map((d) => (
              <button key={d} onClick={() => setDay(d)}
                className={`h-9 px-3 rounded-lg text-sm border transition-colors ${
                  day === d ? 'border-brand-400 bg-brand-50 text-brand-700' : 'bg-white border-line text-ink-700 hover:border-ink-200'
                }`}>
                {d}
              </button>
            ))}
          </div>
        </div>
        <div>
          <div className="text-xs text-ink-500 mb-2 font-medium">Hora</div>
          <div className="grid grid-cols-6 gap-2">
            {times.map((t) => (
              <button key={t} onClick={() => setTime(t)}
                className={`h-9 rounded-lg text-sm tabular border transition-colors ${
                  time === t ? 'border-brand-400 bg-brand-50 text-brand-700' : 'bg-white border-line text-ink-700 hover:border-ink-200'
                }`}>
                {t}
              </button>
            ))}
          </div>
        </div>
        <div className="rounded-lg border border-ai-200 ai-soft p-3 text-sm text-ink-700 flex gap-2">
          <Icon.Sparkles size={14} className="text-ai-600 mt-0.5 shrink-0" />
          <span>SOFIA reutilizará el script actual de 5 preguntas y subirá la transcripción al perfil al finalizar.</span>
        </div>
        <div className="flex justify-end gap-2 pt-2">
          <Button variant="ghost" onClick={onClose}>Cancelar</Button>
          <Button variant="primary" icon={<Icon.CheckCircle size={14} />} onClick={confirm}>Confirmar</Button>
        </div>
      </div>
    </Modal>
  );
}

// ---------- Submit to client ----------
function SubmitToClientModal({ open, onClose, candidate, client = 'Acme Retail Group' }) {
  const toast = useToast();
  const [note, setNote] = usM('Recomiendo fuertemente. Inglés C1 verificado por SOFIA Call. Disponibilidad inmediata.');
  const submit = () => {
    toast?.push({ title: `${candidate?.name} submitido`, body: `Enviado a ${client} para revisión final.`, tone: 'success' });
    onClose?.();
  };
  if (!candidate) return null;
  return (
    <Modal open={open} onClose={onClose} size="md">
      <ModalHeader
        icon={<Icon.Send size={18} />}
        title={`Submitir candidato a ${client}`}
        subtitle="Se enviará paquete con CV, transcripción de screening y match analysis"
        onClose={onClose}
      />
      <div className="p-6 space-y-4">
        <div className="flex items-center gap-3 p-3 rounded-xl border border-line bg-ink-50">
          <Avatar name={candidate.name} color={candidate.avatarColor} size={40} />
          <div className="flex-1">
            <div className="text-sm font-semibold text-ink-900">{candidate.name}</div>
            <div className="text-xs text-ink-500">{candidate.role} · {candidate.yearsExperience} años</div>
          </div>
          <Pill tone="brand">Match {candidate.matchScore}%</Pill>
        </div>
        <div>
          <div className="text-xs text-ink-500 mb-1 font-medium">Nota para el cliente</div>
          <textarea
            value={note} onChange={(e) => setNote(e.target.value)}
            rows={4}
            className="w-full bg-white border border-line focus:border-brand-400 outline-none rounded-lg p-3 text-sm text-ink-900 resize-none"
          />
        </div>
        <div className="grid grid-cols-3 gap-2">
          {[
            { icon: <Icon.File size={12} />, label: 'CV completo' },
            { icon: <Icon.Headphones size={12} />, label: 'Transcripción SOFIA Call' },
            { icon: <Icon.Brain size={12} />, label: 'Match analysis' },
          ].map((x) => (
            <div key={x.label} className="flex items-center gap-2 p-2.5 rounded-lg bg-ink-50 border border-line text-xs text-ink-700">
              <span className="h-5 w-5 rounded bg-brand-50 text-brand-600 flex items-center justify-center">{x.icon}</span>
              {x.label}
            </div>
          ))}
        </div>
        <div className="flex justify-end gap-2 pt-2">
          <Button variant="ghost" onClick={onClose}>Cancelar</Button>
          <Button variant="primary" icon={<Icon.Send size={14} />} onClick={submit}>Submitir a {client}</Button>
        </div>
      </div>
    </Modal>
  );
}

// ---------- Interview kit ----------
function InterviewKitModal({ open, onClose, candidate }) {
  const toast = useToast();
  if (!candidate) return null;
  const kit = [
    { section: 'Apertura', items: ['Rompe-hielo personalizado: hobbies, idiomas, mudanza reciente', 'Resumen de SOFIA (60 seg) sobre fortalezas y gaps'] },
    { section: 'Profundización técnica', items: ['Caso role-play: cliente moroso (15 min)', 'Validación de inglés C1: 3 preguntas espontáneas', 'Manejo de Salesforce: walkthrough en pantalla compartida'] },
    { section: 'Cultural & motivación', items: ['¿Por qué Acme Retail vs. otra opción?', '¿Cómo describirías un equipo donde brillas?'] },
    { section: 'Cierre', items: ['Compensación y modalidad', 'Próximos pasos: oferta en 48h si avanza'] },
  ];
  return (
    <Modal open={open} onClose={onClose} size="lg">
      <ModalHeader
        icon={<Icon.Notebook size={18} />}
        title="Kit de entrevista generado por SOFIA"
        subtitle={`Personalizado para ${candidate.name} · Acme Retail · Bilingüe`}
        onClose={onClose}
      />
      <div className="p-6 grid grid-cols-12 gap-5 overflow-y-auto">
        <div className="col-span-8 space-y-5">
          {kit.map((s) => (
            <div key={s.section}>
              <div className="text-xs uppercase tracking-[0.16em] text-brand-600 mb-2 font-semibold">{s.section}</div>
              <ul className="space-y-2">
                {s.items.map((it, i) => (
                  <li key={i} className="flex items-start gap-2 text-sm text-ink-800">
                    <span className="h-1.5 w-1.5 rounded-full bg-brand-400 mt-2 shrink-0" />
                    {it}
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </div>
        <div className="col-span-4 space-y-3">
          <div className="rounded-xl border border-ai-200 ai-soft p-4">
            <div className="flex items-center gap-2 mb-2">
              <Icon.Sparkles size={14} className="text-ai-600" />
              <span className="text-xs uppercase tracking-[0.16em] text-ai-700 font-semibold">SOFIA recomienda</span>
            </div>
            <p className="text-sm text-ink-800 leading-relaxed">
              Empieza por el caso role-play; el screening detectó muy buen manejo de objeciones pero quieres confirmar bajo presión real.
            </p>
          </div>
          <Card className="p-4 space-y-2">
            <div className="text-xs uppercase tracking-[0.16em] text-ink-500 font-medium">Duración estimada</div>
            <div className="text-2xl font-semibold tabular text-ink-900">45 min</div>
            <div className="text-xs text-ink-500">+ 10 min de feedback con el comité</div>
          </Card>
          <Button variant="primary" className="w-full" icon={<Icon.Download size={14} />}
                  onClick={() => { toast?.push({ title: 'Kit descargado', tone: 'success' }); }}>
            Descargar PDF
          </Button>
        </div>
      </div>
    </Modal>
  );
}

// ---------- Bulk WhatsApp campaign ----------
function BulkCampaignModal({ open, onClose }) {
  const toast = useToast();
  const [segment, setSegment] = usM('Inglés B2+ · San Salvador · disponible inmediato');
  const [template, setTemplate] = usM('t1');
  const send = () => {
    toast?.push({ title: 'Campaña enviada', body: '47 mensajes vía SOFIA Chat encolados.', tone: 'brand' });
    onClose?.();
  };
  return (
    <Modal open={open} onClose={onClose} size="lg">
      <ModalHeader
        icon={<Icon.Megaphone size={18} />}
        title="Campaña masiva WhatsApp · SOFIA Chat"
        subtitle="Envía un mensaje personalizado a un segmento del Candidate Pool"
        onClose={onClose}
      />
      <div className="p-6 grid grid-cols-12 gap-5">
        <div className="col-span-7 space-y-4">
          <div>
            <div className="text-xs text-ink-500 mb-1 font-medium">Segmento</div>
            <Input value={segment} onChange={setSegment} icon={<Icon.Filter size={14} />} />
          </div>
          <div>
            <div className="text-xs text-ink-500 mb-2 font-medium">Plantilla base</div>
            <div className="grid grid-cols-2 gap-2">
              {DATA.TEMPLATES.slice(0, 4).map((t) => (
                <button key={t.id} onClick={() => setTemplate(t.id)}
                  className={`text-left p-3 rounded-lg border text-sm ${
                    template === t.id ? 'border-brand-300 bg-brand-50/60 ring-2 ring-brand-100' : 'border-line bg-white hover:border-ink-200'
                  }`}>
                  <div className="font-medium text-ink-900 text-sm">{t.name}</div>
                  <div className="text-[11px] text-ink-500 mt-1 line-clamp-2">{t.body}</div>
                </button>
              ))}
            </div>
          </div>
          <div className="flex items-center justify-between rounded-lg border border-line bg-ink-50 px-3 py-2.5">
            <div className="flex items-center gap-2 text-sm text-ink-800">
              <Icon.Sparkles size={14} className="text-ai-600" />
              Personalizar por candidato con SOFIA
            </div>
            <Check checked={true} onChange={() => {}} />
          </div>
        </div>
        <div className="col-span-5">
          <Card className="p-4 space-y-3">
            <div className="text-xs uppercase tracking-[0.16em] text-ink-500 font-medium">Resumen</div>
            <div className="flex justify-between text-sm">
              <span className="text-ink-500">Destinatarios</span>
              <span className="tabular font-semibold text-ink-900">47</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-ink-500">Costo SOFIA Chat</span>
              <span className="tabular text-ink-800">USD $4.10</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-ink-500">Open rate estimado</span>
              <span className="tabular text-emerald-700 font-semibold">92%</span>
            </div>
            <Divider />
            <div className="flex justify-between text-sm">
              <span className="text-ink-500">Mensajes/seg</span>
              <span className="tabular text-ink-900">12</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-ink-500">Tiempo total</span>
              <span className="tabular text-ink-900">~4 seg</span>
            </div>
          </Card>
          <Button variant="primary" className="w-full mt-3" icon={<Icon.Send size={14} />} onClick={send}>
            Enviar campaña
          </Button>
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, {
  SofiaChatModal, SofiaCallModal, ScheduleCallModal,
  SubmitToClientModal, InterviewKitModal, BulkCampaignModal,
});
