/* global React, Icon, AVATAR_VIDEO */
/* ============================================================
   OASIA — Floating Assistant Widget
   Idle video plays in the FAB. Click opens chat panel.
   ============================================================ */

function FloatingAssistant({ open, setOpen }) {
  const [tab, setTab] = React.useState("chat");
  const [messages, setMessages] = React.useState([
    { from: "bot", text: "Hola. Soy Lucía, del equipo de Oasia. Si te apetece, cuéntame en una o dos frases qué te ha traído aquí." },
  ]);
  const [input, setInput] = React.useState("");
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages, open]);

  const quickReplies = [
    "Tengo cuotas impagadas",
    "Ya hay procedimiento abierto",
    "Quiero refinanciar",
    "Pensar en dación",
  ];

  const send = (text) => {
    const t = (text || input).trim();
    if (!t) return;
    setMessages([...messages, { from: "user", text: t }]);
    setInput("");
    setTimeout(() => {
      setMessages((m) => [...m, {
        from: "bot",
        text: "Gracias por contarme. Voy a hacerte tres o cuatro preguntas muy sencillas para entender bien tu caso. Cuando terminemos, un compañero del equipo te llamará — solo si tú quieres y solo cuando tengamos algo concreto que ofrecerte.",
      }]);
    }, 600);
  };

  return (
    <>
      {/* FAB */}
      {!open && (
        <button
          onClick={() => setOpen(true)}
          aria-label="Abrir asistente Lucía"
          className="assistant-fab"
          style={{
            position: "fixed",
            bottom: 28, right: 28,
            display: "flex", alignItems: "center", gap: 14,
            padding: "8px 22px 8px 8px",
            background: "var(--bg-2)",
            border: "1px solid var(--line)",
            borderRadius: "var(--r-pill)",
            boxShadow: "0 18px 40px -12px rgba(20, 56, 54, 0.35), 0 6px 16px rgba(0,0,0,0.08)",
            cursor: "pointer",
            zIndex: 50,
            transition: "all .25s",
            fontFamily: "var(--font-sans)",
          }}
          onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "0 26px 48px -14px rgba(20, 56, 54, 0.45), 0 8px 20px rgba(0,0,0,0.10)"; }}
          onMouseLeave={(e) => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.boxShadow = "0 18px 40px -12px rgba(20, 56, 54, 0.35), 0 6px 16px rgba(0,0,0,0.08)"; }}
        >
          <div style={{
            position: "relative",
            width: 56, height: 56,
            borderRadius: "50%",
            overflow: "hidden",
            background: "var(--petrol-dark)",
            flexShrink: 0,
          }}>
            <video
              src={AVATAR_VIDEO}
              autoPlay loop muted playsInline
              style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "center 18%" }}
            />
          </div>
          <div style={{ textAlign: "left", paddingRight: 4 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--ink)", lineHeight: 1.1 }}>
              Hablar con Lucía
            </div>
            <div style={{ fontSize: 11, color: "var(--ink-3)", display: "inline-flex", alignItems: "center", gap: 6, marginTop: 3 }}>
              <span style={{ display: "inline-block", width: 6, height: 6, borderRadius: "50%", background: "var(--success)" }} />
              Disponible ahora · 24/7
            </div>
          </div>
        </button>
      )}

      {/* Panel */}
      {open && (
        <div className="assistant-panel" style={{
          position: "fixed",
          bottom: 28, right: 28,
          width: 400,
          maxHeight: "calc(100vh - 56px)",
          background: "var(--bg-2)",
          border: "1px solid var(--line)",
          borderRadius: "var(--r-xl)",
          boxShadow: "0 40px 80px -16px rgba(20, 56, 54, 0.4), 0 16px 32px rgba(0,0,0,0.12)",
          zIndex: 50,
          display: "flex", flexDirection: "column",
          overflow: "hidden",
          animation: "fadeUp .35s cubic-bezier(.2,.7,.2,1)",
        }}>
          {/* Header with avatar */}
          <div style={{
            position: "relative",
            padding: "20px 20px 16px",
            background: "linear-gradient(160deg, #1F4F4B 0%, #143836 100%)",
            color: "#fff",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <div style={{
                width: 52, height: 52,
                borderRadius: "50%",
                overflow: "hidden",
                border: "2px solid rgba(248,244,234,0.25)",
                flexShrink: 0,
              }}>
                <video
                  src={AVATAR_VIDEO}
                  autoPlay loop muted playsInline
                  style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "center 18%" }}
                />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 19, fontWeight: 500 }}>
                  Lucía
                </div>
                <div style={{ fontSize: 12, color: "rgba(248,244,234,0.70)", display: "inline-flex", alignItems: "center", gap: 6, marginTop: 2 }}>
                  <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#7ad19c", display: "inline-block" }} />
                  Asistente de Oasia · En línea
                </div>
              </div>
              <button
                onClick={() => setOpen(false)}
                style={{
                  width: 32, height: 32,
                  background: "rgba(255,255,255,0.10)",
                  border: "none",
                  borderRadius: "50%",
                  color: "#fff",
                  cursor: "pointer",
                  display: "flex", alignItems: "center", justifyContent: "center",
                }}
                aria-label="Cerrar"
              >
                <Icon name="x" size={16} />
              </button>
            </div>
          </div>

          {/* Tabs */}
          <div style={{ display: "flex", borderBottom: "1px solid var(--line)", background: "var(--bg-2)" }}>
            {[
              ["chat", "Chat", "msg"],
              ["video", "Videollamada", "video"],
              ["channels", "Canales", "globe"],
            ].map(([k, lbl, icn]) => (
              <button key={k} onClick={() => setTab(k)} style={{
                flex: 1,
                padding: "12px 8px",
                background: "transparent",
                color: tab === k ? "var(--petrol)" : "var(--ink-3)",
                border: "none",
                borderBottom: tab === k ? "2px solid var(--petrol)" : "2px solid transparent",
                cursor: "pointer",
                fontSize: 12.5, fontWeight: 600,
                display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6,
                marginBottom: -1,
              }}>
                <Icon name={icn} size={14} />
                {lbl}
              </button>
            ))}
          </div>

          {tab === "chat" && (
            <>
              <div ref={scrollRef} style={{
                flex: 1,
                padding: 20,
                display: "flex", flexDirection: "column", gap: 12,
                overflowY: "auto",
                maxHeight: 360,
                minHeight: 320,
                background: "var(--bg)",
              }}>
                {messages.map((m, i) => (
                  <div key={i} style={{
                    alignSelf: m.from === "user" ? "flex-end" : "flex-start",
                    maxWidth: "85%",
                    padding: "11px 16px",
                    background: m.from === "user" ? "var(--petrol)" : "var(--bg-2)",
                    color: m.from === "user" ? "#fff" : "var(--ink)",
                    border: m.from === "user" ? "none" : "1px solid var(--line)",
                    borderRadius: m.from === "user" ? "18px 18px 4px 18px" : "18px 18px 18px 4px",
                    fontSize: 14, lineHeight: 1.55,
                    animation: "fadeUp .3s",
                  }}>
                    {m.text}
                  </div>
                ))}

                {messages.length <= 2 && (
                  <div style={{ marginTop: 6, display: "flex", flexWrap: "wrap", gap: 6 }}>
                    {quickReplies.map((r) => (
                      <button key={r} onClick={() => send(r)} style={{
                        padding: "8px 12px",
                        fontSize: 12.5,
                        background: "var(--bg-2)",
                        color: "var(--petrol)",
                        border: "1px solid var(--petrol-line)",
                        borderRadius: "var(--r-pill)",
                        cursor: "pointer",
                        fontWeight: 500,
                      }}>
                        {r}
                      </button>
                    ))}
                  </div>
                )}
              </div>

              <div style={{
                padding: 14,
                borderTop: "1px solid var(--line)",
                background: "var(--bg-2)",
                display: "flex", gap: 8, alignItems: "center",
              }}>
                <input
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  onKeyDown={(e) => e.key === "Enter" && send()}
                  placeholder="Escribe lo que necesites…"
                  style={{
                    flex: 1,
                    padding: "12px 16px",
                    background: "var(--bg)",
                    border: "1px solid var(--line)",
                    borderRadius: "var(--r-pill)",
                    fontSize: 14,
                    fontFamily: "var(--font-sans)",
                    color: "var(--ink)",
                    outline: "none",
                  }}
                />
                <button onClick={() => send()} style={{
                  width: 40, height: 40,
                  background: "var(--petrol)",
                  border: "none",
                  borderRadius: "50%",
                  color: "#fff",
                  cursor: "pointer",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  flexShrink: 0,
                }}>
                  <Icon name="send" size={16} />
                </button>
              </div>
              <div style={{
                padding: "8px 14px 12px",
                fontSize: 11,
                color: "var(--ink-3)",
                textAlign: "center",
                background: "var(--bg-2)",
                borderTop: "1px solid var(--line)",
                display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6,
              }}>
                <Icon name="lock" size={11} />
                Conversación cifrada y confidencial
              </div>
            </>
          )}

          {tab === "video" && (
            <div style={{
              padding: "32px 24px",
              textAlign: "center",
              display: "flex", flexDirection: "column", alignItems: "center", gap: 18,
              background: "var(--bg-2)",
              flex: 1,
            }}>
              <div style={{
                width: 160, height: 160,
                borderRadius: "50%",
                overflow: "hidden",
                border: "3px solid var(--petrol-soft)",
              }}>
                <video
                  src={AVATAR_VIDEO}
                  autoPlay loop muted playsInline
                  style={{ width: "100%", height: "100%", objectFit: "cover", objectPosition: "center 18%" }}
                />
              </div>
              <div>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 500, marginBottom: 6 }}>
                  Videollamada con Lucía
                </div>
                <p style={{ fontSize: 14, color: "var(--ink-2)", maxWidth: 280, lineHeight: 1.5 }}>
                  Habla cara a cara con nuestra asistente. Igual que con una persona, pero a cualquier hora.
                </p>
              </div>
              <button className="btn btn-primary">
                <Icon name="video" size={16} />
                Iniciar videollamada
              </button>
              <div className="meta" style={{ fontSize: 12 }}>
                No necesitas cámara · Solo audio si prefieres
              </div>
            </div>
          )}

          {tab === "channels" && (
            <div style={{
              padding: 20,
              display: "flex", flexDirection: "column", gap: 10,
              background: "var(--bg-2)",
              flex: 1,
            }}>
              <div style={{ fontSize: 13, color: "var(--ink-2)", marginBottom: 6 }}>
                Si prefieres seguir la conversación en otro canal:
              </div>
              {[
                { icon: "whatsapp", title: "WhatsApp", body: "Más cómodo desde tu móvil. La conversación se guarda contigo.", cta: "Abrir WhatsApp" },
                { icon: "phone",    title: "Teléfono",  body: "Hablar de viva voz, sin nada por escrito. 24/7.", cta: "Llamar al 900 000 000" },
                { icon: "msg",      title: "Correo electrónico", body: "Para casos con documentación adjunta o más complejos.", cta: "Escribir a hola@oasia.es" },
              ].map((c) => (
                <a key={c.title} href="#" style={{
                  display: "flex", alignItems: "flex-start", gap: 12,
                  padding: 14,
                  background: "var(--bg)",
                  border: "1px solid var(--line)",
                  borderRadius: "var(--r-md)",
                  textDecoration: "none",
                  transition: "all .2s",
                }}
                  onMouseEnter={(e) => e.currentTarget.style.borderColor = "var(--petrol)"}
                  onMouseLeave={(e) => e.currentTarget.style.borderColor = "var(--line)"}
                >
                  <div style={{
                    width: 36, height: 36, flexShrink: 0,
                    background: "var(--petrol-soft)",
                    borderRadius: "50%",
                    display: "flex", alignItems: "center", justifyContent: "center",
                  }}>
                    <Icon name={c.icon} size={16} color="var(--petrol)" />
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600, fontSize: 14, color: "var(--ink)", marginBottom: 2 }}>{c.title}</div>
                    <div style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.4, marginBottom: 6 }}>{c.body}</div>
                    <div style={{ fontSize: 12, color: "var(--petrol)", fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 4 }}>
                      {c.cta}
                      <Icon name="arrowRight" size={12} />
                    </div>
                  </div>
                </a>
              ))}
            </div>
          )}
        </div>
      )}
    </>
  );
}

window.FloatingAssistant = FloatingAssistant;
