/* global React */
const { useState: useStateAI, useRef: useRefAI, useEffect: useEffectAI } = React;

/* canned answers keyed loosely; concept only */
const CANNED = {
  es: {
    begur: "En Begur, una villa con vistas al mar parte de unos 850.000 € y puede superar los 3 M€ en primera línea. ¿Te preparo una selección?",
    impuestos: "Un comprador extranjero paga el ITP (10% en 2ª mano en Cataluña) o IVA 10% en obra nueva, más notaría y registro (~1-2%). Te lo detallamos por escrito.",
    visita: "¡Encantados! Podemos agendar una vídeo-visita en directo esta misma semana. ¿Qué día y en qué idioma te va mejor?",
    default: "Gracias por tu mensaje. Un asesor de Grup GCB te responderá enseguida. ¿En qué zona y con qué presupuesto estás pensando?",
  },
  en: {
    begur: "In Begur, a sea-view villa starts around €850,000 and can exceed €3M on the front line. Shall I prepare a shortlist?",
    impuestos: "A foreign buyer pays ITP transfer tax (10% on resale in Catalonia) or 10% VAT on new build, plus notary and registry (~1-2%). We'll send the full breakdown.",
    visita: "With pleasure! We can arrange a live video viewing this week. Which day and in which language suits you best?",
    default: "Thanks for your message. A Grup GCB advisor will reply shortly. Which area and budget did you have in mind?",
  },
  fr: {
    begur: "À Begur, une villa vue mer démarre autour de 850 000 € et peut dépasser 3 M€ en front de mer. Je vous prépare une sélection ?",
    impuestos: "Un acheteur étranger paie l'ITP (10% dans l'ancien en Catalogne) ou 10% de TVA dans le neuf, plus notaire et registre (~1-2%). Nous vous envoyons le détail.",
    visita: "Avec plaisir ! Nous pouvons organiser une visite vidéo en direct cette semaine. Quel jour et dans quelle langue préférez-vous ?",
    default: "Merci pour votre message. Un conseiller Grup GCB vous répondra très vite. Quel secteur et quel budget envisagez-vous ?",
  },
};

function pickAnswer(text, lang) {
  const dict = CANNED[lang] || CANNED.es;
  const s = text.toLowerCase();
  if (/begur|villa|vista|sea|mer|cuesta|coût|cost|precio|price/.test(s)) return dict.begur;
  if (/impuesto|tax|impôt|impot|nie|notar/.test(s)) return dict.impuestos;
  if (/visit|vídeo|video|agend|book|réserv|reserv|tour/.test(s)) return dict.visita;
  return dict.default;
}

function Chatbot({ t, lang, open, setOpen }) {
  const [msgs, setMsgs] = useStateAI([{ from: "bot", text: t.chatGreeting }]);
  const [typing, setTyping] = useStateAI(false);
  const [draft, setDraft] = useStateAI("");
  const bodyRef = useRefAI(null);

  useEffectAI(() => { setMsgs([{ from: "bot", text: t.chatGreeting }]); }, [lang]);
  useEffectAI(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }, [msgs, typing, open]);

  const send = (text) => {
    const clean = (text || "").trim();
    if (!clean) return;
    setMsgs((m) => [...m, { from: "user", text: clean }]);
    setDraft("");
    setTyping(true);
    setTimeout(() => {
      setTyping(false);
      setMsgs((m) => [...m, { from: "bot", text: pickAnswer(clean, lang) }]);
    }, 1100);
  };

  const chips = [t.aiChip1, t.aiChip2, t.aiChip3];

  return (
    <div style={{ position: "fixed", right: 24, bottom: 24, zIndex: 60 }}>
      {open && (
        <div className="panel-in" style={{ position: "absolute", right: 0, bottom: 76, width: 360, maxWidth: "calc(100vw - 48px)", background: "#fff", borderRadius: 14, overflow: "hidden", boxShadow: "0 40px 90px -30px rgba(42,20,20,0.5)", display: "flex", flexDirection: "column", height: 520, maxHeight: "calc(100vh - 130px)" }}>
          {/* header */}
          <div style={{ background: "var(--burgundy)", color: "#fff", padding: "16px 18px", display: "flex", alignItems: "center", gap: 12 }}>
            <div className="font-serif" style={{ width: 40, height: 40, borderRadius: 999, background: "rgba(248,244,237,0.16)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: "1.1rem", fontWeight: 600, color: "#fff" }}>GB</div>
            <div style={{ flex: 1 }}>
              <div className="font-serif" style={{ fontSize: "1rem", fontWeight: 600 }}>{t.chatTitle}</div>
              <div style={{ fontSize: "0.7rem", color: "rgba(248,244,237,0.8)", display: "flex", alignItems: "center", gap: 6 }}>
                <span style={{ width: 7, height: 7, borderRadius: 999, background: "#7bd389" }} />{t.chatStatus}
              </div>
            </div>
            <button onClick={() => setOpen(false)} aria-label="Cerrar" style={{ background: "none", border: "none", color: "#fff", cursor: "pointer", opacity: 0.85, fontSize: 22, lineHeight: 1 }}>×</button>
          </div>

          {/* body */}
          <div ref={bodyRef} className="thin-scroll" style={{ flex: 1, overflowY: "auto", padding: "18px", background: "var(--cream)" }}>
            {msgs.map((m, i) => (
              <div key={i} className="bubble-in" style={{ display: "flex", justifyContent: m.from === "user" ? "flex-end" : "flex-start", marginBottom: 10 }}>
                <div style={{
                  maxWidth: "82%", padding: "10px 14px", borderRadius: 14, fontSize: "0.88rem", lineHeight: 1.45,
                  background: m.from === "user" ? "var(--burgundy)" : "#fff",
                  color: m.from === "user" ? "#fff" : "var(--charcoal)",
                  borderBottomRightRadius: m.from === "user" ? 4 : 14,
                  borderBottomLeftRadius: m.from === "user" ? 14 : 4,
                  boxShadow: "0 6px 18px -10px rgba(42,42,42,0.3)",
                }}>{m.text}</div>
              </div>
            ))}
            {typing && (
              <div style={{ display: "flex", justifyContent: "flex-start" }}>
                <div style={{ background: "#fff", padding: "12px 16px", borderRadius: 14, display: "flex", gap: 4 }}>
                  <span className="dot" style={{ width: 7, height: 7, borderRadius: 999, background: "var(--burgundy-light)" }} />
                  <span className="dot" style={{ width: 7, height: 7, borderRadius: 999, background: "var(--burgundy-light)" }} />
                  <span className="dot" style={{ width: 7, height: 7, borderRadius: 999, background: "var(--burgundy-light)" }} />
                </div>
              </div>
            )}

            {/* quick chips only before first user msg */}
            {msgs.filter((m) => m.from === "user").length === 0 && !typing && (
              <div style={{ marginTop: 10, display: "flex", flexDirection: "column", gap: 8 }}>
                {chips.map((c, i) => (
                  <button key={i} onClick={() => send(c)} style={{ textAlign: "left", background: "#fff", border: "1px solid var(--line)", borderRadius: 999, padding: "9px 14px", fontSize: "0.8rem", color: "var(--burgundy)", cursor: "pointer", fontFamily: "DM Sans, sans-serif" }}>{c}</button>
                ))}
              </div>
            )}
          </div>

          {/* input */}
          <form onSubmit={(e) => { e.preventDefault(); send(draft); }} style={{ display: "flex", gap: 8, padding: 12, borderTop: "1px solid var(--line)", background: "#fff" }}>
            <input value={draft} onChange={(e) => setDraft(e.target.value)} placeholder={t.chatPlaceholder} style={{ flex: 1, border: "1px solid var(--line)", borderRadius: 999, padding: "10px 16px", fontSize: "0.85rem", outline: "none", fontFamily: "DM Sans, sans-serif" }} />
            <button type="submit" aria-label="Enviar" style={{ background: "var(--burgundy)", border: "none", borderRadius: 999, width: 40, height: 40, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", flexShrink: 0 }}>
              <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" /></svg>
            </button>
          </form>
        </div>
      )}

      {/* launcher */}
      <button
        onClick={() => setOpen((o) => !o)}
        className={open ? "" : "floaty"}
        aria-label={t.aiCta}
        style={{ width: 60, height: 60, borderRadius: 999, background: "var(--burgundy)", border: "2px solid var(--gold)", boxShadow: "0 16px 40px -12px rgba(122,36,36,0.6)", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer", marginLeft: "auto" }}
      >
        {open ? (
          <span style={{ color: "#fff", fontSize: 26, lineHeight: 1 }}>×</span>
        ) : (
          <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" /></svg>
        )}
      </button>
    </div>
  );
}

function AITeaser({ t, onOpen }) {
  return (
    <section style={{ background: "#fff", padding: "110px 0", borderTop: "1px solid var(--line)" }}>
      <div className="mx-auto px-6 lg:px-12" style={{ maxWidth: 1340 }}>
        <div className="grid lg:grid-cols-2 gap-14 items-center">
          <div className="reveal">
            <span className="eyebrow" style={{ color: "var(--terracotta)" }}>{t.aiEyebrow}</span>
            <h2 className="font-serif mt-4" style={{ fontSize: "clamp(2rem, 3.6vw, 3.2rem)", fontWeight: 500, lineHeight: 1.08, color: "var(--charcoal)" }}>{t.aiTitle}</h2>
            <p className="mt-6" style={{ color: "#5d574d", fontSize: "1.08rem", lineHeight: 1.7, maxWidth: 480 }}>{t.aiLead}</p>
            <button onClick={onOpen} className="btn-primary font-sans mt-9" style={{ borderRadius: 3, padding: "16px 30px", letterSpacing: "0.12em", textTransform: "uppercase", fontSize: "0.74rem", fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 10, border: "none", cursor: "pointer" }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" /></svg>
              {t.aiCta}
            </button>
          </div>

          {/* faux chat preview */}
          <div className="reveal" data-delay="2" style={{ position: "relative" }}>
            <div style={{ background: "var(--cream)", borderRadius: 14, padding: 22, boxShadow: "0 40px 80px -40px rgba(42,20,20,0.4)", border: "1px solid var(--line)" }}>
              <div className="flex items-center gap-3 mb-5" style={{ paddingBottom: 16, borderBottom: "1px solid var(--line)" }}>
                <div className="font-serif" style={{ width: 38, height: 38, borderRadius: 999, background: "var(--burgundy)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 600 }}>GB</div>
                <div>
                  <div className="font-serif" style={{ fontWeight: 600, color: "var(--charcoal)" }}>{t.chatTitle}</div>
                  <div style={{ fontSize: "0.72rem", color: "#7bd389", display: "flex", alignItems: "center", gap: 5 }}><span style={{ width: 6, height: 6, borderRadius: 999, background: "#7bd389" }} />{t.chatStatus}</div>
                </div>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                <div style={{ alignSelf: "flex-start", background: "#fff", padding: "11px 15px", borderRadius: 14, borderBottomLeftRadius: 4, fontSize: "0.88rem", maxWidth: "85%", boxShadow: "0 6px 16px -10px rgba(0,0,0,0.2)" }}>{t.chatGreeting}</div>
                <div style={{ alignSelf: "flex-end", background: "var(--burgundy)", color: "#fff", padding: "11px 15px", borderRadius: 14, borderBottomRightRadius: 4, fontSize: "0.88rem", maxWidth: "85%" }}>{t.aiChip1}</div>
                <div style={{ alignSelf: "flex-start", background: "#fff", padding: "12px 16px", borderRadius: 14, display: "flex", gap: 4 }}>
                  <span className="dot" style={{ width: 7, height: 7, borderRadius: 999, background: "var(--burgundy-light)" }} />
                  <span className="dot" style={{ width: 7, height: 7, borderRadius: 999, background: "var(--burgundy-light)" }} />
                  <span className="dot" style={{ width: 7, height: 7, borderRadius: 999, background: "var(--burgundy-light)" }} />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Chatbot, AITeaser });
