/* Veridyne Academy — AI assistant widget. Floating button + chat panel.
   Sends questions to /api/ask (grounded in the course KB); employees only. */

const AI_SUGGESTIONS = [
  "What's the difference between SAML and OIDC?",
  "When should I use SWA instead of SAML in Okta?",
  "What are Auth0 Actions and how do they differ from Rules?",
  "Explain the Okta workforce SSO flow.",
];

/* Minimal, safe formatter: escape HTML, then render links, bold, code, and bullet lists. */
function formatAnswer(text) {
  const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  const inline = (s) =>
    esc(s)
      .replace(/(https?:\/\/[^\s<)]+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>')
      .replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
      .replace(/`([^`]+)`/g, "<code>$1</code>");

  const lines = String(text).split("\n");
  let html = "";
  let inList = false;
  const closeList = () => { if (inList) { html += "</ul>"; inList = false; } };
  for (const raw of lines) {
    const line = raw.trim();
    if (!line) { closeList(); continue; }
    if (/^[-*•]\s+/.test(line)) {
      if (!inList) { html += "<ul>"; inList = true; }
      html += "<li>" + inline(line.replace(/^[-*•]\s+/, "")) + "</li>";
    } else {
      closeList();
      html += "<p>" + inline(line) + "</p>";
    }
  }
  closeList();
  return html;
}

function AiMessage({ m }) {
  if (m.role === "user") return <div className="ai-msg user">{m.text}</div>;
  return <div className={"ai-msg bot" + (m.error ? " err" : "")}
    dangerouslySetInnerHTML={{ __html: formatAnswer(m.text) }} />;
}

function Assistant() {
  const store = useStore();
  const firstName = ((store && store.session && (store.session.name || store.session.email)) || "").trim().split(/\s+/)[0];
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState([]);
  const [input, setInput] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const logRef = React.useRef(null);
  const inputRef = React.useRef(null);

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

  React.useEffect(() => {
    if (open && inputRef.current) inputRef.current.focus();
  }, [open]);

  const send = async (text) => {
    const q = (text != null ? text : input).trim();
    if (!q || busy) return;
    setInput("");
    const history = messages.map((m) => ({ role: m.role, text: m.text }));
    const next = [...messages, { role: "user", text: q }];
    setMessages(next);
    setBusy(true);
    try {
      const base = (window.VERIDYNE_CONFIG && window.VERIDYNE_CONFIG.apiBase) || "";
      const r = await fetch(base + "/api/ask", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ question: q, history }),
      });
      const data = await r.json().catch(() => ({}));
      if (!r.ok) throw new Error(data.error || "Something went wrong.");
      setMessages([...next, { role: "assistant", text: data.answer || "No answer." }]);
    } catch (e) {
      setMessages([...next, { role: "assistant", text: e.message || "The assistant is unavailable right now.", error: true }]);
    } finally {
      setBusy(false);
    }
  };

  const onKey = (e) => {
    if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); }
  };

  if (!open) {
    return (
      <button className="ai-fab anim-fade-in" onClick={() => setOpen(true)} aria-label="Ask Veri, your Academy assistant">
        <Icon name="zap" size={17} />
        <span className="ai-fab-label">Ask Veri</span>
      </button>
    );
  }

  return (
    <div className="ai-panel glass-raised anim-fade-up" role="dialog" aria-label="Academy assistant">
      <div className="ai-head">
        <div style={{ width: 34, height: 34, borderRadius: 11, display: "grid", placeItems: "center", background: "var(--ember-soft)", border: "1px solid rgba(180,99,42,0.4)", color: "var(--ember-bright)", flexShrink: 0 }}>
          <Icon name="zap" size={18} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="ai-title">Veri</div>
          <div className="ai-sub">Your Academy Assistant</div>
        </div>
        <button className="btn btn-ghost btn-sm" onClick={() => setOpen(false)} aria-label="Close assistant">
          <Icon name="x" size={18} />
        </button>
      </div>

      <div className="ai-log" ref={logRef}>
        {messages.length === 0 ? (
          <div className="ai-empty">
            <Icon name="zap" size={26} style={{ color: "var(--ember-bright)", marginBottom: 10 }} />
            <p style={{ fontWeight: 600, color: "var(--bone)", fontSize: "1.05em", marginBottom: 4 }}>
              Hello{firstName ? ", " + firstName : ""} 👋
            </p>
            <p style={{ marginBottom: 12 }}>I'm Veri. Ask me anything about the Okta or Auth0 material.</p>
            <div>
              {AI_SUGGESTIONS.map((s, i) => (
                <button key={i} className="ai-chip" onClick={() => send(s)}>{s}</button>
              ))}
            </div>
          </div>
        ) : (
          messages.map((m, i) => <AiMessage key={i} m={m} />)
        )}
        {busy ? (
          <div className="ai-msg bot ai-dots" aria-label="Thinking"><span></span><span></span><span></span></div>
        ) : null}
      </div>

      <div className="ai-form">
        <textarea ref={inputRef} className="ai-input" rows={1} value={input} placeholder="Ask a question…"
          onChange={(e) => setInput(e.target.value)} onKeyDown={onKey} disabled={busy} />
        <button className="ai-send" onClick={() => send()} disabled={busy || !input.trim()} aria-label="Send">
          <Icon name="arrowRight" size={18} />
        </button>
      </div>
      <div className="ai-disclaimer">AI can make mistakes — verify against the linked official docs.</div>
    </div>
  );
}

window.Assistant = Assistant;
