// chat-view.jsx — Full-screen chat view for an active agent.
const { useState: useStateCV, useEffect: useEffectCV, useRef: useRefCV } = React;

function ChatMessage({ role, text, agent, t, p, loading }) {
  const Icon = agent?.icon;
  const isUser = role === "user";
  return (
    <div style={{
      display: "flex", gap: 14,
      flexDirection: "row",
      padding: "20px 0",
      borderBottom: `1px solid ${p.borderSoft}`,
    }}>
      <div style={{
        width: 32, height: 32, borderRadius: 8,
        background: isUser
          ? `linear-gradient(135deg, ${t.accent}, ${t.accent}aa)`
          : `linear-gradient(160deg, ${t.accent}24, ${t.accent}08)`,
        border: isUser ? "none" : `1px solid ${t.accent}30`,
        display: "flex", alignItems: "center", justifyContent: "center",
        color: isUser ? "#0A0A0A" : t.accent,
        fontFamily: "'Geist', sans-serif", fontSize: 11, fontWeight: 600,
        letterSpacing: "0.04em", flexShrink: 0,
      }}>
        {isUser ? "TÚ" : (Icon ? <Icon size={16} /> : "AI")}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          display: "flex", alignItems: "baseline", gap: 10, marginBottom: 8,
        }}>
          <span style={{
            fontFamily: "'Geist', sans-serif", fontSize: 13.5, fontWeight: 500,
            color: isUser ? p.text : t.accent,
          }}>{isUser ? "Tú" : agent.name}</span>
          <span style={{
            fontFamily: "'Geist', sans-serif", fontSize: 11,
            color: p.textDim,
          }}>hace un momento</span>
        </div>
        <div style={{
          fontFamily: "'Geist', sans-serif", fontSize: 14.5,
          lineHeight: 1.65, color: p.text,
          whiteSpace: "pre-wrap", wordBreak: "break-word",
        }}>
          {text}
          {loading && (
            <span style={{
              display: "inline-block", width: 8, height: 16,
              background: t.accent, marginLeft: 3, verticalAlign: "text-bottom",
              animation: "mdpBlink 1s steps(2) infinite",
            }}/>
          )}
        </div>
      </div>
    </div>
  );
}

function ChatView({ agent, t, p, consultas, onCredits, onNewSession, onBack }) {
  const isMobile = window.useIsMobile();
  const [messages, setMessages] = useStateCV([]);
  const [input, setInput] = useStateCV("");
  const [loading, setLoading] = useStateCV(false);
  const [convId, setConvId] = useStateCV(null);
  const [copiedIdx, setCopiedIdx] = useStateCV(-1);
  const scrollRef = useRefCV(null);
  const inputRef = useRefCV(null);
  const Icon = agent.icon;

  const outOfCredits = (consultas ?? 0) <= 0;
  const isAdn = agent.id === "adn-experto";
  const [adnApproved, setAdnApproved] = useStateCV(false);
  const [confirming, setConfirming] = useStateCV(false);

  // El último mensaje del agente (el ADN ya compilado) es lo que se guarda.
  const lastAgentText = () => {
    for (let i = messages.length - 1; i >= 0; i--) {
      if (messages[i].role === "agent" && messages[i].text) return messages[i].text;
    }
    return "";
  };
  const approveAdn = async () => {
    try {
      await MDP_API.adnApprove(lastAgentText());
      setAdnApproved(true);
    } catch (_) {}
    setConfirming(false);
  };
  const reopenAdn = async () => {
    try { await MDP_API.adnReopen(); } catch (_) {}
    setAdnApproved(false); setConfirming(false);
  };

  // Reset al cambiar de agente: saludo + carga de memoria (última conversación)
  useEffectCV(() => {
    let cancelled = false;
    const greeting = {
      role: "agent",
      text: `Hola, soy ${agent.name}.\n\n${agent.desc}\n\n¿Por dónde quieres empezar hoy?`,
    };
    setMessages([greeting]);
    setInput("");
    setLoading(false);
    setConvId(null);
    setAdnApproved(false);

    (async () => {
      try {
        const h = await MDP_API.chatHistory(agent.id);
        if (!cancelled && h && h.messages && h.messages.length) {
          setMessages([greeting, ...h.messages]);
          setConvId(h.conversationId);
        }
      } catch (_) {}
      if (agent.id === "adn-experto") {
        try {
          const adn = await MDP_API.adnGet();
          if (!cancelled && adn && adn.aprobado) setAdnApproved(true);
        } catch (_) {}
      }
    })();

    setTimeout(() => inputRef.current?.focus(), 50);
    return () => { cancelled = true; };
  }, [agent.id]);

  // Scroll to bottom on new messages
  useEffectCV(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages.length, loading]);

  const send = async (textOverride) => {
    const text = (textOverride ?? input).trim();
    if (!text || loading) return;
    setInput("");

    const history = [...messages, { role: "user", text }];
    setMessages(history);
    setLoading(true);
    setMessages(m => [...m, { role: "agent", text: "" }]);  // burbuja del agente, vacía

    try {
      const data = await MDP_API.sendChat(agent.id, history, convId);
      setConvId(data.conversationId);
      setMessages(m => {
        const next = [...m];
        next[next.length - 1] = { role: "agent", text: data.reply };
        return next;
      });
      if (onCredits) onCredits(data.consultas);
    } catch (err) {
      const msg = (err && err.data && err.data.error) || "Hubo un problema. Intenta de nuevo en un momento.";
      setMessages(m => {
        const next = [...m];
        next[next.length - 1] = { role: "agent", text: msg };
        return next;
      });
    } finally {
      setLoading(false);
    }
  };

  const handleNewSession = () => {
    onNewSession();
    setMessages([{
      role: "agent",
      text: `Hola, soy ${agent.name}.\n\n${agent.desc}\n\n¿Por dónde quieres empezar hoy?`,
    }]);
    setInput("");
    setLoading(false);
    setConvId(null);
  };

  const copyMessage = (idx, text) => {
    navigator.clipboard?.writeText(text);
    setCopiedIdx(idx);
    setTimeout(() => setCopiedIdx(-1), 1500);
  };

  const suggestions = SUGGESTIONS[agent.id] || [];
  const showSuggestions = messages.length <= 1;

  return (
    <div style={{
      display: "flex", flexDirection: "column",
      height: "100%", minHeight: 0,
    }}>
      {/* Agent header */}
      <div style={{
        padding: isMobile ? "14px 16px" : "22px 36px 22px",
        borderBottom: `1px solid ${p.border}`,
        display: "flex", alignItems: "flex-start", gap: isMobile ? 12 : 16,
        background: p.bg,
      }}>
        <div style={{
          width: 46, height: 46, borderRadius: 999,
          background: t.accent + "16",
          border: `1.5px solid ${t.accent}66`,
          display: "flex", alignItems: "center", justifyContent: "center",
          color: t.accent, flexShrink: 0,
        }}>
          <Icon size={22} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            display: "flex", alignItems: "center", gap: 10, marginBottom: 6,
          }}>
            <span style={{
              fontFamily: "'Geist', sans-serif", fontSize: 10.5,
              color: p.textMuted, letterSpacing: "0.22em", textTransform: "uppercase",
              fontWeight: 500,
            }}>Nivel {String(agent.level).padStart(2,"0")} · {agent.levelName}</span>
            <span style={{
              display: "inline-flex", alignItems: "center", gap: 6,
              padding: "2px 9px", borderRadius: 999,
              background: "rgba(46,125,107,0.12)",
              border: "1px solid rgba(46,125,107,0.3)",
              fontFamily: "'Geist', sans-serif", fontSize: 10.5,
              color: "#4FB59F", letterSpacing: "0.04em",
            }}>
              <span style={{ width: 5, height: 5, borderRadius: 999, background: "#4FB59F" }}/>
              Activo
            </span>
          </div>
          <div style={{
            fontFamily: "'Montserrat', sans-serif", fontWeight: 700,
            fontSize: isMobile ? 20 : 26, color: p.text, lineHeight: 1.15,
            letterSpacing: "-0.01em",
          }}>{agent.name}</div>
          <div style={{
            fontFamily: "'Geist', sans-serif", fontSize: 13.5,
            color: p.textMuted, marginTop: 4,
          }}>{agent.desc}</div>
        </div>
        <button onClick={handleNewSession} style={{
          padding: isMobile ? "9px 11px" : "9px 16px", background: p.bg2,
          border: `1px solid ${p.border}`, borderRadius: 8,
          color: p.text, fontFamily: "'Geist', sans-serif", fontSize: 13,
          cursor: "default", display: "flex", alignItems: "center", gap: 7,
          flexShrink: 0,
        }}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none"
               stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
            <path d="M3 12a9 9 0 1 0 3-6.7"/>
            <path d="M3 4v5h5"/>
          </svg>
          {!isMobile && "Nueva sesión"}
        </button>
      </div>

      {/* Messages scroll area */}
      <div ref={scrollRef} style={{
        flex: 1, overflowY: "auto",
        padding: isMobile ? "4px 16px 16px" : "8px 36px 24px",
      }}>
        <div style={{ maxWidth: 820, margin: "0 auto" }}>
          {messages.map((m, i) => (
            <div key={i} style={{ position: "relative" }}>
              <ChatMessage
                role={m.role} text={m.text} agent={agent}
                t={t} p={p}
                loading={loading && i === messages.length - 1 && m.role === "agent"}
              />
              {m.role === "agent" && m.text && !(loading && i === messages.length - 1) && (
                <div style={{
                  display: "flex", gap: 6, marginTop: -8, marginBottom: 12,
                  marginLeft: 46,
                }}>
                  <button onClick={() => copyMessage(i, m.text)} style={{
                    padding: "5px 11px", background: "transparent",
                    border: `1px solid ${p.border}`, borderRadius: 6,
                    color: copiedIdx === i ? "#4FB59F" : p.textMuted,
                    fontFamily: "'Geist', sans-serif", fontSize: 11.5,
                    cursor: "default", display: "flex", alignItems: "center", gap: 5,
                  }}>
                    {copiedIdx === i ? "Copiado" : "Copiar"}
                  </button>
                  <button onClick={() => {
                    // regenerate: pop last user+agent, resend
                    let lastUser = "";
                    for (let j = messages.length - 1; j >= 0; j--) {
                      if (messages[j].role === "user") { lastUser = messages[j].text; break; }
                    }
                    if (!lastUser) return;
                    setMessages(m => m.slice(0, -2));
                    setTimeout(() => send(lastUser), 100);
                  }} style={{
                    padding: "5px 11px", background: "transparent",
                    border: `1px solid ${p.border}`, borderRadius: 6,
                    color: p.textMuted,
                    fontFamily: "'Geist', sans-serif", fontSize: 11.5,
                    cursor: "default",
                  }}>Regenerar</button>
                  <button style={{
                    padding: "5px 11px", background: "transparent",
                    border: `1px solid ${p.border}`, borderRadius: 6,
                    color: p.textMuted,
                    fontFamily: "'Geist', sans-serif", fontSize: 11.5,
                    cursor: "default",
                  }}>Guardar</button>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>

      {/* Suggestions + input */}
      <div style={{
        padding: isMobile ? "12px 14px 18px" : "16px 36px 24px",
        borderTop: `1px solid ${p.borderSoft}`,
        background: p.bg,
      }}>
        <div style={{ maxWidth: 820, margin: "0 auto" }}>
          {/* Barra de aprobación del ADN del Experto */}
          {isAdn && messages.length > 1 && (
            <div style={{
              marginBottom: 14, padding: "13px 15px", borderRadius: 11,
              background: adnApproved ? "rgba(46,125,107,0.12)" : t.accent + "12",
              border: `1px solid ${adnApproved ? "rgba(46,125,107,0.4)" : t.accent + "44"}`,
              display: "flex", alignItems: "center", gap: 13, flexWrap: "wrap",
            }}>
              <div style={{
                width: 34, height: 34, borderRadius: 999, flexShrink: 0,
                background: adnApproved ? "rgba(46,125,107,0.18)" : t.accent + "1c",
                border: `1px solid ${adnApproved ? "#4FB59F66" : t.accent + "55"}`,
                display: "flex", alignItems: "center", justifyContent: "center",
                color: adnApproved ? "#4FB59F" : t.accent,
              }}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none"
                     stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
                  {adnApproved ? <path d="M20 6 9 17l-5-5"/> : <path d="M12 3a9 9 0 1 0 9 9"/>}
                </svg>
              </div>
              <div style={{ flex: 1, minWidth: 200 }}>
                <div style={{
                  fontFamily: "'Geist', sans-serif", fontSize: 13.5, fontWeight: 600,
                  color: p.text, marginBottom: 2,
                }}>{adnApproved ? "ADN aprobado y activo" : "¿Tu ADN ya está completo?"}</div>
                <div style={{
                  fontFamily: "'Geist', sans-serif", fontSize: 12.5, color: p.textMuted, lineHeight: 1.45,
                }}>{adnApproved
                  ? "Este ADN alimenta a todos los agentes del sistema."
                  : "Apruébalo para confirmar que es el que alimentará al resto de los agentes."}</div>
              </div>
              {adnApproved ? (
                <button onClick={reopenAdn} style={{
                  padding: "9px 15px", background: "transparent",
                  border: `1px solid ${p.border}`, borderRadius: 8, color: p.text,
                  fontFamily: "'Geist', sans-serif", fontSize: 12.5, fontWeight: 500, cursor: "default",
                }}>Editar / re-aprobar</button>
              ) : confirming ? (
                <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                  <span style={{ fontFamily: "'Geist', sans-serif", fontSize: 12.5, color: p.text }}>
                    ¿Confirmas que es tu ADN definitivo?
                  </span>
                  <button onClick={approveAdn} style={{
                    padding: "9px 15px", background: t.accent, border: 0, borderRadius: 8,
                    color: "#0A0A0A", fontFamily: "'Geist', sans-serif", fontSize: 12.5, fontWeight: 600, cursor: "default",
                  }}>Sí, aprobar</button>
                  <button onClick={() => setConfirming(false)} style={{
                    padding: "9px 13px", background: "transparent",
                    border: `1px solid ${p.border}`, borderRadius: 8, color: p.textMuted,
                    fontFamily: "'Geist', sans-serif", fontSize: 12.5, cursor: "default",
                  }}>Cancelar</button>
                </div>
              ) : (
                <button onClick={() => setConfirming(true)} style={{
                  padding: "9px 16px", background: t.accent, border: 0, borderRadius: 8,
                  color: "#0A0A0A", fontFamily: "'Geist', sans-serif", fontSize: 12.5, fontWeight: 600, cursor: "default",
                }}>Aprobar mi ADN</button>
              )}
            </div>
          )}

          {!outOfCredits && showSuggestions && suggestions.length > 0 && (
            <div style={{ marginBottom: 14 }}>
              <div style={{
                fontFamily: "'Geist', sans-serif", fontSize: 11,
                color: p.textMuted, letterSpacing: "0.14em",
                textTransform: "uppercase", marginBottom: 10,
              }}>Sugerencias para empezar</div>
              <div style={{
                display: "grid", gap: 8,
                gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr",
              }}>
                {suggestions.map((s, i) => (
                  <button key={i} onClick={() => send(s)} style={{
                    padding: "11px 14px", textAlign: "left",
                    background: p.bg2,
                    border: `1px solid ${p.border}`, borderRadius: 8,
                    color: p.text,
                    fontFamily: "'Geist', sans-serif", fontSize: 13,
                    cursor: "default", transition: "border-color .15s, background .15s",
                    display: "flex", alignItems: "center", gap: 10,
                  }}
                  onMouseEnter={e => e.currentTarget.style.borderColor = t.accent + "55"}
                  onMouseLeave={e => e.currentTarget.style.borderColor = p.border}>
                    <span style={{ color: t.accent, flexShrink: 0 }}>→</span>
                    <span>{s}</span>
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Input */}
          {outOfCredits ? (
            <div style={{
              padding: "22px 20px", borderRadius: 12,
              background: p.bg2, border: `1px solid ${p.border}`,
              display: "flex", flexDirection: "column", alignItems: "center", gap: 6, textAlign: "center",
            }}>
              <div style={{
                fontFamily: "'Montserrat', sans-serif", fontWeight: 700, fontSize: 17, color: p.text,
              }}>Te quedaste sin consultas</div>
              <div style={{
                fontFamily: "'Geist', sans-serif", fontSize: 13.5, color: p.textMuted, maxWidth: 420, lineHeight: 1.5,
              }}>Para seguir trabajando con los agentes, escríbenos y renovamos tu acceso.</div>
              <a href="mailto:soporte@vanesajackson.com?subject=Renovar%20consultas%20MDP"
                 style={{
                   marginTop: 8, padding: "11px 20px", borderRadius: 9,
                   background: t.accent, color: "#0A0A0A", textDecoration: "none",
                   fontFamily: "'Geist', sans-serif", fontSize: 13.5, fontWeight: 600,
                   display: "inline-flex", alignItems: "center", gap: 8,
                 }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                     stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M3 6h18v12H3z"/><path d="m3 6 9 7 9-7"/>
                </svg>
                Contactar a soporte
              </a>
              <div style={{
                marginTop: 2, fontFamily: "'Geist', sans-serif", fontSize: 12, color: p.textDim,
              }}>soporte@vanesajackson.com</div>
            </div>
          ) : (
          <div style={{
            display: "flex", alignItems: "flex-end", gap: 10,
            background: p.bg2, border: `1px solid ${p.border}`,
            borderRadius: 12, padding: "10px 10px 10px 14px",
          }}>
            <button style={{
              width: 32, height: 32, borderRadius: 8,
              background: "transparent", border: `1px solid ${p.border}`,
              color: p.textMuted, cursor: "default",
              display: "flex", alignItems: "center", justifyContent: "center",
              flexShrink: 0,
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                   stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
                <path d="M12 5v14"/><path d="M5 12h14"/>
              </svg>
            </button>
            <textarea
              ref={inputRef}
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault();
                  send();
                }
              }}
              placeholder={`Escribe a ${agent.name}...`}
              rows={1}
              style={{
                flex: 1, background: "transparent", border: 0, outline: "none",
                color: p.text, fontSize: 14.5, lineHeight: 1.5,
                fontFamily: "'Geist', sans-serif",
                resize: "none", padding: "6px 0", maxHeight: 140,
              }}
            />
            <button onClick={() => send()} disabled={!input.trim() || loading}
                    style={{
              padding: "9px 16px",
              background: input.trim() && !loading
                ? `linear-gradient(180deg, ${t.accent}, ${t.accent}cc)`
                : p.bgCard,
              border: 0, borderRadius: 8,
              color: input.trim() && !loading ? "#0A0A0A" : p.textDim,
              fontFamily: "'Geist', sans-serif", fontSize: 13, fontWeight: 500,
              cursor: "default",
              display: "flex", alignItems: "center", gap: 7,
              flexShrink: 0,
            }}>
              Enviar
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
                   stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 12h14"/><path d="m13 6 6 6-6 6"/>
              </svg>
            </button>
          </div>
          )}
          {!outOfCredits && (
          <div style={{
            marginTop: 10, textAlign: "center",
            fontFamily: "'Geist', sans-serif", fontSize: 11,
            color: p.textDim,
          }}>
            Las respuestas siguen el método Marca de Poder. Verifica antes de publicar
            <span style={{ margin: "0 8px", opacity: 0.5 }}>·</span>
            <kbd style={{
              background: p.bg2, border: `1px solid ${p.border}`,
              borderRadius: 4, padding: "1px 6px",
              fontSize: 10, fontFamily: "ui-monospace, monospace",
              color: p.textMuted,
            }}>Enter</kbd>
            <span style={{ marginLeft: 6 }}>para enviar</span>
          </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.ChatView = ChatView;
