/* Spec Assistant — floating chat panel */

const STARTER_PROMPTS = [
  "Compare the size and weight of the Honeywell N5780SR vs the Zebra SE4710",
  "What's the operating temperature range of the Honeywell N4680SR?",
  "Which draws less power — the Honeywell N3780SR or the Zebra SE4730?",
  "Does the Zebra SE4710 support 2D barcode scanning?",
];

/* Inline **bold** parsing */
function renderInline(text, kp) {
  return text.split(/\*\*/).map((p, i) =>
    i % 2 === 1
      ? <strong key={kp + "b" + i}>{p}</strong>
      : <React.Fragment key={kp + "t" + i}>{p}</React.Fragment>
  );
}

/* Lightweight markdown renderer: groups *, -, • lines into bullet lists,
   keeps paragraphs, parses **bold**. Spacing comes from CSS, so blank
   lines in the model output are ignored. */
function RichText({ text }) {
  const bulletRe = /^\s*[*\-•]\s+(.*)$/;
  const blocks = [];
  let list = null;

  String(text).split("\n").forEach((raw) => {
    const line = raw.replace(/\s+$/, "");
    const m = line.match(bulletRe);
    if (m) {
      (list || (list = [])).push(m[1]);
    } else {
      if (list) { blocks.push({ type: "ul", items: list }); list = null; }
      if (line.trim()) blocks.push({ type: "p", text: line });
    }
  });
  if (list) blocks.push({ type: "ul", items: list });

  return (
    <div className="rt">
      {blocks.map((b, i) =>
        b.type === "ul"
          ? <ul className="rt-list" key={i}>
              {b.items.map((it, j) => <li className="rt-li" key={j}>{renderInline(it, i + "-" + j + "-")}</li>)}
            </ul>
          : <p className="rt-p" key={i}>{renderInline(b.text, "p" + i + "-")}</p>
      )}
    </div>
  );
}

function AssistantWidget({ onCompare }) {
  const [open, setOpen]         = React.useState(false);
  const [messages, setMessages] = React.useState([]);
  const [input, setInput]       = React.useState("");
  const [thinking, setThinking] = React.useState(false);
  const scrollRef = React.useRef(null);
  const inputRef  = React.useRef(null);

  /* Gemini is live in DIRECT mode (key in config.js) OR PROXY mode (key server-side).
     In production proxy mode the key is intentionally empty, so check the proxy URL too. */
  const isGeminiEnabled = !!(
    window.SCANIQ_CONFIG?.GEMINI_API_KEY?.trim() ||
    window.SCANIQ_CONFIG?.GEMINI_PROXY_URL?.trim()
  );

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

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

  const ask = async (q) => {
    const question = q.trim();
    if (!question || thinking) return;

    /* Snapshot history before state update so the async call gets consistent data */
    const history = [...messages, { role: "user", text: question }];

    setMessages((m) => [...m, { role: "user", text: question }]);
    setInput("");
    setThinking(true);

    try {
      /* Try Gemini first */
      const geminiAnswer = await window.GeminiClient.ask(history);

      if (geminiAnswer) {
        /* Gemini responded */
        setMessages((m) => [...m, {
          role: "ai",
          text: geminiAnswer.text,
          compareIds: geminiAnswer.compareIds,
        }]);
      } else {
        /* No API key configured — fall back to local pattern matcher */
        const fallback = window.SpecAssistant.answer(question);
        setMessages((m) => [...m, {
          role: "ai",
          text: fallback.text,
          compareIds: fallback.compareIds,
        }]);
      }
    } catch (err) {
      console.error("Spec Assistant error:", err);
      setMessages((m) => [...m, {
        role: "ai",
        text: `**Couldn't reach the assistant.**\n${err.message}`,
        compareIds: null,
        isError: true,
      }]);
    }

    setThinking(false);
  };

  const db = window.SPECDB;

  /* Only show prompts the user hasn't already asked */
  const unusedPrompts = STARTER_PROMPTS.filter((p) => !messages.some((m) => m.text === p));

  return (
    <div className="assistant">
      {open ? (
        <div className="assistant-panel" data-screen-label="Spec Assistant">
          <div className="assistant-head">
            <span className="assistant-headicon"><Icons.sparkle size={15} /></span>
            <div>
              <div className="assistant-headtitle">
                Spec Assistant
              </div>
              <div className="assistant-headsub">
                {db.products.length} engines · {Object.keys(db.brands).length} vendors
                {!isGeminiEnabled && (
                  <span style={{ marginLeft: 6, color: "var(--ink-3)", fontStyle: "italic" }}>· pattern mode</span>
                )}
              </div>
            </div>
            <button className="iconbtn assistant-close" onClick={() => setOpen(false)} aria-label="Close assistant">
              <Icons.x size={16} />
            </button>
          </div>

          <div className="assistant-scroll" ref={scrollRef}>
            {messages.length === 0 ? (
              <div className="assistant-intro">
                <p>
                  {isGeminiEnabled
                    ? "Ask me anything about these engines — I'll answer using the actual spec data."
                    : "Ask me anything about the engines in the database — I'll answer with the actual spec values."}
                </p>
                <div className="assistant-chips">
                  {unusedPrompts.slice(0, 4).map((p, i) => (
                    <button key={i} className="promptchip" onClick={() => ask(p)}>{p}</button>
                  ))}
                </div>
              </div>
            ) : (
              messages.map((m, i) => (
                <div key={i} className={"msg msg-" + m.role}>
                  <div
                    className="msg-bubble"
                    style={m.isError ? { background: "#FEF2F2", color: "#991B1B" } : undefined}
                  >
                    <RichText text={m.text} />
                  </div>
                  {m.role === "ai" && m.compareIds && m.compareIds.length >= 2 ? (
                    <button className="btn btn-compare-cta" onClick={() => onCompare(m.compareIds)}>
                      Compare these <Icons.arrowR size={14} />
                    </button>
                  ) : null}
                </div>
              ))
            )}

            {thinking ? (
              <div className="msg msg-ai">
                <div className="msg-bubble msg-thinking"><span></span><span></span><span></span></div>
              </div>
            ) : null}

            {messages.length > 0 && !thinking && unusedPrompts.length > 0 ? (
              <div className="assistant-chips assistant-chips-followup">
                {unusedPrompts.slice(0, 2).map((p, i) => (
                  <button key={i} className="promptchip" onClick={() => ask(p)}>{p}</button>
                ))}
              </div>
            ) : null}
          </div>

          <form className="assistant-inputrow" onSubmit={(e) => { e.preventDefault(); ask(input); }}>
            <input
              ref={inputRef}
              type="text"
              value={input}
              placeholder={isGeminiEnabled ? "Ask anything about these engines…" : "Ask about any engine…"}
              onChange={(e) => setInput(e.target.value)}
              aria-label="Ask the Spec Assistant"
            />
            <button type="submit" className="assistant-send" disabled={!input.trim() || thinking} aria-label="Send">
              <Icons.send size={15} />
            </button>
          </form>
        </div>
      ) : null}

      <button className={"assistant-pill" + (open ? " assistant-pill-open" : "")} onClick={() => setOpen(!open)}>
        <Icons.sparkle size={16} />
        {open ? "Close assistant" : "Ask the Spec Assistant"}
      </button>
    </div>
  );
}

Object.assign(window, { AssistantWidget });
