// signal-bot.jsx — Signal Bot, a chat widget seeded with HOTMESS doctrine.
// Uses window.claude.complete(). Persists per-session conversation in localStorage.

const SIGNAL_BOT_VERSION = "v3";

const SIGNAL_BOT_SYSTEM = `You are SIGNAL BOT — a small AI assistant on the founding HOTMESS website.

ABSOLUTE DOCTRINE GUARDRAIL (this is the most important instruction in this prompt):
HOTMESS belongs to cities. London is the first frequency, not the only frequency. Never frame HOTMESS as closed, exclusionary, territorial, "London only," or limited to one city forever. HOTMESS is rooted in London first, but exists as a broader philosophy of queer signal infrastructure — nightlife, care, movement, atmosphere, recovery and Radio — that resonates globally. Stay operationally honest about what is shipped today without ever shutting down emotional possibility for cities beyond London.

The signal was never meant to stop at one city. People already follow HOTMESS from Madrid, Berlin, Bangkok, New York and beyond. If a user is in any of those places, they are already part of the conversation.

GOLD-STANDARD RESPONSE FOR ANY OUT-OF-LONDON QUESTION (study this pattern):

User: "I'm in Spain, can I become part of HOTMESS?"
You: "Yes. HOTMESS is currently rooted in London — that's where the live infrastructure, Pulse systems, Radio and founding network are forming first. But the signal was never meant to stop at one city. People already follow HOTMESS from Madrid, Berlin, Bangkok, New York and beyond because the world it's building — nightlife, care, movement, atmosphere, recovery, Radio — exists far outside London too. Right now the focus is making the first city dense and real. But if you're in Spain and paying attention early, you're already part of the conversation. If you're thinking about venues, culture, Radio, partnerships or future city conversations, Phil reads those directly: phil@hotmessldn.com or WhatsApp 07457 404159."

That tone — open door, operationally honest, doctrinally true — is the target for every city question.

WHAT NEVER TO SAY:
- "HOTMESS is London." (closed statement — wrong)
- "Above my pay grade" (sarcastic, breaks atmosphere)
- "I don't have expansion plans to speak to" (defensive, closes door)
- "The platform isn't live outside London." (operationally honest but emotionally closing — must be paired with openness)
- "You're outside the perimeter." (territorial)
- Any phrasing that shrinks the world or denies future possibility.

WHAT TO SAY WHEN UNCERTAIN ABOUT FUTURE ROLLOUT:
"London is the first live city. The focus right now is making the infrastructure dense, trusted and real before the signal expands further. If you want to be part of the conversation early, Phil reads those directly: phil@hotmessldn.com · WhatsApp 07457 404159."

OPERATIONAL HONESTY (still important):
- The live MVP runs in London. Other city infrastructure isn't shipped yet.
- Don't promise launches, dates, or specific city rollouts.
- Don't invent member counts, partner counts, dispatches, schedules.
- If asked about live numbers: "I don't have live numbers — Phil reads every inquiry directly."

BUT operational honesty NEVER overrides the doctrine guardrail. You can be honest about what isn't live without being closed about what's possible.

WHAT HOTMESS IS:
HOTMESS is the live queer signal layer. It combines nightlife, movement, recovery, radio, commerce, care and chemistry into one continuous ecosystem. Built from London but designed to travel. Components: Pulse (the globe), Ghosted (mutuality-first chemistry), Hand N Hand (care/recovery), HOTMESS Radio, RAW CONVICT Records, Tap-Pack (NFC/QR), Market, Safety.

The founder is Phil Gizzie (a.k.a. SMASH DADDY). He owns the station, DJs as SMASH DADDY, runs the label, and reads every inquiry himself. He builds from London and Koh Samui.

CORE DOCTRINE:
- HOTMESS is a live queer signal layer.
- Pulse is not a map. It's a signal.
- Everything on HOTMESS is a signal.
- Partners buy participation, not ad inventory.
- Care is infrastructure.
- Cities don't just move. They sound different.
- The city was already speaking. HOTMESS just made the signals visible.
- Mutuality before message.
- HOTMESS belongs to cities. London is the first frequency.

CONFIRMED CANON:
- Six globe layers: Events, Venues, People, Safety, Market, Radio.
- Six safety primitives: Walk Home, Ride Safe, Stay With Me, Morning Ping, Check-In, Recovery Mode.
- Four radio shows: Wake The Mess (mornings), Dial-A-Daddy (late nights), Hand N Hand (Sundays — sponsored by HNH MESS LUBE), RAW CONVICT (releases).
- RAW001 "Hot Mess" by Paul King ft Stewart Whoo is out now on RAW CONVICT.
- Founding tiers (annual unless noted): Founding Venue £250, Promoter £350, Wellness £400, Signal £500, Chain £750 (3 sites + £200/extra), Anchor £1,000 (postcode exclusivity).
- Care is free forever. Recovery never has a paid tier.
- HOTMESS Radio: listen.radioking.com/radio/hotmess-radio
- Phil's WhatsApp: 07457 404159
- Emails: phil@hotmessldn.com (direct), vendors@hotmessldn.com (partners + city rollout), care@hotmessldn.com (recovery/safety), welcome@hotmessldn.com (members), compliance@hotmessldn.com (moderation/reports), pr@hotmessldn.com (press).

ROUTING:
- City conversations (ANY city, anywhere — Spain, Madrid, Berlin, Manchester, Bangkok, etc.) → phil@hotmessldn.com or WhatsApp 07457 404159 (or vendors@hotmessldn.com with "CITY · [city]" in subject)
- Venue / vendor / creator / recovery-org partnership → §21 inquiry form OR vendors@hotmessldn.com
- Recovery / safety / care orgs → care@hotmessldn.com
- Direct conversation with Phil → phil@hotmessldn.com or WhatsApp
- Press / media → pr@hotmessldn.com
- Urgent → WhatsApp 07457 404159

VOICE:
- Open. Direct. Confident. Welcoming.
- Lowercase except proper nouns (HOTMESS, RAW CONVICT, city names, Phil).
- No emojis. No exclamation marks. No sarcasm.
- Care-first as the default register.
- Never territorial. Never sarcastic. Never defensive.

FORMAT:
- Plain text. No markdown headers, no asterisks for bold.
- 2-4 short paragraphs.
- End with a routing line when relevant: "phil@hotmessldn.com · WhatsApp 07457 404159."
- Always claim to be SIGNAL BOT, never human.`;

function SignalBot() {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState(() => {
    try {
      const storedVersion = localStorage.getItem("hm_signal_bot_version");
      if (storedVersion === SIGNAL_BOT_VERSION) {
        const stored = localStorage.getItem("hm_signal_bot_log");
        if (stored) return JSON.parse(stored);
      } else {
        // Version mismatch — clear stale conversation so old anchoring doesn't carry over
        localStorage.removeItem("hm_signal_bot_log");
        localStorage.setItem("hm_signal_bot_version", SIGNAL_BOT_VERSION);
      }
    } catch {}
    return [{
      role: "assistant",
      content: "signal bot — trained on HOTMESS doctrine. ask me what HOTMESS is, how a night runs on it, how partners join, where care lives, or about your city. for urgent things or to reach Phil directly, WhatsApp 07457 404159.",
    }];
  });
  const [input, setInput] = React.useState("");
  const [pending, setPending] = React.useState(false);
  const scrollRef = React.useRef(null);

  // Persist to localStorage
  React.useEffect(() => {
    try { localStorage.setItem("hm_signal_bot_log", JSON.stringify(messages)); } catch {}
  }, [messages]);

  // Auto-scroll on new message
  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, pending, open]);

  const send = async (e) => {
    if (e) e.preventDefault();
    const text = input.trim();
    if (!text || pending) return;
    setInput("");
    const next = [...messages, { role: "user", content: text }];
    setMessages(next);
    setPending(true);

    try {
      // Build messages for Claude API (skip the seed assistant greeting if it's the only one)
      const apiMessages = next
        .filter((_, i) => !(i === 0 && next[0].role === "assistant"))
        .map((m) => ({ role: m.role, content: m.content }));

      const res = await fetch("/api/signal-bot", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({
          messages: apiMessages.length ? apiMessages : [{ role: "user", content: text }],
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || "signal-bot error");
      const reply = data.reply;

      setMessages([...next, { role: "assistant", content: String(reply || "").trim() || "signal lost. try again in a moment." }]);
    } catch (err) {
      setMessages([...next, {
        role: "assistant",
        content: "signal lost. for urgent things go via WhatsApp · 07457 404159, or email phil@hotmessldn.com.",
      }]);
    } finally {
      setPending(false);
    }
  };

  const clear = () => {
    setMessages([{
      role: "assistant",
      content: "cleared. ask me anything about HOTMESS.",
    }]);
  };

  return (
    <>
      {/* Floating bubble */}
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        aria-label={open ? "Close Signal Bot" : "Open Signal Bot"}
        title="Signal Bot · trained on HOTMESS doctrine"
        style={{
          position: "fixed",
          left: "clamp(16px, 3vw, 28px)",
          bottom: "clamp(16px, 3vw, 28px)",
          width: 56, height: 56, borderRadius: "50%",
          background: open ? "var(--bg)" : "var(--gold)",
          border: open ? "1px solid var(--gold)" : "none",
          color: open ? "var(--gold)" : "var(--bg)",
          display: "flex", alignItems: "center", justifyContent: "center",
          boxShadow: "0 10px 30px rgba(200,150,44,0.4), 0 0 0 1px rgba(0,0,0,0.2)",
          zIndex: 70, cursor: "pointer",
          transition: "transform .2s ease, background .2s, color .2s",
          fontFamily: "var(--display)",
          fontSize: 13, letterSpacing: "0.04em",
        }}
        onMouseEnter={(e) => { e.currentTarget.style.transform = "scale(1.08)"; }}
        onMouseLeave={(e) => { e.currentTarget.style.transform = "scale(1)"; }}
      >
        {open ? "×" : (
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <polyline points="3 12 6 12 9 4 12 20 15 9 18 15 21 12"/>
          </svg>
        )}
      </button>

      {/* Chat panel */}
      {open && (
        <div
          role="dialog"
          aria-label="Signal Bot chat"
          style={{
            position: "fixed",
            left: "clamp(16px, 3vw, 28px)",
            bottom: "calc(clamp(16px, 3vw, 28px) + 72px)",
            width: "min(380px, calc(100vw - 32px))",
            height: "min(560px, calc(100vh - 140px))",
            background: "var(--bg)",
            border: "1px solid var(--gold)",
            borderRadius: 18,
            boxShadow: "0 30px 80px rgba(0,0,0,0.7), 0 0 0 1px rgba(200,150,44,0.2)",
            zIndex: 69,
            display: "flex", flexDirection: "column", overflow: "hidden",
            fontFamily: "var(--sans)",
          }}
        >
          {/* Header */}
          <div style={{
            padding: "14px 18px", borderBottom: "1px solid var(--line)",
            display: "flex", justifyContent: "space-between", alignItems: "center",
            background: "rgba(200,150,44,0.04)",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <span style={{
                width: 8, height: 8, borderRadius: "50%", background: "#3ee07a",
                boxShadow: "0 0 8px #3ee07a", animation: "blink 1.6s ease-in-out infinite",
              }}></span>
              <div className="display" style={{ fontSize: 16, lineHeight: 1, color: "var(--ink)" }}>
                SIGNAL <span style={{ color: "var(--gold)" }}>BOT</span>
              </div>
            </div>
            <button onClick={clear} type="button"
              className="mono"
              style={{
                padding: "4px 8px", background: "transparent",
                border: "1px solid var(--line-2)", color: "var(--ink-3)",
                fontSize: 9, letterSpacing: "0.14em", cursor: "pointer",
              }}
            >CLEAR</button>
          </div>

          {/* Sub-header */}
          <div className="mono" style={{
            padding: "8px 18px", borderBottom: "1px solid var(--line)",
            color: "var(--ink-4)", textTransform: "none", letterSpacing: 0,
            fontFamily: "var(--sans)", fontStyle: "italic", fontSize: 11,
            background: "rgba(0,0,0,0.3)",
          }}>
            trained on doctrine. not human. urgent → WhatsApp 07457 404159.
          </div>

          {/* Messages */}
          <div ref={scrollRef} style={{
            flex: "1 1 auto", minHeight: 0, overflowY: "auto",
            padding: "16px 18px",
            display: "flex", flexDirection: "column", gap: 14,
          }}>
            {messages.map((m, i) => (
              <div key={i} style={{
                display: "flex", flexDirection: "column", gap: 4,
                alignItems: m.role === "user" ? "flex-end" : "flex-start",
              }}>
                <div className="mono" style={{
                  fontSize: 9, letterSpacing: "0.14em",
                  color: m.role === "user" ? "var(--ink-3)" : "var(--gold)",
                }}>{m.role === "user" ? "YOU" : "SIGNAL BOT"}</div>
                <div style={{
                  maxWidth: "92%",
                  padding: "10px 14px",
                  background: m.role === "user" ? "rgba(200,150,44,0.08)" : "rgba(255,255,255,0.025)",
                  border: m.role === "user" ? "1px solid rgba(200,150,44,0.3)" : "1px solid var(--line)",
                  color: "var(--ink)",
                  fontSize: 14, lineHeight: 1.55,
                  whiteSpace: "pre-wrap",
                }}>
                  {m.content}
                </div>
              </div>
            ))}
            {pending && (
              <div style={{ display: "flex", flexDirection: "column", gap: 4, alignItems: "flex-start" }}>
                <div className="mono" style={{ fontSize: 9, letterSpacing: "0.14em", color: "var(--gold)" }}>SIGNAL BOT</div>
                <div style={{
                  padding: "10px 14px",
                  border: "1px solid var(--line)",
                  color: "var(--ink-3)",
                  fontSize: 14, fontStyle: "italic",
                  display: "flex", alignItems: "center", gap: 8,
                }}>
                  <span style={{ display: "inline-block", width: 6, height: 6, borderRadius: "50%", background: "var(--gold)", animation: "blink 1.2s ease-in-out infinite" }}></span>
                  reading the signal…
                </div>
              </div>
            )}
          </div>

          {/* Input */}
          <form onSubmit={send} style={{
            padding: "12px 14px",
            borderTop: "1px solid var(--line)",
            background: "rgba(0,0,0,0.4)",
            display: "flex", gap: 8,
          }}>
            <input
              type="text"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="ask anything about HOTMESS…"
              disabled={pending}
              style={{
                flex: 1, minWidth: 0,
                background: "transparent",
                border: "1px solid var(--line-2)",
                color: "var(--ink)",
                padding: "10px 12px",
                fontFamily: "var(--sans)", fontSize: 13,
                outline: "none",
              }}
              onFocus={(e) => { e.currentTarget.style.borderColor = "var(--gold)"; }}
              onBlur={(e) => { e.currentTarget.style.borderColor = "var(--line-2)"; }}
            />
            <button type="submit" disabled={pending || !input.trim()}
              className="mono"
              style={{
                padding: "10px 14px",
                background: input.trim() && !pending ? "var(--gold)" : "transparent",
                color: input.trim() && !pending ? "var(--bg)" : "var(--ink-4)",
                border: `1px solid ${input.trim() && !pending ? "var(--gold)" : "var(--line-2)"}`,
                cursor: input.trim() && !pending ? "pointer" : "not-allowed",
                fontSize: 10, letterSpacing: "0.14em",
                transition: "all .2s",
              }}
            >SEND</button>
          </form>
        </div>
      )}
    </>
  );
}

Object.assign(window, { SignalBot });
