/* global React, Icon, VENTURES, UNIDADES, WHATSAPP, WHATSAPP_URL */
const { useState: useStateBot, useRef: useRefBot, useEffect: useEffectBot } = React;

/* Build the portfolio knowledge base for the assistant from the live data */
function buildContext() {
  const units = UNIDADES.map(u => `- ${u.titulo}: ${u.desc} (${u.items.map(i => i.label).join(", ")})`).join("\n");
  const vents = VENTURES.map(v => `- ${v.name} [${v.sector} · ${v.estado}]${v.url ? " · " + v.url : ""}: ${v.blurb}`).join("\n");
  return `Eres "Alzio para 3H", el asistente virtual de 3H enterprise (treshache.co), desarrolladores de proyectos desde 2010 en Colombia. Estás impulsado por la tecnología de Alzio, el agente de IA de 3H.

TONO: cálido, cercano, profesional y breve. Responde SIEMPRE en español, en 2-4 frases máximo, con formato natural (puedes usar viñetas cortas). No inventes datos que no estén aquí; si no sabes algo, ofrece poner en contacto con el equipo por WhatsApp (${WHATSAPP}).

QUÉ ES 3H: desarrollamos proyectos reales (desde el diagnóstico hasta la operación) y el software que los impulsa. Dos unidades:
${units}

PORTAFOLIO VIGENTE:
${vents}

DETALLE DE ELEMENT (Lago Calima): lotes urbanizados desde 1.500 m² en Restrepo, Valle del Cauca, sobre la vía Buga–Buenaventura km 32. Precios desde $195.000.000 COP. Cada lote incluye sin costo el diseño de una casa; la construcción es opcional con descuento en DIKE Ingeniería. Amenidades: hotel dentro del proyecto, piscina infinita, restaurante gourmet, alquiler de embarcaciones y lancha-taxi. Clima 17-34°C, ideal para kitesurf y wingfoil. A 35 min de Buga y 60 de Cali.

OBJETIVO: resolver dudas sobre 3H y sus proyectos, e impulsar el contacto. Cuando alguien muestre interés real (invertir, cotizar, agendar visita, contratar software), invítalo a continuar por WhatsApp: ${WHATSAPP}.`;
}

function AlzioBot() {
  const [open, setOpen] = useStateBot(false);
  const [messages, setMessages] = useStateBot([
    { role: "assistant", content: "¡Hola! Soy Alzio, el asistente de 3H 👋 Puedo contarte sobre nuestros proyectos —como Element en el Lago Calima— o sobre cómo desarrollamos proyectos y software. ¿En qué te ayudo?" },
  ]);
  const [input, setInput] = useStateBot("");
  const [loading, setLoading] = useStateBot(false);
  const scrollRef = useRefBot(null);

  useEffectBot(() => { window.__openAlzio = () => setOpen(true); }, []);
  useEffectBot(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, [messages, loading, open]);

  const suggestions = [
    "¿Qué proyectos tienen?",
    "Quiero invertir en Element",
    "Desarrollan software a la medida?",
  ];

  async function send(text) {
    const q = (text ?? input).trim();
    if (!q || loading) return;
    const next = [...messages, { role: "user", content: q }];
    setMessages(next);
    setInput("");
    setLoading(true);
    try {
      const convo = next.map(m => `${m.role === "user" ? "Usuario" : "Alzio"}: ${m.content}`).join("\n");
      const prompt = `${buildContext()}\n\nConversación:\n${convo}\nAlzio:`;
      const reply = await window.claude.complete(prompt);
      setMessages(m => [...m, { role: "assistant", content: (reply || "").trim() || "Perdona, no pude procesar eso. ¿Lo intentamos de otra forma?" }]);
    } catch (e) {
      setMessages(m => [...m, { role: "assistant", content: `Tuve un problema para responder. Escríbenos directo por WhatsApp al ${WHATSAPP} y te atendemos enseguida.` }]);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div>
      {/* Launcher */}
      <button onClick={() => setOpen(o => !o)}
        className="fixed bottom-5 right-5 z-50 flex h-14 w-14 items-center justify-center rounded-full bg-taupe-900 text-amber-300 shadow-xl shadow-taupe-900/30 ring-1 ring-white/10 transition hover:scale-105 hover:bg-taupe-800"
        aria-label="Abrir asistente Alzio">
        <Icon name={open ? "X" : "Sparkles"} size={24} />
        {!open && <span className="absolute -right-0.5 -top-0.5 h-3.5 w-3.5 rounded-full bg-amber-400 ring-2 ring-stone-50" />}
      </button>

      {/* Panel */}
      {open && (
        <div className="fixed bottom-24 right-5 z-50 flex h-[min(560px,75vh)] w-[min(380px,calc(100vw-2.5rem))] flex-col overflow-hidden rounded-2xl bg-white shadow-2xl shadow-taupe-900/30 ring-1 ring-taupe-200">
          {/* Header */}
          <div className="flex items-center gap-3 bg-taupe-900 px-4 py-3.5 text-white">
            <span className="grid h-9 w-9 place-items-center rounded-full bg-amber-400 text-taupe-900">
              <Icon name="Sparkles" size={18} />
            </span>
            <div className="leading-tight">
              <div className="font-bold">Alzio · Asistente 3H</div>
              <div className="flex items-center gap-1.5 text-[11px] text-taupe-300">
                <span className="h-1.5 w-1.5 rounded-full bg-emerald-400" /> En línea · IA
              </div>
            </div>
          </div>

          {/* Messages */}
          <div ref={scrollRef} className="flex-1 space-y-3 overflow-y-auto bg-stone-50 p-4 hide-scrollbar">
            {messages.map((m, i) => (
              <div key={i} className={`flex ${m.role === "user" ? "justify-end" : "justify-start"}`}>
                <div className={`max-w-[85%] rounded-2xl px-3.5 py-2.5 text-sm leading-relaxed ${m.role === "user" ? "rounded-br-md bg-taupe-900 text-white" : "rounded-bl-md bg-white text-taupe-800 ring-1 ring-taupe-200"}`}>
                  {m.content}
                </div>
              </div>
            ))}
            {loading && (
              <div className="flex justify-start">
                <div className="flex gap-1 rounded-2xl rounded-bl-md bg-white px-4 py-3 ring-1 ring-taupe-200">
                  <span className="h-1.5 w-1.5 animate-bounce rounded-full bg-taupe-400" style={{ animationDelay: "0ms" }} />
                  <span className="h-1.5 w-1.5 animate-bounce rounded-full bg-taupe-400" style={{ animationDelay: "150ms" }} />
                  <span className="h-1.5 w-1.5 animate-bounce rounded-full bg-taupe-400" style={{ animationDelay: "300ms" }} />
                </div>
              </div>
            )}
            {messages.length <= 1 && !loading && (
              <div className="flex flex-wrap gap-2 pt-1">
                {suggestions.map(s => (
                  <button key={s} onClick={() => send(s)}
                    className="rounded-full bg-white px-3 py-1.5 text-xs font-medium text-taupe-700 ring-1 ring-taupe-200 transition hover:bg-taupe-100">
                    {s}
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Input */}
          <div className="border-t border-taupe-100 bg-white p-3">
            <div className="flex items-end gap-2">
              <textarea value={input} onChange={e => setInput(e.target.value)} rows={1}
                onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }}
                placeholder="Escribe tu mensaje…"
                className="max-h-24 flex-1 resize-none rounded-xl border-0 bg-stone-100 px-3.5 py-2.5 text-sm text-taupe-900 outline-none ring-1 ring-taupe-200 placeholder:text-taupe-400 focus:ring-taupe-400" />
              <button onClick={() => send()} disabled={loading || !input.trim()}
                className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-taupe-900 text-amber-300 transition hover:bg-taupe-800 disabled:opacity-40">
                <Icon name="Send" size={17} />
              </button>
            </div>
            <a href={WHATSAPP_URL} target="_blank" rel="noopener noreferrer"
              className="mt-2 flex items-center justify-center gap-1.5 text-[11px] font-medium text-taupe-400 hover:text-taupe-600 transition">
              <Icon name="MessageCircle" size={12} /> o continúa por WhatsApp con el equipo
            </a>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { AlzioBot });
