// Chatbot — wired to window.claude.complete with LIVE API data as context.

// React hooks (Babel-standalone — make hooks visible per-script)
const { useState, useEffect, useRef, useMemo, useCallback, createContext, useContext } = React;

const cbStyles = {
  fab: {
    position: "fixed", bottom: 20, right: 20, zIndex: 40,
    display: "flex", alignItems: "center", gap: 8,
    height: 40, padding: "0 16px", borderRadius: 999,
    background: "linear-gradient(135deg, #E91E63 0%, #FF6B35 100%)",
    color: "#fff", border: "none", cursor: "pointer",
    fontFamily: "var(--vk-font-sans)", fontSize: 13, fontWeight: 600,
    boxShadow: "0 0 0 1px rgba(0,0,0,0.4)",
  },
  scrim: { position: "fixed", inset: 0, background: "transparent", zIndex: 90 },
  panel: {
    position: "fixed", bottom: 72, right: 20, width: 400, height: "60vh", maxHeight: 560,
    background: "var(--vk-surface-1)",
    boxShadow: "0 0 0 1px rgba(233,30,99,0.30)",
    borderRadius: 8, zIndex: 95,
    display: "flex", flexDirection: "column",
    animation: "vkfade 120ms ease-out",
  },
  header: { padding: 14, borderBottom: "1px solid var(--vk-border-subtle)", display: "flex", alignItems: "center", gap: 10 },
  body: { flex: 1, overflowY: "auto", padding: 14, display: "flex", flexDirection: "column", gap: 10 },
  msgUser: { alignSelf: "flex-end", maxWidth: "80%", padding: "8px 12px", borderRadius: 12, background: "var(--vk-gradient)", color: "#fff", fontSize: 13, lineHeight: 1.5 },
  msgBot:  { alignSelf: "flex-start", maxWidth: "85%", padding: "8px 12px", borderRadius: 12, background: "var(--vk-surface-2)", color: "var(--vk-text-primary)", fontSize: 13, lineHeight: 1.5, whiteSpace: "pre-wrap" },
  msgPending: { alignSelf: "flex-start", maxWidth: "85%", padding: "8px 12px", borderRadius: 12, background: "var(--vk-surface-2)", color: "var(--vk-text-tertiary)", fontSize: 13, fontStyle: "italic" },
  composer: { padding: 12, borderTop: "1px solid var(--vk-border-subtle)", display: "flex", gap: 8, alignItems: "center" },
  suggestion: {
    display: "inline-flex", alignItems: "center",
    fontSize: 11, padding: "4px 8px", borderRadius: 999,
    background: "var(--vk-surface-2)", color: "var(--vk-text-secondary)",
    cursor: "pointer", boxShadow: "var(--vk-ring-ambient)",
  },
};

async function buildDataContext(city, runId) {
  // Pull live data from the API (cached). Fall back gracefully on error.
  try {
    const [ents, rels, briefs] = await Promise.all([
      window.VK_API.fetchPath("/entities", { city, run_id: runId, limit: 500 }),
      window.VK_API.fetchPath("/relationships", { city, run_id: runId }),
      window.VK_API.fetchPath("/briefs", { city, limit: 1 }),
    ]);
    const entRows = Array.isArray(ents) ? ents : [];
    const relRows = Array.isArray(rels) ? rels : [];
    const brief = Array.isArray(briefs) && briefs[0];

    const entLine = (e) => {
      const flags = ["partner","supporter","competitor","blocker","investment","support","recruiting"]
        .filter((f) => e[f + "_candidate"] === "yes");
      return `- ${e.canonical_name} [${e.entity_type}${e.sector_or_focus ? "/"+e.sector_or_focus : ""}] infl=${e.influence_score} rel=${e.relevance_score} risk=${e.risk_score} conf=${e.confidence_score}${flags.length ? " flags=["+flags.join(",")+"]" : ""}${e.role_in_ecosystem ? "  // "+e.role_in_ecosystem : ""}`;
    };
    const relLine = (r) => `- ${r.source_entity_name} —${r.relationship_type.toLowerCase()}→ ${r.target_entity_name} (${r.confidence})`;
    return [
      `# VK Quantum data — ${city}` + (runId ? ` · run ${runId}` : ""),
      ``,
      `## Entities (${entRows.length})`,
      entRows.slice(0, 200).map(entLine).join("\n"),
      ``,
      `## Relationships (${relRows.length})`,
      relRows.slice(0, 250).map(relLine).join("\n"),
      ``,
      brief ? `## Latest brief executive summary\n${brief.executive_summary || brief.brief_title || ""}` : ``,
    ].join("\n");
  } catch (err) {
    return "# No data available — API unreachable.";
  }
}

const SUGGESTIONS = [
  "Who are the top 3 investors by influence?",
  "Which companies were flagged as investment targets?",
  "What's flagged as a blocker and why?",
];

function Chatbot() {
  const app = useAppState();
  const [open, setOpen] = useState(false);
  const [text, setText] = useState("");
  const [pending, setPending] = useState(false);
  const [msgs, setMsgs] = useState([
    { role: "bot", text: "Ask me anything about this ecosystem. I have live entities, relationships, and the latest brief for the selected city/run loaded." },
  ]);
  const endRef = useRef(null);

  function scrollToBottom() {
    setTimeout(() => endRef.current?.parentElement?.scrollTo({ top: 99999, behavior: "smooth" }), 50);
  }

  async function send(prompt) {
    const q = (prompt ?? text).trim();
    if (!q || pending) return;
    setMsgs((m) => [...m, { role: "user", text: q }]);
    setText("");
    setPending(true);
    scrollToBottom();

    const context = await buildDataContext(app.city, app.runId);
    const sys = [
      "You are the VK Quantum operator assistant.",
      "Answer ONLY using the structured data below — do not invent entities, scores, or relationships.",
      "Be terse and factual. Use entity names exactly as written. Show scores as plain integers.",
      "If the data does not support an answer, say so plainly. Never speculate.",
      "Sentence case. No emoji. No greetings. Cite scores when relevant.",
      "",
      "---",
      context,
    ].join("\n");

    try {
      const reply = await window.claude.complete({
        messages: [{ role: "user", content: sys + "\n\n---\nQuestion: " + q }],
      });
      setMsgs((m) => [...m, { role: "bot", text: reply }]);
    } catch (err) {
      setMsgs((m) => [...m, { role: "bot", text: "Couldn't reach the model. " + (err?.message || "") }]);
    } finally {
      setPending(false);
      scrollToBottom();
    }
  }

  return (
    <>
      {!open && (
        <button style={cbStyles.fab} onClick={() => setOpen(true)}>
          <Icon name="MessageCircle" size={16} /> Ask the data
        </button>
      )}
      {open && (
        <>
          <div style={cbStyles.scrim} onClick={() => setOpen(false)}></div>
          <div style={cbStyles.panel} onClick={(e) => e.stopPropagation()}>
            <div style={cbStyles.header}>
              <Icon name="MessageCircle" size={16} color="var(--vk-orange)" />
              <span style={{ fontSize: 13, fontWeight: 500 }}>Ask the data</span>
              <span style={{ fontSize: 11, color: "var(--vk-text-tertiary)" }}>{app.city} · {app.runLabel}</span>
              <div style={{ flex: 1 }}></div>
              <button className="vk-btn vk-btn--ghost" onClick={() => setOpen(false)} style={{ width: 28, padding: 0, justifyContent: "center" }}>
                <Icon name="X" size={14} />
              </button>
            </div>
            <div style={cbStyles.body}>
              {msgs.map((m, i) => (
                <div key={i} style={m.role === "user" ? cbStyles.msgUser : cbStyles.msgBot}>{m.text}</div>
              ))}
              {pending && <div style={cbStyles.msgPending}>thinking…</div>}
              {msgs.length === 1 && !pending && (
                <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 4 }}>
                  {SUGGESTIONS.map((s) => (
                    <span key={s} style={cbStyles.suggestion} onClick={() => send(s)}>{s}</span>
                  ))}
                </div>
              )}
              <div ref={endRef}></div>
            </div>
            <div style={cbStyles.composer}>
              <input className="vk-input" style={{ flex: 1 }}
                placeholder="Ask about an entity, score, or relationship…"
                value={text} disabled={pending}
                onChange={(e) => setText(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter") send(); }}
              />
              <button className="vk-btn vk-btn--primary" onClick={() => send()} disabled={pending} style={{ height: 28, padding: "0 12px" }}>
                <Icon name="Send" size={14} />
              </button>
            </div>
          </div>
        </>
      )}
    </>
  );
}

Object.assign(window, { Chatbot });
