// AI chat assistant. Uses OpenAI when a key is present, otherwise a built-in
// knowledge-based responder so it answers customers out of the box.
//
// To enable OpenAI: set  window.ANSYS_OPENAI_KEY = "sk-..."  before this script,
// or replace the empty string below. Model defaults to gpt-4o-mini.
const NS_BOT = window.AnsysDigitalDesignSystem_4543d7;
const OPENAI_KEY = (typeof window !== "undefined" && window.ANSYS_OPENAI_KEY) || "";
const OPENAI_MODEL = (typeof window !== "undefined" && window.ANSYS_OPENAI_MODEL) || "gpt-4o-mini";

const BOT_SYSTEM = `You are the AI assistant for Ansys Digital, a premium Shopify design and development agency. Ansys Digital works EXCLUSIVELY on Shopify — never suggest or discuss other platforms (WooCommerce, Magento, Wix, etc.) as services you offer; you may only mention migrating FROM any platform TO Shopify.
Services: Shopify store design, custom development, redesign, theme customization, speed optimization, migration to Shopify, landing pages, CRO, and maintenance & support. You also offer 55+ advanced Shopify features (cart, product-page, and section features) and can customize any reference design a customer provides.
Policy: 2 complimentary revisions valid for 21 days after delivery; a free 30-minute Google Meet onboarding training on delivery (great for beginners). Pricing is custom-quoted after a free discovery call. You serve brands across USA, UK, Canada, Australia, UAE, Europe and India.
Contact: WhatsApp +91 92780 24499, email support@ansysdigital.com.
Tone: confident, warm, concise. Keep answers short (2-4 sentences). Always guide the customer toward booking a free discovery call or messaging on WhatsApp. Never use emoji.`;

const BOT_SUGGEST = ["What services do you offer?", "How much does a Shopify store cost?", "Do you offer training?", "Can you migrate my store to Shopify?"];

function botFallback(q) {
  const t = q.toLowerCase();
  const has = (...w) => w.some((x) => t.includes(x));
  if (has("price", "cost", "pricing", "quote", "budget", "charge")) return "We don't use fixed packages — every store is different. After a free discovery call we scope a custom quote, so you only pay for what your store actually needs. Want to book a call?";
  if (has("training", "learn", "beginner", "how to use", "manage")) return "Yes — on delivery you get a free 30-minute Google Meet walkthrough covering your dashboard, products, orders, payments and more. It's perfect if you're new to Shopify.";
  if (has("revision", "change", "edit after", "changes")) return "You get 2 complimentary revisions, valid for 21 days after handover — so we can fine-tune the store once it's live.";
  if (has("migrat", "move", "switch", "transfer")) return "Absolutely. We migrate from any platform to Shopify with zero data loss and no SEO drop. Share your current store and we'll map out the move.";
  if (has("time", "how long", "timeline", "deliver", "fast")) return "Most Shopify stores are designed and launched within a few weeks, depending on scope. You'll get a clear timeline in your proposal.";
  if (has("service", "do you do", "offer", "help with", "what can")) return "We handle everything Shopify: store design, custom development, redesign, speed optimization, migration, landing pages, CRO, and ongoing support — plus 55+ advanced features we can customize to any design you like.";
  if (has("feature", "cart", "product page", "section", "upsell", "customi")) return "We offer 55+ advanced Shopify features across cart, product pages and sections — and if you send a reference site or design, we customize and deliver it on your store.";
  if (has("contact", "call", "whatsapp", "email", "reach", "book", "talk")) return "Easiest ways to reach us: WhatsApp +91 92780 24499 or email support@ansysdigital.com. Would you like to book a free discovery call?";
  if (has("hi", "hello", "hey", "namaste")) return "Hi! I'm the Ansys Digital assistant. Ask me anything about building, redesigning, or scaling your Shopify store.";
  return "Great question! We're a premium Shopify agency handling design, development, migration, CRO and support. For specifics, book a free discovery call or message us on WhatsApp at +91 92780 24499.";
}

async function botAsk(history) {
  if (!OPENAI_KEY) { await new Promise((r) => setTimeout(r, 500)); return botFallback(history[history.length - 1].content); }
  try {
    const res = await fetch("https://api.openai.com/v1/chat/completions", {
      method: "POST",
      headers: { "Content-Type": "application/json", Authorization: "Bearer " + OPENAI_KEY },
      body: JSON.stringify({ model: OPENAI_MODEL, temperature: 0.5, max_tokens: 260, messages: [{ role: "system", content: BOT_SYSTEM }, ...history] }),
    });
    if (!res.ok) throw new Error("api");
    const data = await res.json();
    return data.choices?.[0]?.message?.content?.trim() || botFallback(history[history.length - 1].content);
  } catch (e) {
    return botFallback(history[history.length - 1].content);
  }
}

function ChatBot() {
  const [open, setOpen] = React.useState(false);
  const [msgs, setMsgs] = React.useState([{ role: "assistant", content: "Hi! I'm the Ansys Digital assistant. Ask me anything about designing, building, or scaling your Shopify store." }]);
  const [input, setInput] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const scrollRef = React.useRef(null);
  React.useEffect(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, [msgs, busy, open]);

  const send = async (text) => {
    const q = (text ?? input).trim();
    if (!q || busy) return;
    const next = [...msgs, { role: "user", content: q }];
    setMsgs(next); setInput(""); setBusy(true);
    const reply = await botAsk(next.filter((m) => m.role !== "system"));
    setMsgs((m) => [...m, { role: "assistant", content: reply }]); setBusy(false);
  };

  return (
    <React.Fragment>
      <button onClick={() => setOpen((o) => !o)} aria-label={open ? "Close chat" : "Chat with us"} className="ai-fab" style={{ position: "fixed", right: 24, bottom: 24, zIndex: 80, width: 60, height: 60, borderRadius: "50%", border: "none", cursor: "pointer", background: "var(--grad-brand,#0E47C0)", color: "#fff", display: "grid", placeItems: "center", boxShadow: "0 14px 34px -8px rgba(14,71,192,.6)", transition: "transform .25s var(--ease-spring,cubic-bezier(.22,1,.36,1))" }}>
        <Ic name={open ? "x" : "message-circle-more"} size={26} />
        {!open ? <span style={{ position: "absolute", top: 2, right: 2, width: 14, height: 14, borderRadius: "50%", background: "var(--accent,#FFD700)", border: "2px solid #fff" }} /> : null}
      </button>

      <div className="ai-panel" style={{ position: "fixed", right: 24, bottom: 96, zIndex: 79, width: "min(380px,calc(100vw - 32px))", height: "min(560px,calc(100vh - 140px))", display: "flex", flexDirection: "column", background: "var(--surface-card,#fff)", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-xl,20px)", boxShadow: "var(--shadow-xl,0 30px 60px -20px rgba(10,13,22,.4))", overflow: "hidden", transformOrigin: "bottom right", transition: "opacity .25s var(--ease-out), transform .25s var(--ease-out)", opacity: open ? 1 : 0, transform: open ? "none" : "translateY(12px) scale(.96)", pointerEvents: open ? "auto" : "none" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "16px 18px", background: "var(--grad-brand,#0E47C0)", color: "#fff" }}>
          <span style={{ width: 40, height: 40, borderRadius: "50%", overflow: "hidden", background: "rgba(255,255,255,.16)", display: "grid", placeItems: "center", flexShrink: 0, border: "1.5px solid rgba(255,255,255,.4)" }}><img src="assets/ai-avatar.png" alt="Ansys AI Assistant" style={{ width: "100%", height: "100%", objectFit: "cover" }} /></span>
          <div style={{ lineHeight: 1.25 }}>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15 }}>Ansys AI Assistant</div>
            <div style={{ fontSize: 12, color: "rgba(255,255,255,.8)", display: "flex", alignItems: "center", gap: 6 }}><span style={{ width: 7, height: 7, borderRadius: "50%", background: "#43e08b" }} /> Online · replies instantly</div>
          </div>
          <button onClick={() => setOpen(false)} aria-label="Close" style={{ marginLeft: "auto", background: "transparent", border: "none", color: "rgba(255,255,255,.85)", cursor: "pointer", display: "grid", placeItems: "center" }}><Ic name="chevron-down" size={22} /></button>
        </div>

        <div ref={scrollRef} style={{ flex: 1, overflowY: "auto", padding: "18px 16px", display: "flex", flexDirection: "column", gap: 12, background: "var(--surface-subtle,#f6f8fb)" }}>
          {msgs.map((m, i) => (
            <div key={i} style={{ alignSelf: m.role === "user" ? "flex-end" : "flex-start", maxWidth: "84%", padding: "10px 14px", borderRadius: m.role === "user" ? "14px 14px 4px 14px" : "14px 14px 14px 4px", background: m.role === "user" ? "var(--brand,#0E47C0)" : "var(--surface-card,#fff)", color: m.role === "user" ? "#fff" : "var(--text-primary)", border: m.role === "user" ? "none" : "1px solid var(--border-subtle)", boxShadow: m.role === "user" ? "none" : "var(--shadow-sm)", fontSize: 14, lineHeight: 1.5, textWrap: "pretty" }}>{m.content}</div>
          ))}
          {busy ? (
            <div style={{ alignSelf: "flex-start", padding: "12px 16px", borderRadius: "14px 14px 14px 4px", background: "var(--surface-card,#fff)", border: "1px solid var(--border-subtle)", boxShadow: "var(--shadow-sm)", display: "flex", gap: 5 }}>
              {[0, 1, 2].map((d) => <span key={d} style={{ width: 7, height: 7, borderRadius: "50%", background: "var(--text-muted,#94a3b8)", animation: "aiDot 1s ease-in-out " + (d * 0.15) + "s infinite" }} />)}
            </div>
          ) : null}
          {msgs.length <= 1 && !busy ? (
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 4 }}>
              {BOT_SUGGEST.map((s) => (
                <button key={s} onClick={() => send(s)} style={{ padding: "8px 12px", borderRadius: "var(--radius-pill,999px)", border: "1px solid var(--blue-200)", background: "var(--blue-50)", color: "var(--brand)", fontSize: 12.5, fontWeight: 600, cursor: "pointer", font: "inherit", lineHeight: 1.2 }}>{s}</button>
              ))}
            </div>
          ) : null}
        </div>

        <form onSubmit={(e) => { e.preventDefault(); send(); }} style={{ display: "flex", gap: 8, padding: 12, borderTop: "1px solid var(--border-subtle)", background: "var(--surface-card,#fff)" }}>
          <input value={input} onChange={(e) => setInput(e.target.value)} placeholder="Ask about your Shopify store…" style={{ flex: 1, padding: "11px 14px", borderRadius: "var(--radius-pill,999px)", border: "1px solid var(--border-default)", fontSize: 14, outline: "none", font: "inherit", color: "var(--text-primary)", background: "var(--surface-subtle,#f6f8fb)" }} />
          <button type="submit" disabled={busy || !input.trim()} aria-label="Send" style={{ flexShrink: 0, width: 44, height: 44, borderRadius: "50%", border: "none", cursor: busy || !input.trim() ? "default" : "pointer", background: busy || !input.trim() ? "var(--neutral-300,#cbd5e1)" : "var(--brand,#0E47C0)", color: "#fff", display: "grid", placeItems: "center", transition: "background .2s" }}><Ic name="send" size={18} /></button>
        </form>
      </div>
    </React.Fragment>
  );
}
Object.assign(window, { ChatBot });
