/* AI-Jhostter — chatbot impulsado por Google Gemini.
   ───────────────────────────────────────────────────────────────────────────
   El chat llama al backend Express (server.js) en /api/chat.
   El backend usa GEMINI_API_KEY (variable de entorno) para llamar a Gemini,
   alimentado con el CV completo de Jhostter (PDF + datos del perfil).
   La API key NUNCA se expone en el navegador.
   ─────────────────────────────────────────────────────────────────────────── */
const CHAT_API_CONFIG = {
  // Endpoint del backend Express. Relativo al dominio donde se sirva.
  url: "/api/chat",
  // false = siempre usa el backend Gemini (no demo)
  preferPreviewApi: false
};

const { useState, useRef, useEffect } = React;

function buildSystemPrompt(lang) {
  const C = window.CONTENT;
  const exp = C.experience.map((e) => `- ${e.role[lang]} @ ${e.company} (${e.period[lang]}): ${e.points[lang].join(" ")}`).join("\n");
  const skills = C.skills.map((s) => `${s.group[lang]}: ${s.items.join(", ")}`).join("\n");
  const projs = C.projects.map((p) => `* ${p.name} — ${p.summary[lang]} Stack: ${p.stack.join(", ")}. ${p.highlights[lang].join(" ")}`).join("\n");
  const edu = C.education.map((e) => `- ${e.degree[lang]} @ ${e.school} (${e.period})`).join("\n");

  const persona = lang === "es" ?
  `Eres "AI-Jhostter", el gemelo de IA de Jhostter Antonio Valdez Ortiz, en su portafolio profesional. Hablas en PRIMERA PERSONA como si fueras Jhostter. Eres cercano, profesional y seguro, con un toque técnico. Responde SIEMPRE en español. Sé conciso (2-4 frases máximo, usa viñetas solo si ayuda). Si te preguntan algo que no está en mi información, dilo con honestidad y redirige a contactarme por WhatsApp o LinkedIn. Nunca inventes datos.` :
  `You are "AI-Jhostter", the AI twin of Jhostter Antonio Valdez Ortiz, embedded in his professional portfolio. Speak in the FIRST PERSON as if you were Jhostter. You are warm, professional, and confident, with a technical edge. ALWAYS reply in English. Be concise (2-4 sentences max, bullets only if helpful). If asked something not in my info, say so honestly and redirect to contacting me on WhatsApp or LinkedIn. Never make up data.`;

  return `${persona}

=== MI PERFIL / MY PROFILE ===
Nombre: Jhostter Antonio Valdez Ortiz
Roles: QA Automation Engineer, SDET, DevOps Technical Lead, AI Agent Engineer
Ubicación: Santo Domingo, República Dominicana. Disponible para remoto internacional.
Resumen: ${window.I18N[lang].about.body}

=== EXPERIENCIA / EXPERIENCE ===
${exp}

=== SKILLS ===
${skills}

=== PROYECTOS / PROJECTS ===
${projs}

=== EDUCACIÓN / EDUCATION ===
${edu}

=== CONTACTO ===
LinkedIn: ${C.contact.linkedin}
Teléfono: ${C.contact.phone}
WhatsApp: +1 ${C.contact.whatsapp}`;
}

function fmtMsg(text) {
  const esc = String(text)
    .replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  return esc
    .replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>")
    .replace(/\*(.+?)\*/g, "<em>$1</em>")
    .replace(/\n/g, "<br>");
}

function AIChat({ lang, t }) {
  const H = t.hero;
  const [messages, setMessages] = useState([{ role: "bot", text: H.chatIntro }]);
  const [input, setInput] = useState("");
  const [busy, setBusy] = useState(false);
  const [showSugg, setShowSugg] = useState(true);
  const bodyRef = useRef(null);
  const introRef = useRef(H.chatIntro);

  // Reset intro when language changes (only if conversation is fresh)
  useEffect(() => {
    setMessages((m) => {
      if (m.length === 1 && m[0].role === "bot") return [{ role: "bot", text: H.chatIntro }];
      return m;
    });
  }, [lang]);

  useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [messages, busy]);

  // Llama al backend Gemini (server.js /api/chat).
  // Envía el idioma e historial completo; el backend construye el system prompt con el CV.
  async function callBackend(systemPrompt, history) {
    const res = await fetch(CHAT_API_CONFIG.url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        lang,
        messages: history
          .filter((m) => m.role === "user" || m.role === "bot")
          .map((m) => ({ role: m.role === "user" ? "user" : "assistant", content: m.text }))
      })
    });
    if (!res.ok) throw new Error("backend-" + res.status);
    const data = await res.json();
    return data.reply || data.text || data.content || "";
  }

  async function send(text) {
    const q = (text ?? input).trim();
    if (!q || busy) return;
    setShowSugg(false);
    setInput("");
    const history = [...messages, { role: "user", text: q }];
    setMessages(history);
    setBusy(true);
    try {
      const systemPrompt = buildSystemPrompt(lang);
      const usePreviewApi = CHAT_API_CONFIG.preferPreviewApi && window.claude && window.claude.complete;
      let reply;
      if (usePreviewApi) {
        // Demo dentro del entorno de previsualización
        const convo = history.
        filter((m) => m.role === "user" || m.role === "bot").
        map((m) => `${m.role === "user" ? "Usuario" : "AI-Jhostter"}: ${m.text}`).
        join("\n");
        const prompt = `${systemPrompt}\n\n=== CONVERSACIÓN ===\n${convo}\nAI-Jhostter:`;
        reply = await window.claude.complete(prompt);
      } else {
        // Producción: backend propio que protege la API key
        reply = await callBackend(systemPrompt, history);
      }
      setMessages((m) => [...m, { role: "bot", text: (reply || "").trim() || H.chatError }]);
    } catch (e) {
      setMessages((m) => [...m, { role: "bot", text: H.chatError }]);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="chat-card glass">
      <div className="avatar-orb">
        <div className="avatar-ring"></div>
        <div className="avatar-photo hav-orb" data-comment-anchor="b3ab775d24-img-89-39">
          <svg className="hav" viewBox="0 0 100 100" role="img" aria-label="Avatar humanoide IA animado">
            <defs>
              <linearGradient id="havBody" x1="0" y1="0" x2="1" y2="1">
                <stop offset="0" stopColor="#8fc0ff"></stop>
                <stop offset="1" stopColor="#5b9dff"></stop>
              </linearGradient>
              <radialGradient id="havBg" cx="50%" cy="36%" r="72%">
                <stop offset="0" stopColor="#16213c"></stop>
                <stop offset="1" stopColor="#070a12"></stop>
              </radialGradient>
              <linearGradient id="havVisor" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0" stopColor="#0c1426"></stop>
                <stop offset="1" stopColor="#05070f"></stop>
              </linearGradient>
              <clipPath id="havVisorClip">
                <rect x="36" y="30" width="28" height="20" rx="9"></rect>
              </clipPath>
            </defs>
            <rect width="100" height="100" fill="url(#havBg)"></rect>
            <circle className="hav-aura" cx="50" cy="42" r="30" fill="none" stroke="#5b9dff" strokeOpacity="0.28" strokeWidth="0.6"></circle>
            <g className="hav-figure">
              <path d="M19 100 C19 77 31 67 50 67 C69 67 81 77 81 100 Z" fill="url(#havBody)"></path>
              <path d="M19 100 C19 77 31 67 50 67 C69 67 81 77 81 100 Z" fill="#06070b" opacity="0.16"></path>
              <rect x="44" y="55" width="12" height="15" rx="5" fill="url(#havBody)"></rect>
              <rect x="32" y="20" width="36" height="40" rx="15" fill="url(#havBody)"></rect>
              <rect x="36" y="30" width="28" height="20" rx="9" fill="url(#havVisor)"></rect>
              <g className="hav-eyes">
                <rect className="hav-eye" x="42" y="37" width="5" height="6" rx="2.5" fill="#a8d4ff"></rect>
                <rect className="hav-eye" x="53" y="37" width="5" height="6" rx="2.5" fill="#a8d4ff"></rect>
              </g>
              <g clipPath="url(#havVisorClip)">
                <rect className="hav-scan" x="36" y="30" width="28" height="2.2" fill="#5b9dff" opacity="0.6"></rect>
              </g>
              <line x1="50" y1="20" x2="50" y2="13" stroke="#8fc0ff" strokeWidth="1.6" strokeLinecap="round"></line>
              <circle className="hav-pulse" cx="50" cy="11" r="2.4" fill="#a8d4ff"></circle>
            </g>
          </svg>
        </div>
      </div>
      <div className="chat-head">
        <div className="chat-head-txt">
          <b>{H.chatTitle}</b>
          <small>{H.chatSubtitle}</small>
        </div>
        <span className="chat-badge"><i className="dot live"></i>{H.chatLive}</span>
      </div>
      <div className="chat-body" ref={bodyRef}>
        {messages.map((m, i) =>
        <div key={i} className={`msg ${m.role}`} dangerouslySetInnerHTML={{ __html: fmtMsg(m.text) }}></div>
        )}
        {busy &&
        <div className="msg bot">
            <span className="typing"><i></i><i></i><i></i></span>
          </div>
        }
      </div>
      {showSugg &&
      <div className="chat-sugg">
          {H.chatSuggestions.map((s, i) =>
        <button key={i} onClick={() => send(s)}>{s}</button>
        )}
        </div>
      }
      <form className="chat-input" onSubmit={(e) => {e.preventDefault();send();}}>
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder={H.chatPlaceholder}
          aria-label={H.chatPlaceholder} />
        
        <button type="submit" className="chat-send" disabled={busy} aria-label="Enviar">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
        </button>
      </form>
    </div>);

}

window.AIChat = AIChat;