// "Ask Solo AI" — floating Q&A widget mounted persistently inside both
// AdminShell (admin-shell.jsx) and ResellerShell (reseller-shell.jsx), so
// it appears on every page inside each shell rather than being wired in
// page-by-page.
//
// Backend: routes/admin-ai.ts (POST /api/admin/ai/ask, requireAdmin only —
// any admin/super_admin) and routes/portal-ai.ts (POST /api/portal/ai/ask,
// loadResellerContext only — any company_admin/member), both backed by the
// shared lib/aiAssistant.ts. Admin sees every customer's assets; portal
// users are scoped to their own company's assets only (enforced server-
// side — this widget never sends a company id itself, same pattern as
// reseller-device-linking.jsx).
//
// mode="admin"  -> light theme (matches AdminShell), posts to /api/admin/ai/ask
// mode="portal" -> light theme (matches ResellerShell's white theme), posts to /api/portal/ai/ask
//
// Kept as a single self-contained component (own fetch, own local
// question/answer history) so neither shell file needs more than a one-line
// <AskSoloAiWidget mode="..." /> addition.

const { useState, useRef, useEffect } = React;

const ASK_SOLO_AI_THEME = {
  admin: {
    askUrl: "/api/admin/ai/ask",
    panelBg: "#fff",
    panelText: "#000",
    border: "rgba(0,0,0,0.18)",
    subtleBorder: "rgba(0,0,0,0.12)",
    accent: "#000",
    accentText: "#fff",
    mutedText: "rgba(0,0,0,0.5)",
    bubbleBg: "rgba(0,0,0,0.04)",
    inputBg: "rgba(0,0,0,0.03)",
    inputBorder: "rgba(0,0,0,0.25)",
    shadow: "0 12px 40px rgba(0,0,0,0.25)",
  },
  // Uses --pt-* CSS variables (not literal hex/rgba like `admin` above)
  // because this widget renders as a DOM descendant of ResellerShell's
  // (or a standalone pre-auth page's) data-portal-theme={theme}
  // subtree — reading the live tokens makes it automatically flip with
  // the reseller/customer portal's light/dark toggle, no extra wiring
  // needed. See portal-theme.jsx for the token definitions.
  portal: {
    askUrl: "/api/portal/ai/ask",
    panelBg: "var(--pt-bg)",
    panelText: "var(--pt-fg)",
    border: "var(--pt-border-subtle)",
    subtleBorder: "var(--pt-border-2)",
    accent: "var(--pt-accent-bg)",
    accentText: "var(--pt-accent-fg)",
    mutedText: "var(--pt-fg-dim)",
    bubbleBg: "var(--pt-surface-3)",
    inputBg: "var(--pt-surface-2)",
    inputBorder: "var(--pt-border-strong)",
    shadow: "0 12px 40px var(--pt-border-strong)",
  },
};

function AskSoloAiWidget({ mode }) {
  const theme = ASK_SOLO_AI_THEME[mode] || ASK_SOLO_AI_THEME.admin;
  const [open, setOpen] = useState(false);
  const [question, setQuestion] = useState("");
  const [messages, setMessages] = useState([]); // [{ question, answer, error }]
  const [busy, setBusy] = useState(false);
  const [toggleHover, setToggleHover] = useState(false);
  const scrollRef = useRef(null);

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

  const submit = async (e) => {
    e.preventDefault();
    const q = question.trim();
    if (!q || busy) return;
    setBusy(true);
    setQuestion("");
    setMessages((prev) => [...prev, { question: q, answer: null, error: null }]);
    try {
      const res = await fetch(theme.askUrl, {
        method: "POST", credentials: "same-origin",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ question: q }),
      });
      const data = await res.json().catch(() => ({}));
      setMessages((prev) => {
        const next = [...prev];
        const last = next[next.length - 1];
        if (!res.ok) {
          next[next.length - 1] = { ...last, error: data.error || "Something went wrong. Please try again." };
        } else {
          next[next.length - 1] = { ...last, answer: data.answer || "" };
        }
        return next;
      });
    } catch {
      setMessages((prev) => {
        const next = [...prev];
        next[next.length - 1] = { ...next[next.length - 1], error: "Couldn't reach the server. Check your connection and try again." };
        return next;
      });
    }
    setBusy(false);
  };

  return (
    <div style={{ position: "fixed", right: 28, bottom: 28, zIndex: 200 }} data-testid="ask-solo-ai-widget">
      {open && (
        <div style={{
          width: 360, maxWidth: "calc(100vw - 56px)", height: 460, maxHeight: "calc(100vh - 140px)",
          background: theme.panelBg, color: theme.panelText,
          border: `1px solid ${theme.border}`, boxShadow: theme.shadow,
          display: "flex", flexDirection: "column", marginBottom: 14,
        }}>
          <div style={{
            display: "flex", alignItems: "center", justifyContent: "space-between",
            padding: "14px 16px", borderBottom: `1px solid ${theme.subtleBorder}`,
          }}>
            <div>
              <div style={{
                fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 14,
                textTransform: "uppercase", letterSpacing: "0.06em",
              }}>Ask Solo AI</div>
              <div style={{
                fontFamily: "var(--font-body)", fontSize: 10, letterSpacing: "0.18em",
                textTransform: "uppercase", color: theme.mutedText, marginTop: 2,
              }}>{mode === "admin" ? "All customer assets" : "Your assets"}</div>
            </div>
            <button
              type="button" onClick={() => setOpen(false)} data-testid="ask-solo-ai-close"
              style={{
                background: "none", border: "none", cursor: "pointer",
                color: theme.mutedText, fontSize: 18, lineHeight: 1, padding: 4,
              }}
            >×</button>
          </div>

          <div ref={scrollRef} style={{ flex: 1, overflowY: "auto", padding: "14px 16px" }}>
            {messages.length === 0 && (
              <div style={{
                fontFamily: "var(--font-body)", fontSize: 12.5, color: theme.mutedText, lineHeight: 1.6,
              }}>
                Ask anything about {mode === "admin" ? "any customer's" : "your company's"} assets — status,
                telemetry, tickets, or spec sheets. Mention a serial number to ask about a specific unit.
                {mode !== "admin" && " You'll only ever see your own company's assets."} This assistant
                can answer questions but can't make changes on your behalf.
              </div>
            )}
            {messages.map((m, i) => (
              <div key={i} style={{ marginBottom: 18 }}>
                <div style={{
                  fontFamily: "var(--font-body)", fontSize: 12.5, fontWeight: 600,
                  marginBottom: 6,
                }}>{m.question}</div>
                {m.error ? (
                  <div style={{
                    background: "rgba(190,40,40,0.1)", border: "1px solid rgba(190,40,40,0.4)",
                    color: "#c94b4b", padding: "8px 10px",
                    fontFamily: "var(--font-body)", fontSize: 12, lineHeight: 1.5,
                  }}>{m.error}</div>
                ) : m.answer !== null ? (
                  <div style={{
                    background: theme.bubbleBg, padding: "10px 12px",
                    fontFamily: "var(--font-body)", fontSize: 12.5, lineHeight: 1.6,
                    whiteSpace: "pre-wrap",
                  }}>{m.answer}</div>
                ) : (
                  <div style={{
                    fontFamily: "var(--font-body)", fontSize: 12, color: theme.mutedText,
                  }}>Thinking…</div>
                )}
              </div>
            ))}
          </div>

          <form onSubmit={submit} style={{
            display: "flex", gap: 8, padding: 12, borderTop: `1px solid ${theme.subtleBorder}`,
          }}>
            <input
              type="text" value={question} onChange={(e) => setQuestion(e.target.value)}
              placeholder="Ask a question…" disabled={busy} data-testid="ask-solo-ai-input"
              style={{
                flex: 1, boxSizing: "border-box",
                background: theme.inputBg, border: `1px solid ${theme.inputBorder}`,
                color: theme.panelText, fontFamily: "var(--font-body)", fontSize: 13,
                padding: "9px 10px", outline: "none",
              }}
            />
            <button
              type="submit" disabled={busy || !question.trim()} data-testid="ask-solo-ai-submit"
              style={{
                background: theme.accent, color: theme.accentText, border: "none",
                padding: "9px 16px", cursor: busy || !question.trim() ? "not-allowed" : "pointer",
                opacity: busy || !question.trim() ? 0.5 : 1,
                fontFamily: "var(--font-body)", fontSize: 11.5, fontWeight: 600,
                letterSpacing: "0.08em", textTransform: "uppercase",
              }}
            >Ask</button>
          </form>
        </div>
      )}

      <button
        type="button" onClick={() => setOpen((v) => !v)} data-testid="ask-solo-ai-toggle"
        onMouseEnter={() => setToggleHover(true)} onMouseLeave={() => setToggleHover(false)}
        style={{
          background: theme.accent, color: theme.accentText, border: "none",
          padding: "13px 22px", cursor: "pointer", boxShadow: theme.shadow,
          fontFamily: "var(--font-body)", fontSize: 12, fontWeight: 600,
          letterSpacing: "0.1em", textTransform: "uppercase",
          display: "flex", alignItems: "center", gap: 9,
          transform: toggleHover ? "translateY(-2px)" : "translateY(0)",
          transition: "transform 160ms ease",
        }}
      >
        {typeof IconPulse === "function" && <IconPulse />}
        {open ? "Close" : "Ask Solo AI"}
      </button>
    </div>
  );
}

Object.assign(window, { AskSoloAiWidget });
