"use client";

import { useEffect, useRef, useState, useCallback } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import { ChevronDown, Plus, Trash2, X } from "lucide-react";
import { JM, JV } from "@/components/project-creation/modal-theme";
import {
  type ChatContextRef,
  contextRefKey,
} from "@/lib/chat-context-refs";

interface ChatMessage {
  role: "user" | "assistant";
  content: string;
}

interface AtlasChatProps {
  projectId: string;
  projectName?: string;
  /** Sidebar picks — shown as chips; sent with each user message until removed */
  chatContextRefs?: ChatContextRef[];
  onRemoveChatContextRef?: (key: string) => void;
  /** Separate thread from overview discovery chat (stored in DB per scope). */
  conversationScope?: "overview" | "build";
  /** Shown in the composer when no context refs (e.g. Discovery vs Workspace). */
  contextEmptyLabel?: string;
  /** Empty-state subtitle under the Vibn title */
  emptyStateHint?: string;
}

// ---------------------------------------------------------------------------
// Markers — Atlas appends these at end of messages to signal UI actions
// ---------------------------------------------------------------------------

const PHASE_MARKER_RE = /\[\[PHASE_COMPLETE:(.*?)\]\]/s;
const NEXT_STEP_RE = /\[\[NEXT_STEP:(.*?)\]\]/s;

interface PhasePayload {
  phase: string;
  title: string;
  summary: string;
  data: Record<string, unknown>;
}

interface NextStepPayload {
  action: string;
  label: string;
}

function extractMarkers(text: string): {
  clean: string;
  phase: PhasePayload | null;
  nextStep: NextStepPayload | null;
} {
  let clean = text;
  let phase: PhasePayload | null = null;
  let nextStep: NextStepPayload | null = null;

  const phaseMatch = clean.match(PHASE_MARKER_RE);
  if (phaseMatch) {
    try { phase = JSON.parse(phaseMatch[1]); } catch { /* ignore */ }
    clean = clean.replace(PHASE_MARKER_RE, "").trimEnd();
  }

  const nextMatch = clean.match(NEXT_STEP_RE);
  if (nextMatch) {
    try { nextStep = JSON.parse(nextMatch[1]); } catch { /* ignore */ }
    clean = clean.replace(NEXT_STEP_RE, "").trimEnd();
  }

  return { clean, phase, nextStep };
}

// ---------------------------------------------------------------------------
// Markdown-lite renderer — handles **bold**, newlines, numbered/bullet lists
// ---------------------------------------------------------------------------
function renderContent(text: string | null | undefined) {
  if (!text) return null;
  return text.split("\n").map((line, i) => {
    const parts = line.split(/(\*\*.*?\*\*)/g).map((seg, j) =>
      seg.startsWith("**") && seg.endsWith("**")
        ? <strong key={j} style={{ fontWeight: 600, color: JM.ink }}>{seg.slice(2, -2)}</strong>
        : <span key={j}>{seg}</span>
    );
    return <div key={i} style={{ minHeight: line.length ? undefined : "0.75em" }}>{parts}</div>;
  });
}

// ---------------------------------------------------------------------------
// Message row
// ---------------------------------------------------------------------------
function MessageRow({
  msg, projectId, workspace,
}: {
  msg: ChatMessage;
  projectId: string;
  workspace: string;
}) {
  const isAtlas = msg.role === "assistant";
  const { clean, phase, nextStep } = isAtlas
    ? extractMarkers(msg.content ?? "")
    : { clean: msg.content ?? "", phase: null, nextStep: null };

  // Phase save state
  const [saved, setSaved] = useState(false);
  const [saving, setSaving] = useState(false);

  // Architecture generation state
  const [archState, setArchState] = useState<"idle" | "loading" | "done" | "error">("idle");
  const [archError, setArchError] = useState<string | null>(null);

  const handleSavePhase = async () => {
    if (!phase || saved || saving) return;
    setSaving(true);
    try {
      await fetch(`/api/projects/${projectId}/save-phase`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(phase),
      });
      setSaved(true);
    } catch { /* swallow — user can retry */ } finally {
      setSaving(false);
    }
  };

  const handleGenerateArchitecture = async () => {
    if (archState !== "idle") return;
    setArchState("loading");
    setArchError(null);
    try {
      const res = await fetch(`/api/projects/${projectId}/architecture`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({}),
      });
      const d = await res.json();
      if (!res.ok) throw new Error(d.error || "Generation failed");
      setArchState("done");
    } catch (e) {
      setArchError(e instanceof Error ? e.message : "Something went wrong");
      setArchState("error");
    }
  };

  if (!isAtlas) {
    return (
      <div style={{
        marginBottom: 20,
        marginTop: -4,
        animation: "enter 0.3s ease both",
        display: "flex",
        justifyContent: "flex-end",
      }}>
        <div style={{
          maxWidth: "min(85%, 480px)",
          display: "flex",
          flexDirection: "column",
          alignItems: "flex-end",
          gap: 4,
        }}>
          <div style={{
            background: JV.userBubbleBg,
            border: `1px solid ${JV.userBubbleBorder}`,
            borderRadius: 18,
            padding: "12px 16px",
            fontSize: 14,
            color: JM.ink,
            lineHeight: 1.65,
            fontFamily: JM.fontSans,
            whiteSpace: "pre-wrap",
          }}>
            {renderContent(clean)}
          </div>
          <div style={{
            fontSize: 10, fontWeight: 600, color: JM.muted,
            textTransform: "uppercase", letterSpacing: "0.06em",
            fontFamily: JM.fontSans,
            paddingRight: 2,
          }}>
            You
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ display: "flex", gap: 12, marginBottom: 26, animation: "enter 0.3s ease both" }}>
      <div style={{
        width: 28, height: 28, borderRadius: 8, flexShrink: 0, marginTop: 2,
        background: JM.primaryGradient,
        display: "flex", alignItems: "center", justifyContent: "center",
        fontSize: 11, fontWeight: 700,
        color: "#fff",
        fontFamily: JM.fontSans,
        boxShadow: JM.primaryShadow,
      }}>
        A
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 10, fontWeight: 600, color: JM.muted,
          marginBottom: 6, textTransform: "uppercase", letterSpacing: "0.05em",
          fontFamily: JM.fontSans,
        }}>
          Vibn
        </div>
        <div style={{
          fontSize: 15, color: JM.ink, lineHeight: 1.75,
          fontFamily: JM.fontSans,
          whiteSpace: "normal",
        }}>
          {renderContent(clean)}
        </div>

        {/* Phase save button */}
        {phase && (
          <div style={{ marginTop: 14 }}>
            <button
              type="button"
              onClick={handleSavePhase}
              disabled={saved || saving}
              style={{
                display: "inline-flex", alignItems: "center", gap: 7,
                padding: "8px 16px", borderRadius: 8,
                background: saved ? "#e8f5e9" : JM.primaryGradient,
                color: saved ? "#2e7d32" : "#fff",
                border: saved ? "1px solid #a5d6a7" : "none",
                fontSize: 12, fontWeight: 600,
                fontFamily: JM.fontSans,
                cursor: saved || saving ? "default" : "pointer",
                transition: "all 0.15s",
                opacity: saving ? 0.7 : 1,
                boxShadow: saved ? "none" : JM.primaryShadow,
              }}
            >
              {saved ? "✓ Phase saved" : saving ? "Saving…" : `Save phase — ${phase.title}`}
            </button>
            {!saved && (
              <div style={{
                marginTop: 6, fontSize: 11, color: JM.muted,
                fontFamily: JM.fontSans, lineHeight: 1.4,
              }}>
                {phase.summary}
              </div>
            )}
          </div>
        )}

        {/* Next step — architecture generation */}
        {nextStep?.action === "generate_architecture" && (
          <div style={{
            marginTop: 16,
            padding: "16px 18px",
            background: JV.composerSurface,
            border: `1px solid ${JM.border}`,
            borderRadius: 14,
            borderLeft: `3px solid ${JM.indigo}`,
            boxShadow: "0 1px 8px rgba(30,27,75,0.04)",
          }}>
            {archState === "done" ? (
              <div>
                <div style={{ fontSize: "0.82rem", fontWeight: 600, color: "#2e7d32", marginBottom: 6 }}>
                  ✓ Architecture generated
                </div>
                <p style={{ fontSize: "0.76rem", color: "#6b6560", margin: "0 0 12px", lineHeight: 1.5 }}>
                  Review the recommended apps, services, and infrastructure — then confirm when you&apos;re ready.
                </p>
                <Link
                  href={`/${workspace}/project/${projectId}/build`}
                  style={{
                    display: "inline-block", padding: "8px 16px", borderRadius: 8,
                    background: JM.primaryGradient, color: "#fff",
                    fontSize: 12, fontWeight: 600,
                    fontFamily: JM.fontSans, textDecoration: "none",
                    boxShadow: JM.primaryShadow,
                  }}
                >
                  Review architecture →
                </Link>
              </div>
            ) : archState === "error" ? (
              <div>
                <div style={{ fontSize: "0.78rem", color: "#c62828", marginBottom: 8 }}>
                  ⚠ {archError}
                </div>
                <button
                  type="button"
                  onClick={() => { setArchState("idle"); setArchError(null); }}
                  style={{
                    padding: "7px 14px", borderRadius: 8, border: `1px solid ${JM.border}`,
                    background: "none", fontSize: 12, color: JM.mid,
                    fontFamily: JM.fontSans, cursor: "pointer",
                  }}
                >
                  Try again
                </button>
              </div>
            ) : (
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, color: JM.ink, marginBottom: 5, fontFamily: JM.fontSans }}>
                  Next: Technical architecture
                </div>
                <p style={{ fontSize: 12, color: JM.mid, margin: "0 0 14px", lineHeight: 1.55, fontFamily: JM.fontSans }}>
                  The AI will read your PRD and recommend the apps, services, and infrastructure your product needs. Takes about 30 seconds.
                </p>
                <button
                  type="button"
                  onClick={handleGenerateArchitecture}
                  disabled={archState === "loading"}
                  style={{
                    display: "inline-flex", alignItems: "center", gap: 8,
                    padding: "9px 18px", borderRadius: 8, border: "none",
                    background: archState === "loading" ? JM.muted : JM.primaryGradient,
                    color: "#fff", fontSize: 12, fontWeight: 600,
                    fontFamily: JM.fontSans,
                    cursor: archState === "loading" ? "default" : "pointer",
                    transition: "background 0.15s",
                    boxShadow: archState === "loading" ? "none" : JM.primaryShadow,
                  }}
                >
                  {archState === "loading" && (
                    <span style={{
                      width: 12, height: 12, borderRadius: "50%",
                      border: "2px solid #ffffff40", borderTopColor: "#fff",
                      animation: "spin 0.7s linear infinite", display: "inline-block",
                    }} />
                  )}
                  {archState === "loading" ? "Analysing PRD…" : nextStep.label}
                </button>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Typing indicator
// ---------------------------------------------------------------------------
function TypingIndicator() {
  return (
    <div style={{ display: "flex", gap: 12, marginBottom: 26, animation: "enter 0.2s ease", alignItems: "center" }}>
      <div style={{
        width: 28, height: 28, borderRadius: 8, flexShrink: 0,
        background: JM.primaryGradient,
        boxShadow: JM.primaryShadow,
        display: "flex", alignItems: "center", justifyContent: "center",
        fontSize: 11, fontWeight: 700, color: "#fff", fontFamily: JM.fontSans,
      }}>A</div>
      <div style={{ display: "flex", gap: 5, alignItems: "center", paddingTop: 2 }}>
        {[0, 1, 2].map(d => (
          <div key={d} style={{
            width: 5, height: 5, borderRadius: "50%", background: JM.muted,
            animation: `blink 1s ease ${d * 0.15}s infinite`,
          }} />
        ))}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Main component
// ---------------------------------------------------------------------------
export function AtlasChat({
  projectId,
  chatContextRefs = [],
  onRemoveChatContextRef,
  conversationScope = "overview",
  contextEmptyLabel = "Discovery",
  emptyStateHint,
}: AtlasChatProps) {
  const params = useParams();
  const workspace = (params?.workspace as string) ?? "";

  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState("");
  const [isStreaming, setIsStreaming] = useState(false);
  const [historyLoaded, setHistoryLoaded] = useState(false);
  const [showScrollFab, setShowScrollFab] = useState(false);
  const initTriggered = useRef(false);
  const endRef = useRef<HTMLDivElement>(null);
  const scrollRef = useRef<HTMLDivElement>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  const visibleMessages = messages.filter(msg => msg.content);

  const syncScrollFab = useCallback(() => {
    const el = scrollRef.current;
    if (!el) return;
    const dist = el.scrollHeight - el.scrollTop - el.clientHeight;
    setShowScrollFab(dist > 120 && visibleMessages.length > 0);
  }, [visibleMessages.length]);

  // Scroll to bottom whenever messages change
  useEffect(() => {
    endRef.current?.scrollIntoView({ behavior: "smooth" });
    requestAnimationFrame(syncScrollFab);
  }, [messages, isStreaming, syncScrollFab]);

  // Send a message to Atlas — optionally hidden from UI (for init trigger)
  const sendToAtlas = useCallback(async (text: string, hideUserMsg = false) => {
    if (!hideUserMsg) {
      setMessages(prev => [...prev, { role: "user", content: text }]);
    }
    setIsStreaming(true);

    const isInit = text.trim() === "__atlas_init__";
    const payload: { message: string; contextRefs?: ChatContextRef[] } = { message: text };
    if (!isInit && chatContextRefs.length > 0) {
      payload.contextRefs = chatContextRefs;
    }

    try {
      const res = await fetch(`/api/projects/${projectId}/atlas-chat`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...payload, scope: conversationScope }),
      });

      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(err.error || "Atlas is unavailable. Please try again.");
      }

      const data = await res.json();

      // alreadyStarted means the init was called but history already exists — ignore
      if (data.alreadyStarted) return;

      if (data.reply) {
        setMessages(prev => [...prev, { role: "assistant", content: data.reply }]);
      }
    } catch (e) {
      const msg = e instanceof Error ? e.message : "Something went wrong.";
      setMessages(prev => [...prev, { role: "assistant", content: msg }]);
    } finally {
      setIsStreaming(false);
    }
  }, [projectId, chatContextRefs, conversationScope]);

  // On mount: load stored history; if empty, trigger Atlas greeting exactly once
  useEffect(() => {
    let cancelled = false; // guard against unmount during fetch

    fetch(`/api/projects/${projectId}/atlas-chat?scope=${encodeURIComponent(conversationScope)}`)
      .then(r => r.json())
      .then((data: { messages: ChatMessage[] }) => {
        if (cancelled) return;
        const stored = data.messages ?? [];
        setMessages(stored);
        setHistoryLoaded(true);

        // Only greet if there is genuinely no history and we haven't triggered yet
        if (stored.length === 0 && !initTriggered.current) {
          initTriggered.current = true;
          sendToAtlas("__atlas_init__", true);
        }
      })
      .catch(() => {
        if (cancelled) return;
        setHistoryLoaded(true);
      });

    return () => { cancelled = true; };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [projectId, conversationScope]);

  const handleReset = async () => {
    if (!confirm("Clear this conversation and start fresh?")) return;
    try {
      await fetch(
        `/api/projects/${projectId}/atlas-chat?scope=${encodeURIComponent(conversationScope)}`,
        { method: "DELETE" }
      );
      setMessages([]);
      setHistoryLoaded(false);
      initTriggered.current = false;
      // Trigger fresh greeting
      setTimeout(() => {
        initTriggered.current = true;
        sendToAtlas("__atlas_init__", true);
      }, 100);
    } catch {
      // swallow
    }
  };

  const handleSend = () => {
    const text = input.trim();
    if (!text || isStreaming) return;
    setInput("");
    sendToAtlas(text, false);
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const isEmpty = visibleMessages.length === 0 && !isStreaming;

  const feedPad = { paddingLeft: 20, paddingRight: 20 } as const;

  return (
    <div style={{
      display: "flex", flexDirection: "column", height: "100%",
      background: JV.chatColumnBg,
      fontFamily: JM.fontSans,
    }}>
      <style>{`
        @keyframes blink { 0%,100%{opacity:.2} 50%{opacity:.8} }
        @keyframes enter { from { opacity:0; transform:translateY(6px); } to { opacity:1; transform:translateY(0); } }
        @keyframes spin { to { transform:rotate(360deg); } }
      `}</style>

      {/* Empty state */}
      {isEmpty && (
        <div style={{
          flex: 1, display: "flex", flexDirection: "column",
          alignItems: "center", justifyContent: "center",
          gap: 12, padding: "40px 20px",
        }}>
          <div style={{ width: "100%", maxWidth: JV.chatFeedMaxWidth, margin: "0 auto" }}>
            <div style={{
              display: "flex", flexDirection: "column", alignItems: "center", gap: 12,
            }}>
              <div style={{
                width: 44, height: 44, borderRadius: 14, background: JM.primaryGradient,
                boxShadow: JM.primaryShadow,
                display: "flex", alignItems: "center", justifyContent: "center",
                fontFamily: JM.fontSans, fontSize: 18, fontWeight: 600, color: "#fff",
                animation: "breathe 2.5s ease infinite",
              }}>A</div>
              <style>{`@keyframes breathe { 0%,100%{transform:scale(1)} 50%{transform:scale(1.08)} }`}</style>
              <div style={{ textAlign: "center" }}>
                <p style={{ fontSize: 15, fontWeight: 600, color: JM.ink, marginBottom: 4, fontFamily: JM.fontDisplay }}>Vibn</p>
                <p style={{ fontSize: 13, color: JM.muted, maxWidth: 320, lineHeight: 1.55, margin: 0 }}>
                  {emptyStateHint ??
                    "Your product strategist. Let\u2019s define what you\u2019re building."}
                </p>
              </div>
            </div>
          </div>
        </div>
      )}

      {!isEmpty && (
        <div style={{
          flex: 1, minHeight: 0, position: "relative", display: "flex", flexDirection: "column",
        }}>
          <div
            ref={scrollRef}
            onScroll={syncScrollFab}
            style={{
              flex: 1, overflowY: "auto", paddingTop: 24, paddingBottom: 16,
              ...feedPad,
            }}
          >
            <div style={{ maxWidth: JV.chatFeedMaxWidth, margin: "0 auto", width: "100%" }}>
              {visibleMessages.map((msg, i) => (
                <MessageRow key={i} msg={msg} projectId={projectId} workspace={workspace} />
              ))}
              {isStreaming && <TypingIndicator />}
              <div ref={endRef} />
            </div>
          </div>
          {showScrollFab && (
            <button
              type="button"
              title="Scroll to latest"
              onClick={() => endRef.current?.scrollIntoView({ behavior: "smooth" })}
              style={{
                position: "absolute",
                right: `max(20px, calc((100% - ${JV.chatFeedMaxWidth}px) / 2 + 8px))`,
                bottom: 12,
                width: 36,
                height: 36,
                borderRadius: "50%",
                border: `1px solid ${JM.border}`,
                background: JV.composerSurface,
                boxShadow: "0 2px 12px rgba(30,27,75,0.1)",
                cursor: "pointer",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                color: JM.mid,
              }}
            >
              <ChevronDown size={18} strokeWidth={2} />
            </button>
          )}
        </div>
      )}

      {isEmpty && isStreaming && (
        <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", ...feedPad }}>
          <div style={{ maxWidth: JV.chatFeedMaxWidth, width: "100%" }}>
            <TypingIndicator />
          </div>
        </div>
      )}

      {!isEmpty && !isStreaming && (
        <div style={{
          padding: "0 0 10px",
          ...feedPad,
          display: "flex",
          justifyContent: "center",
        }}>
          <div style={{
            maxWidth: JV.chatFeedMaxWidth,
            width: "100%",
            display: "flex",
            gap: 8,
            flexWrap: "wrap",
          }}>
            {[
              { label: "Give me suggestions", prompt: "Can you give me some examples or suggestions to help me think through this?" },
              { label: "What's most important?", prompt: "What's the most important thing for me to nail down right now?" },
              { label: "Move on", prompt: "That's enough detail for now — let's move to the next phase." },
            ].map(({ label, prompt }) => (
              <button
                type="button"
                key={label}
                onClick={() => sendToAtlas(prompt, false)}
                style={{
                  padding: "6px 14px", borderRadius: 999,
                  border: `1px solid ${JM.border}`,
                  background: JV.composerSurface, color: JM.mid,
                  fontSize: 12, fontFamily: JM.fontSans,
                  cursor: "pointer", transition: "all 0.1s",
                  whiteSpace: "nowrap",
                }}
                onMouseEnter={e => {
                  (e.currentTarget as HTMLElement).style.background = JV.violetTint;
                  (e.currentTarget as HTMLElement).style.borderColor = JV.bubbleAiBorder;
                  (e.currentTarget as HTMLElement).style.color = JM.ink;
                }}
                onMouseLeave={e => {
                  (e.currentTarget as HTMLElement).style.background = JV.composerSurface;
                  (e.currentTarget as HTMLElement).style.borderColor = JM.border;
                  (e.currentTarget as HTMLElement).style.color = JM.mid;
                }}
              >
                {label}
              </button>
            ))}
          </div>
        </div>
      )}

      <div style={{
        padding: `10px 20px max(20px, env(safe-area-inset-bottom))`,
        flexShrink: 0,
        display: "flex",
        justifyContent: "center",
      }}>
        <div style={{ width: "100%", maxWidth: JV.chatFeedMaxWidth }}>
          <div style={{
            background: JV.composerSurface,
            border: `1px solid ${JM.border}`,
            borderRadius: JV.composerRadius,
            boxShadow: JV.composerShadow,
            overflow: "hidden",
          }}>
            <textarea
              ref={textareaRef}
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder="Reply…"
              rows={2}
              disabled={isStreaming}
              style={{
                display: "block",
                width: "100%",
                border: "none",
                background: "transparent",
                fontSize: 15,
                fontFamily: JM.fontSans,
                color: JM.ink,
                padding: "16px 18px 10px",
                resize: "none",
                outline: "none",
                minHeight: 52,
                maxHeight: 200,
                lineHeight: 1.5,
                boxSizing: "border-box",
              }}
            />
            <div style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              gap: 12,
              padding: "8px 10px 10px 12px",
              borderTop: `1px solid ${JM.border}`,
              background: "rgba(249,250,251,0.6)",
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 4 }}>
                <button
                  type="button"
                  title="Focus composer"
                  onClick={() => textareaRef.current?.focus()}
                  style={{
                    width: 36,
                    height: 36,
                    borderRadius: 10,
                    border: "none",
                    background: "transparent",
                    cursor: "pointer",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    color: JM.mid,
                  }}
                >
                  <Plus size={20} strokeWidth={1.75} />
                </button>
                <button
                  type="button"
                  title="Clear conversation"
                  onClick={handleReset}
                  style={{
                    width: 36,
                    height: 36,
                    borderRadius: 10,
                    border: "none",
                    background: "transparent",
                    cursor: "pointer",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    color: JM.muted,
                  }}
                >
                  <Trash2 size={18} strokeWidth={1.75} />
                </button>
              </div>
              <div style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "flex-end",
                gap: 8,
                flex: 1,
                minWidth: 0,
                flexWrap: "wrap",
              }}>
                {chatContextRefs.length > 0 && onRemoveChatContextRef && (
                  <div style={{
                    display: "flex",
                    flexWrap: "wrap",
                    gap: 6,
                    alignItems: "center",
                    justifyContent: "flex-end",
                    minWidth: 0,
                    flex: "1 1 auto",
                    maxWidth: "100%",
                  }}>
                    {chatContextRefs.map(ref => {
                      const key = contextRefKey(ref);
                      const prefix =
                        ref.kind === "section" ? "Section" : ref.kind === "phase" ? "Phase" : "App";
                      return (
                        <span
                          key={key}
                          style={{
                            display: "inline-flex",
                            alignItems: "center",
                            gap: 4,
                            maxWidth: 200,
                            padding: "4px 6px 4px 10px",
                            borderRadius: 999,
                            border: `1px solid ${JV.bubbleAiBorder}`,
                            background: JV.violetTint,
                            fontSize: 11,
                            fontWeight: 600,
                            color: JM.indigo,
                            fontFamily: JM.fontSans,
                            flexShrink: 1,
                          }}
                        >
                          <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", minWidth: 0 }}>
                            {prefix}: {ref.label}
                          </span>
                          <button
                            type="button"
                            title="Remove reference"
                            onClick={() => onRemoveChatContextRef(key)}
                            style={{
                              border: "none",
                              background: "rgba(255,255,255,0.7)",
                              borderRadius: "50%",
                              width: 20,
                              height: 20,
                              padding: 0,
                              cursor: "pointer",
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                              color: JM.mid,
                              flexShrink: 0,
                            }}
                          >
                            <X size={12} strokeWidth={2.5} />
                          </button>
                        </span>
                      );
                    })}
                  </div>
                )}
                {chatContextRefs.length === 0 && (
                  <span style={{
                    fontSize: 11,
                    fontWeight: 600,
                    color: JM.mid,
                    fontFamily: JM.fontSans,
                    padding: "5px 10px",
                    borderRadius: 999,
                    border: `1px solid ${JM.border}`,
                    background: JV.violetTint,
                    whiteSpace: "nowrap",
                    flexShrink: 0,
                  }}>
                    {contextEmptyLabel}
                  </span>
                )}
                {isStreaming ? (
                  <button
                    type="button"
                    onClick={() => setIsStreaming(false)}
                    style={{
                      padding: "9px 18px", borderRadius: 10, border: "none",
                      background: JV.violetTint, color: JM.mid,
                      fontSize: 12, fontWeight: 600, fontFamily: JM.fontSans,
                      cursor: "pointer",
                      display: "flex", alignItems: "center", gap: 6,
                      flexShrink: 0,
                    }}
                  >
                    <span style={{ width: 8, height: 8, background: JM.indigo, borderRadius: 2, display: "inline-block" }} />
                    Stop
                  </button>
                ) : (
                  <button
                    type="button"
                    onClick={handleSend}
                    disabled={!input.trim()}
                    style={{
                      padding: "9px 20px", borderRadius: 10, border: "none",
                      background: input.trim() ? JM.primaryGradient : JV.violetTint,
                      color: input.trim() ? "#fff" : JM.muted,
                      fontSize: 12, fontWeight: 600, fontFamily: JM.fontSans,
                      cursor: input.trim() ? "pointer" : "default",
                      boxShadow: input.trim() ? JM.primaryShadow : "none",
                      transition: "opacity 0.15s",
                      flexShrink: 0,
                    }}
                    onMouseEnter={e => { if (input.trim()) (e.currentTarget.style.opacity = "0.92"); }}
                    onMouseLeave={e => { (e.currentTarget.style.opacity = "1"); }}
                  >
                    Send
                  </button>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
