// SOFIA AI Assistant — slide-over chat panel. LIGHT theme.

const { useState: usA, useEffect: ueA, useRef: urA } = React;

function AssistantPanel({ open, onClose, onNavigate, onOpenCandidate }) {
  const [messages, setMessages] = usA([
    {
      role: 'assistant',
      text: '¡Hola Marisol! Soy SOFIA, tu copiloto de Recruitment. Puedo buscar candidatos, agendar screenings con SOFIA Call, redactar mensajes para SOFIA Chat o resumir vacantes. Prueba con uno de los ejemplos.',
      time: 'ahora',
    },
  ]);
  const [running, setRunning] = usA(false);
  const [input, setInput] = usA('');
  const endRef = urA(null);

  ueA(() => {
    if (endRef.current) endRef.current.scrollIntoView({ behavior: 'smooth', block: 'end' });
  }, [messages, running]);

  const runScript = (key) => {
    if (running) return;
    const script = DATA.ASSISTANT_SCRIPTS[key];
    if (!script) return;
    setMessages((m) => [...m, { role: 'user', text: script.user, time: 'ahora' }]);
    setRunning(true);

    let idx = 0;
    const toolMsgId = 'tool-' + Date.now();
    setMessages((m) => [...m, { id: toolMsgId, role: 'tool', steps: [], time: 'ahora' }]);

    const stepNext = () => {
      if (idx >= script.steps.length) {
        setTimeout(() => {
          setMessages((m) => [
            ...m,
            { role: 'assistant', text: script.summary, candidates: script.candidates, time: 'ahora' },
          ]);
          setRunning(false);
        }, 400);
        return;
      }
      setMessages((m) =>
        m.map((msg) =>
          msg.id === toolMsgId
            ? { ...msg, steps: [...msg.steps, { ...script.steps[idx], status: 'running' }] }
            : msg
        )
      );
      setTimeout(() => {
        setMessages((m) =>
          m.map((msg) =>
            msg.id === toolMsgId
              ? { ...msg, steps: msg.steps.map((s, i) => (i === idx ? { ...s, status: 'done' } : s)) }
              : msg
          )
        );
        idx++;
        stepNext();
      }, 750);
    };
    stepNext();
  };

  const submit = () => {
    if (!input.trim()) return;
    setMessages((m) => [...m, { role: 'user', text: input, time: 'ahora' }]);
    const lower = input.toLowerCase();
    setInput('');
    setRunning(true);
    setTimeout(() => {
      if (lower.includes('acme') || lower.includes('cobranza')) { runScript('bilingual'); return; }
      if (lower.includes('helix') || lower.includes('b2b'))     { runScript('summary');   return; }
      if (lower.includes('whatsapp') || lower.includes('redacta') || lower.includes('mensaje')) { runScript('draft'); return; }
      setMessages((m) => [...m, { role: 'assistant', text: 'Buen punto. Para esta demo, los flujos completos están disponibles en los 3 ejemplos pre-cargados — pruébalos para ver a SOFIA orquestar SOFIA Chat y SOFIA Call como herramientas MCP.', time: 'ahora' }]);
      setRunning(false);
    }, 500);
  };

  if (!open) return null;

  const examples = [
    { key: 'bilingual', icon: <Icon.Users size={13} />, text: 'Encuéntrame 5 bilingües en San Salvador disponibles' },
    { key: 'summary',   icon: <Icon.File size={13} />, text: 'Resume los 3 mejores candidatos para Helix Energy' },
    { key: 'draft',     icon: <Icon.WhatsApp size={13} />, text: 'Redacta WhatsApp invitando a Ana García el viernes' },
  ];

  return (
    <div className="fixed inset-0 z-[95]">
      <div className="absolute inset-0 bg-ink-900/30 backdrop-blur-sm animate-fade-in" onClick={onClose} />
      <aside className="absolute right-0 top-0 bottom-0 w-[480px] bg-white border-l border-line flex flex-col animate-slide-in-right shadow-pop">
        {/* Header */}
        <div className="px-5 py-4 border-b border-line flex items-center gap-3">
          <Icon.SofiaMark size={36} />
          <div className="flex-1">
            <div className="flex items-center gap-2">
              <span className="text-base font-semibold text-ink-900">SOFIA · Asistente MCP</span>
              <Pill tone="emerald" size="sm" icon={<span className="h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse-soft" />}>Online</Pill>
            </div>
            <div className="text-[11px] text-ink-500 mt-0.5">Conectado a: Candidate Pool · SOFIA Chat · SOFIA Call · Requisitions</div>
          </div>
          <IconButton icon={<Icon.X size={16} />} variant="ghost" onClick={onClose} />
        </div>

        {/* Messages */}
        <div className="flex-1 overflow-y-auto px-5 py-5 space-y-4 bg-sub">
          {messages.map((m, i) => (
            <MessageBubble key={i} m={m} onOpenCandidate={onOpenCandidate} />
          ))}
          {running && (
            <div className="flex items-center gap-2 text-xs text-ink-500 pl-1">
              <span className="flex gap-1">
                <span className="h-1.5 w-1.5 rounded-full bg-brand-400 animate-pulse-soft" />
                <span className="h-1.5 w-1.5 rounded-full bg-brand-400 animate-pulse-soft" style={{ animationDelay: '0.2s' }} />
                <span className="h-1.5 w-1.5 rounded-full bg-brand-400 animate-pulse-soft" style={{ animationDelay: '0.4s' }} />
              </span>
              SOFIA está pensando…
            </div>
          )}
          <div ref={endRef} />
        </div>

        {/* Examples */}
        <div className="px-5 pt-2 pb-3 border-t border-line bg-white">
          <div className="text-[10px] uppercase tracking-[0.18em] text-ink-500 mb-2 font-medium">Ejemplos rápidos</div>
          <div className="flex flex-col gap-2">
            {examples.map((e) => (
              <button key={e.key} onClick={() => runScript(e.key)} disabled={running}
                className="text-left text-xs px-3 py-2 rounded-lg bg-white border border-line hover:border-brand-300 hover:bg-brand-50/30 flex items-center gap-2 text-ink-700 hover-lift">
                <span className="text-brand-500">{e.icon}</span>
                {e.text}
                <Icon.ArrowUpRight size={12} className="ml-auto text-ink-400" />
              </button>
            ))}
          </div>
        </div>

        {/* Input */}
        <div className="p-4 border-t border-line bg-white">
          <div className="flex items-end gap-2 bg-white border border-line rounded-xl focus-within:border-brand-400 focus-within:ring-4 focus-within:ring-brand-100 px-3 py-2">
            <Icon.SofiaMark size={18} className="mt-1" />
            <textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); submit(); } }}
              placeholder="Pregunta a SOFIA… (e.g. 'bilingües disponibles para Acme Retail')"
              rows={1}
              className="flex-1 bg-transparent outline-none text-sm text-ink-900 placeholder:text-ink-400 resize-none py-1.5"
            />
            <IconButton
              icon={running ? <Icon.Loader size={14} className="animate-spin" /> : <Icon.ArrowUp size={14} />}
              onClick={submit}
              variant="primary"
              size="sm"
            />
          </div>
          <div className="flex items-center justify-between mt-2 text-[10px] text-ink-500">
            <span className="flex items-center gap-1.5"><Icon.Shield size={10} /> SOFIA MCP · datos cifrados</span>
            <span>Enter para enviar · Shift+Enter para salto</span>
          </div>
        </div>
      </aside>
    </div>
  );
}

function MessageBubble({ m, onOpenCandidate }) {
  if (m.role === 'user') {
    return (
      <div className="flex justify-end">
        <div className="max-w-[80%] bg-brand-500 text-white rounded-2xl rounded-tr-sm px-3.5 py-2.5 shadow-sm">
          <div className="text-sm">{m.text}</div>
          <div className="text-[10px] text-brand-100 mt-1 text-right">{m.time}</div>
        </div>
      </div>
    );
  }
  if (m.role === 'tool') {
    return (
      <div className="bg-white border border-line rounded-xl p-3 space-y-1.5 shadow-card">
        <div className="flex items-center gap-2 text-[10px] uppercase tracking-[0.18em] text-ink-500 font-semibold">
          <Icon.Workflow size={11} />
          MCP Tools
        </div>
        {m.steps.map((s, i) => (
          <div key={i} className="flex items-center gap-2.5 text-xs">
            <span className="h-4 w-4 rounded flex items-center justify-center shrink-0">
              {s.status === 'done'
                ? <Icon.CheckCircle size={12} className="text-emerald-600" />
                : <Icon.Loader size={12} className="text-brand-500 animate-spin" />}
            </span>
            <span className="font-mono text-[11px] text-brand-600 shrink-0">{s.tool}</span>
            <span className="text-ink-600 flex-1 truncate">{s.label}</span>
          </div>
        ))}
      </div>
    );
  }
  return (
    <div className="flex gap-2">
      <div className="shrink-0"><Icon.SofiaMark size={28} /></div>
      <div className="flex-1 min-w-0">
        <div className="bg-white border border-line rounded-2xl rounded-tl-sm px-3.5 py-2.5 shadow-card">
          <div className="text-sm text-ink-900 whitespace-pre-wrap leading-relaxed">{m.text}</div>
        </div>
        {m.candidates && m.candidates.length > 0 && (
          <div className="mt-2 space-y-2">
            {m.candidates.map((cid) => {
              const c = DATA.CANDIDATES.find((x) => x.id === cid);
              if (!c) return null;
              return (
                <button key={cid} onClick={() => onOpenCandidate?.(c)}
                  className="w-full flex items-center gap-3 p-2.5 rounded-lg bg-white border border-line hover:border-brand-300 hover-lift">
                  <Avatar name={c.name} color={c.avatarColor} size={32} />
                  <div className="flex-1 text-left">
                    <div className="text-sm text-ink-900 font-medium">{c.name}</div>
                    <div className="text-[11px] text-ink-500">{c.role} · {c.city}</div>
                  </div>
                  <Pill tone="brand" size="sm">{c.matchScore}%</Pill>
                </button>
              );
            })}
          </div>
        )}
        <div className="text-[10px] text-ink-400 mt-1 pl-1">SOFIA · {m.time}</div>
      </div>
    </div>
  );
}

Object.assign(window, { AssistantPanel });
