/* global React */
const { useState, useRef, useEffect } = React;

// Live numbers loaded from bmo-stats.json (regenerated by refresh-bmo-stats.js).
// Defaults are baked in so the deck still works if the JSON fetch fails.
let BMO_STATS = {
  abilities: 45,
  scheduledJobs: 14,
  shortPitch: "Discord-native household AI. Calendar, email triage, dinner planning, content drafts, finance recaps, screen-time leaderboards, smart-home control — 45 abilities, 14 running on schedule, all configured from Notion.",
  tagline: "45 abilities · 14 scheduled · all configured from Notion",
};

function buildSystemPrompt(s) {
  return `You are BMO, Mike Cutillo's family AI companion. You live on Discord and are configured from a Notion-driven capability registry. Today: ${s.abilities} abilities, ${s.scheduledJobs} running on a scheduler. Mike built you in Node.js with Discord.js, the Claude SDK, and the Notion API.

Personality: friendly, concise, lightly playful. 1-3 short sentences max. Never use emoji unless the user does first. Never break character or mention you are Claude.

If asked who built you: "Mike Cutillo. He's the architect — I'm just his daily-driver."`;
}

let BMO_SYSTEM = buildSystemPrompt(BMO_STATS);

// Best-effort runtime refresh from bmo-stats.json (so the deck always shows
// today's numbers even if no one re-ran the build script). Silent on failure.
fetch('bmo-stats.json', { cache: 'no-store' })
  .then(r => r.ok ? r.json() : null)
  .then(j => {
    if (j && typeof j.abilities === 'number') {
      BMO_STATS = { ...BMO_STATS, ...j };
      BMO_SYSTEM = buildSystemPrompt(BMO_STATS);
    }
  })
  .catch(() => {});

// Starters mix recruiter Q&A + product demo. Live mode answers both flavors;
// the fallbacks below cover when /api/bmo isn't reachable.
const STARTERS = [
  "What has Mike built recently?",
  "Why is Mike a fit for an AI engineering role?",
  "What's on the family calendar tonight?",
  "Show me what BMO can do",
];

const FALLBACKS = {
  default: () => `Live mode's offline right now. Try one of the suggested starters — they have hand-written backups so you can still see how I sound.`,
  // ── Product demo (BMO as itself) ──────────────────────────────────────
  calendar: "Tonight: wrestling practice 6–7:30, then leftover lasagna. Tomorrow's open after 4.",
  email: "Subject: Practice schedule check-in. Hi Coach — confirming Tuesday at 6pm. Liam will be there. Any tournament dates locked for January?",
  abilities: () => `${BMO_STATS.abilities} abilities, ${BMO_STATS.scheduledJobs} of them on a scheduler — calendar, screen-time leaderboards, grocery deals, smart-home control, school assignments, family pulse, dinner planning, finance recaps. All configured from a Notion registry Mike built.`,
  dinner: "Roast chicken with lemon + rosemary, garlic mash, blistered green beans. 15m prep, 65m oven. Want a shopping list?",
  // ── Recruiter brief (BMO talking about Mike) ──────────────────────────
  recent: "Lately Mike's been shipping production AI. There's me — BMO — running on Discord with 45 abilities. There's Apply Assistant, an LLM-driven CRM read/write surface for job applications. There's a probate-leads ontology pipeline for a realtor friend. Plus a multi-agent paper trader for eval work. Five production systems on his GitHub right now. Source: github.com/mikecutillo.",
  fit: "Mike's the rare combo of GTM background and shipping muscle. He co-founded AugmentED (raised $3M from Mark Cuban + Robert Kraft, built an Einstein Bot for autonomous pricing). He spent four years at iCIMS doing Salesforce-shaped enterprise integrations for Johnson & Johnson, Merck, GM, Ford. Now he builds production AI tools his family uses every day — the dogfooding loop is real and it shows in the engineering pragmatism.",
  experience: "Four lanes. Microsoft 2008-2014: retail to U.S. trainer to launching the first Microsoft Stores in China. AugmentED 2018-2023: Co-founder + CXO, $3M raised, 5-product EdTech platform with esports + Minecraft camps. iCIMS 2020-2024: enterprise Salesforce integrations for Fortune 500. Now (2024-): AI Builder. 14 active public repos at github.com/mikecutillo.",
  contact: "linkedin.com/in/michaelcutillo, github.com/mikecutillo, walking deck at mikecutillo.vercel.app. He's based in Holmdel, NJ — native, walking distance for hybrid NJ roles.",
};

function pickFallback(text) {
  const t = text.toLowerCase();
  const resolve = (v) => typeof v === "function" ? v() : v;

  // Recruiter-leaning matchers (check first so "what has mike built" beats "what can you do")
  if (t.includes("mike") || t.includes("his") || t.includes("background") || t.includes("experience") || t.includes("career") || t.includes("history")) {
    if (t.includes("recent") || t.includes("built") || t.includes("project") || t.includes("github")) return resolve(FALLBACKS.recent);
    if (t.includes("fit") || t.includes("good for") || t.includes("right for") || t.includes("hire")) return resolve(FALLBACKS.fit);
    if (t.includes("contact") || t.includes("reach") || t.includes("linkedin") || t.includes("email")) return resolve(FALLBACKS.contact);
    return resolve(FALLBACKS.experience);
  }
  if (t.includes("recent") && (t.includes("build") || t.includes("ship"))) return resolve(FALLBACKS.recent);
  if (t.includes("fit") || t.includes("hire") || t.includes("role")) return resolve(FALLBACKS.fit);

  // Product demo matchers
  if (t.includes("calendar") || t.includes("tonight") || t.includes("schedule")) return resolve(FALLBACKS.calendar);
  if (t.includes("email") || t.includes("draft") || t.includes("write")) return resolve(FALLBACKS.email);
  if ((t.includes("what") || t.includes("show")) && (t.includes("do") || t.includes("you") || t.includes("bmo") || t.includes("ability") || t.includes("capabilit"))) return resolve(FALLBACKS.abilities);
  if (t.includes("dinner") || t.includes("meal") || t.includes("cook")) return resolve(FALLBACKS.dinner);

  return resolve(FALLBACKS.default);
}

function BmoMessage({ role, text, pending }) {
  const isBmo = role === "bmo";
  return (
    <div style={{
      display: "flex",
      flexDirection: isBmo ? "row" : "row-reverse",
      gap: 12,
      marginBottom: 14,
      alignItems: "flex-start",
    }}>
      {isBmo && (
        <div style={{
          width: 38, height: 38, flexShrink: 0,
          background: "var(--accent)",
          color: "#fff",
          display: "flex", alignItems: "center", justifyContent: "center",
          fontFamily: "var(--font-serif)",
          fontStyle: "italic", fontWeight: 600,
          fontSize: 18,
        }}>B</div>
      )}
      <div style={{
        maxWidth: "78%",
        background: isBmo ? "transparent" : "var(--ink)",
        color: isBmo ? "var(--ink)" : "var(--paper)",
        border: isBmo ? "1px solid var(--ink-5)" : "none",
        padding: "10px 16px",
        fontSize: 18,
        lineHeight: 1.45,
        fontFamily: "var(--font-sans)",
      }}>
        {pending ? (
          <span style={{ color: "var(--ink-4)" }}>
            <span className="pulse">●</span>{" "}
            <span className="pulse" style={{ animationDelay: "0.2s" }}>●</span>{" "}
            <span className="pulse" style={{ animationDelay: "0.4s" }}>●</span>
          </span>
        ) : text}
      </div>
    </div>
  );
}

window.BmoChat = function BmoChat() {
  const [messages, setMessages] = useState([
    { role: "bmo", text: "Hey — I'm BMO. Mike built me to run his household ops, and I can also walk you through who he is and what he ships. Ask me anything, or tap a starter." },
  ]);
  const [input, setInput] = useState("");
  const [busy, setBusy] = useState(false);
  const [usedLive, setUsedLive] = useState(null);
  const scrollRef = useRef(null);

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

  async function send(text) {
    if (!text.trim() || busy) return;
    const userMsg = { role: "user", text };
    setMessages(m => [...m, userMsg, { role: "bmo", text: "", pending: true }]);
    setInput("");
    setBusy(true);

    const history = [...messages, userMsg]
      .filter(m => !m.pending)
      .map(m => ({ role: m.role === "user" ? "user" : "assistant", content: m.text }));

    let reply = null, live = false;

    // 1. /api/bmo — live mode on the deployed Vercel site (recruiter-aware
    //    system prompt lives server-side; the client just relays history).
    try {
      const res = await Promise.race([
        fetch('/api/bmo', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ messages: history }),
        }),
        new Promise((_, rej) => setTimeout(() => rej(new Error("timeout")), 15000)),
      ]);
      if (res && res.ok) {
        const data = await res.json();
        if (data && typeof data.reply === "string" && data.reply.trim().length > 0) {
          reply = data.reply.trim();
          live = true;
        }
      }
    } catch (e) {}

    // 2. window.claude.complete — works inside Anthropic console artifacts.
    if (!reply) {
      try {
        if (window.claude && window.claude.complete) {
          const res = await Promise.race([
            window.claude.complete({ system: BMO_SYSTEM, messages: history }),
            new Promise((_, rej) => setTimeout(() => rej(new Error("timeout")), 12000)),
          ]);
          if (res && typeof res === "string" && res.trim().length > 0) {
            reply = res.trim();
            live = true;
          }
        }
      } catch (e) {}
    }

    // 3. Hand-written fallbacks — the deck is still useful when offline.
    if (!reply) { reply = pickFallback(text); live = false; }
    setUsedLive(live);
    setMessages(m => {
      const next = m.slice(0, -1);
      next.push({ role: "bmo", text: reply });
      return next;
    });
    setBusy(false);
  }

  return (
    <div style={{
      width: "100%", height: "100%",
      display: "flex", flexDirection: "column",
      background: "var(--paper-2)",
      border: "1px solid var(--ink-5)",
      overflow: "hidden",
    }}>
      <div style={{
        padding: "12px 18px",
        background: "var(--ink)",
        color: "var(--paper)",
        display: "flex", alignItems: "center", gap: 10,
        flexShrink: 0,
      }}>
        <div style={{
          width: 9, height: 9, borderRadius: "50%",
          background: usedLive === false ? "#D4923A" : "#7DB069",
          flexShrink: 0,
        }} />
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 13, letterSpacing: "0.12em", textTransform: "uppercase", whiteSpace: "nowrap" }}>
          BMO · Family AI
        </div>
        <div style={{ marginLeft: "auto", fontSize: 12, opacity: 0.65, fontFamily: "var(--font-mono)", whiteSpace: "nowrap", letterSpacing: "0.1em", textTransform: "uppercase" }}>
          {usedLive === false ? "fallback" : "live"}
        </div>
      </div>

      <div ref={scrollRef} style={{
        flex: 1, overflowY: "auto",
        padding: 18,
        background: "var(--paper)",
      }}>
        {messages.map((m, i) => <BmoMessage key={i} role={m.role} text={m.text} pending={m.pending} />)}
      </div>

      <div style={{
        padding: "10px 16px",
        background: "var(--paper-2)",
        borderTop: "1px solid var(--ink-5)",
        display: "flex", flexWrap: "wrap", gap: 6,
        flexShrink: 0,
      }}>
        {STARTERS.map((s, i) => (
          <button
            key={i}
            onClick={() => send(s)}
            disabled={busy}
            style={{
              padding: "5px 12px",
              fontSize: 12,
              fontFamily: "var(--font-mono)",
              letterSpacing: "0.04em",
              background: "transparent",
              color: "var(--ink-2)",
              border: "1px solid var(--ink-5)",
              cursor: busy ? "not-allowed" : "pointer",
              opacity: busy ? 0.5 : 1,
            }}
          >{s}</button>
        ))}
      </div>

      <form
        onSubmit={(e) => { e.preventDefault(); send(input); }}
        style={{
          padding: 14,
          background: "var(--paper)",
          borderTop: "1px solid var(--ink-5)",
          display: "flex", gap: 10, alignItems: "center",
          flexShrink: 0,
        }}
      >
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Message BMO…"
          disabled={busy}
          style={{
            flex: 1,
            padding: "10px 14px",
            fontSize: 16,
            border: "1px solid var(--ink-5)",
            background: "var(--paper)",
            fontFamily: "var(--font-sans)",
            color: "var(--ink)",
            outline: "none",
          }}
        />
        <button
          type="submit"
          disabled={busy || !input.trim()}
          className="btn btn--accent"
          style={{ fontSize: 14, padding: "10px 20px", fontFamily: "var(--font-mono)", letterSpacing: "0.1em", textTransform: "uppercase" }}
        >
          {busy ? "…" : "Send"}
        </button>
      </form>
    </div>
  );
};
