"use client";
import { useState, useRef, useEffect, useCallback } from "react";
import { Node, Edge } from "reactflow";
import { NodeData } from "./nodes/nodeTypes";

interface Props {
  nodes: Node<NodeData>[];
  edges: Edge[];
  onClose: () => void;
}

/* ── Sample patient vars ── */
const PATIENT: Record<string, string> = {
  name: "Sarah",
  treatment: "Teeth Cleaning",
  clinic: "Smile Dental",
  date: "Monday, March 11",
  time: "2:30 PM",
  phone: "+966 50 123 4567",
};

/* ── Helpers ── */
function fill(text: string, mem: Record<string, string>): string {
  return (text ?? "")
    .replace(/\{\{memory\.(\w+)\}\}/g, (_, k) => mem[k] ?? `[${k}]`)
    .replace(/\{\{(\w+)\}\}/g, (_, k) => PATIENT[k] ?? `[${k}]`);
}
function getNext(edges: Edge[], sourceId: string, handle?: string): string | null {
  const edge =
    edges.find(e => e.source === sourceId && (handle ? e.sourceHandle === handle : !e.sourceHandle || e.sourceHandle === null)) ??
    edges.find(e => e.source === sourceId);
  return edge?.target ?? null;
}
function getNode(nodes: Node<NodeData>[], id: string | null): Node<NodeData> | null {
  return id ? nodes.find(n => n.id === id) ?? null : null;
}

/* ── Message type ── */
type Msg = {
  id: string;
  from: "bot" | "user";
  text: string;
  buttons?: { id: string; text: string }[];
  timestamp: string;
  nodeLabel?: string;
};

function nowTime() {
  return new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
}
function uid() {
  return Math.random().toString(36).slice(2, 10);
}

/* ════════════════════════════════════
   SIMULATOR
════════════════════════════════════ */
export default function Simulator({ nodes, edges, onClose }: Props) {
  const [msgs, setMsgs]             = useState<Msg[]>([]);
  const [typing, setTyping]         = useState(false);
  const [waitInput, setWaitInput]   = useState(false);
  const [inputText, setInputText]   = useState("");
  const [memory, setMemory]         = useState<Record<string, string>>({});
  const [activeNode, setActiveNode] = useState<Node<NodeData> | null>(null);
  const [done, setDone]             = useState(false);
  const [started, setStarted]       = useState(false);
  const [clockTime, setClockTime]   = useState(nowTime);
  const chatBoxRef = useRef<HTMLDivElement>(null);
  const inputRef   = useRef<HTMLInputElement>(null);
  const runningRef = useRef(false);

  /* clock */
  useEffect(() => {
    const t = setInterval(() => setClockTime(nowTime()), 30000);
    return () => clearInterval(t);
  }, []);

  /* auto-scroll */
  useEffect(() => {
    const el = chatBoxRef.current;
    if (!el) return;
    setTimeout(() => { el.scrollTop = el.scrollHeight; }, 80);
  }, [msgs, typing]);

  /* ── bot message ── */
  const addBotMsg = useCallback((text: string, buttons?: Msg["buttons"], nodeLabel?: string) => {
    return new Promise<void>(resolve => {
      setTyping(true);
      const delay = Math.min(Math.max(text.length * 10, 500), 1800);
      setTimeout(() => {
        setTyping(false);
        setMsgs(m => [...m, { id: uid(), from: "bot", text, buttons, timestamp: nowTime(), nodeLabel }]);
        setTimeout(resolve, 120);
      }, delay);
    });
  }, []);

  /* ── user message ── */
  const addUserMsg = useCallback((text: string) => {
    setMsgs(m => m.map(msg => ({ ...msg, buttons: undefined })));
    setMsgs(m => [...m, { id: uid(), from: "user", text, timestamp: nowTime() }]);
  }, []);

  /* ── node runner ── */
  const runNode = useCallback(async (nodeId: string | null, mem: Record<string, string>): Promise<void> => {
    if (!nodeId || !runningRef.current) return;
    const node = getNode(nodes, nodeId);
    if (!node) { setDone(true); return; }
    const d = node.data;
    setActiveNode(node);

    if (d.kind === "start") {
      return runNode(getNext(edges, node.id), mem);
    }
    if (d.kind === "message") {
      await addBotMsg(fill(d.content ?? "", mem), undefined, d.label);
      return runNode(getNext(edges, node.id), mem);
    }
    if (d.kind === "buttons") {
      const btns = (d.buttons ?? []).slice(0, 3).map(b => ({ id: b.id, text: b.text }));
      await addBotMsg(fill(d.content ?? "", mem), btns, d.label);
      runningRef.current = false;
      return;
    }
    if (d.kind === "save_var") {
      await addBotMsg(fill(d.varPrompt ?? `What is your ${d.varName ?? "answer"}?`, mem), undefined, d.label);
      setWaitInput(true);
      runningRef.current = false;
      return;
    }
    if (d.kind === "condition") {
      const branchList = (d.branches ?? []).map((b: any) => b.label).join(" / ");
      await addBotMsg(`🔀 Choose:\n${branchList}\n\n_(type your reply)_`, undefined, d.label);
      setWaitInput(true);
      runningRef.current = false;
      return;
    }
    if (d.kind === "sentiment") {
      await addBotMsg("How are you feeling right now?", [
        { id: "positive", text: "😊 Great!" },
        { id: "neutral",  text: "😐 Okay" },
        { id: "negative", text: "😟 Not great" },
      ], d.label);
      runningRef.current = false;
      return;
    }
    if (d.kind === "retry") {
      await addBotMsg(`🔄 *Smart Retry* — waits ${d.retryDelayMinutes ?? 1440} min then sends:\n"${fill(d.retryMessage ?? "Hey {{name}}, just following up! 👋", mem)}"`, undefined, d.label);
      return runNode(getNext(edges, node.id, "responded") ?? getNext(edges, node.id), mem);
    }
    if (d.kind === "wait") {
      const mins = d.delayMinutes ?? 60;
      const label = mins >= 1440 ? `${Math.round(mins / 1440)} day(s)` : mins >= 60 ? `${Math.round(mins / 60)} hr` : `${mins} min`;
      await addBotMsg(`⏳ *[Wait ${label}]* — Pauses here in production. Continuing preview…`, undefined, d.label);
      await new Promise(r => setTimeout(r, 400));
      return runNode(getNext(edges, node.id), mem);
    }
    if (d.kind === "end") {
      await addBotMsg(`✅ *${fill(d.label ?? "Journey Complete", mem)}*\n\n_Conversation ended. Thank you, ${PATIENT.name}!_ 🎉`, undefined, d.label);
      setDone(true);
      setActiveNode(null);
      return;
    }
    return runNode(getNext(edges, node.id), mem);
  }, [nodes, edges, addBotMsg]);

  /* ── start / restart ── */
  const start = useCallback(() => {
    runningRef.current = true;
    setMsgs([]);
    setDone(false);
    setStarted(true);
    setWaitInput(false);
    setTyping(false);
    setActiveNode(null);
    setInputText("");
    const mem: Record<string, string> = {};
    setMemory(mem);
    const startNode = nodes.find(n => n.data.kind === "start");
    if (!startNode) {
      setTimeout(() => {
        setMsgs([{ id: uid(), from: "bot", text: "❌ No Trigger block found. Add a Start/Trigger block to your flow first!", timestamp: nowTime() }]);
        setDone(true);
      }, 400);
      return;
    }
    setTimeout(() => runNode(startNode.id, mem), 500);
  }, [nodes, runNode]);

  /* ── button click ── */
  const handleBtn = useCallback(async (btnId: string, btnText: string) => {
    if (!activeNode || runningRef.current) return;
    runningRef.current = true;
    addUserMsg(btnText);
    const mem = { ...memory };
    setActiveNode(null);
    await new Promise(r => setTimeout(r, 250));
    runNode(getNext(edges, activeNode.id, btnId) ?? getNext(edges, activeNode.id), mem);
  }, [activeNode, memory, edges, addUserMsg, runNode]);

  /* ── text submit ── */
  const handleSubmit = useCallback(async () => {
    if (!inputText.trim() || !activeNode || runningRef.current) return;
    const text = inputText.trim();
    setInputText("");
    setWaitInput(false);
    runningRef.current = true;
    addUserMsg(text);
    let mem = { ...memory };

    if (activeNode.data.kind === "save_var") {
      mem = { ...mem, [activeNode.data.varName ?? "answer"]: text };
      setMemory(mem);
      const next = getNext(edges, activeNode.id);
      setActiveNode(null);
      await new Promise(r => setTimeout(r, 250));
      return runNode(next, mem);
    }
    if (activeNode.data.kind === "condition") {
      const branches: any[] = activeNode.data.branches ?? [];
      let handle = "else";
      const lc = text.toLowerCase().trim();
      const numMatch = lc.match(/^(\d+)$/);
      if (numMatch) {
        const idx = parseInt(numMatch[1]) - 1;
        if (idx >= 0 && idx < branches.length) handle = branches[idx].id;
      } else {
        for (const br of branches) {
          if ((br.keywords ?? []).some((k: string) => lc.includes(k.toLowerCase()))) {
            handle = br.id; break;
          }
        }
      }
      const next = getNext(edges, activeNode.id, handle) ?? getNext(edges, activeNode.id);
      setActiveNode(null);
      await new Promise(r => setTimeout(r, 250));
      return runNode(next, mem);
    }
    const next = getNext(edges, activeNode.id);
    setActiveNode(null);
    await new Promise(r => setTimeout(r, 250));
    runNode(next, mem);
  }, [inputText, activeNode, memory, edges, addUserMsg, runNode]);

  const hasFlow = nodes.length > 0;
  const statusText = typing ? "typing…" : done ? "conversation ended" : activeNode ? `${activeNode.data.label}` : started ? "online" : "online";

  return (
    /* ── Overlay ── */
    <div
      className="fixed inset-0 z-50 flex items-center justify-center overlay-blur-in"
      style={{ background: "rgba(0,0,0,0.75)", backdropFilter: "blur(12px)" }}
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div className="flex flex-col items-center gap-3 phone-enter" style={{ maxHeight: "100vh", padding: "16px 0" }}>

        {/* ══ PHONE SHELL ══ */}
        <div
          className="relative flex flex-col overflow-hidden"
          style={{
            width: 360,
            borderRadius: 44,
            background: "#111827",
            boxShadow: "0 0 0 2px #374151, 0 0 0 7px #111827, 0 0 0 9px #374151, 0 40px 80px rgba(0,0,0,0.7)",
          }}
        >
          {/* Side buttons (decorative) */}
          <div className="absolute -right-[3px] top-24 w-[3px] h-10 bg-gray-600 rounded-r-full" />
          <div className="absolute -left-[3px] top-20 w-[3px] h-7 bg-gray-600 rounded-l-full" />
          <div className="absolute -left-[3px] top-32 w-[3px] h-7 bg-gray-600 rounded-l-full" />

          {/* Notch */}
          <div
            className="absolute top-0 left-1/2 -translate-x-1/2 z-20 flex items-end justify-center"
            style={{ width: 120, height: 28, background: "#111827", borderRadius: "0 0 20px 20px" }}
          >
            <div style={{ width: 48, height: 5, background: "#374151", borderRadius: 99, marginBottom: 5 }} />
          </div>

          {/* Status bar */}
          <div
            className="flex items-center justify-between px-7 text-white"
            style={{ height: 44, background: "#075E54", paddingTop: 16 }}
          >
            <span style={{ fontSize: 11, fontWeight: 700 }}>{clockTime}</span>
            <div className="flex items-center gap-1.5" style={{ fontSize: 11 }}>
              <svg width="15" height="11" viewBox="0 0 15 11" fill="white" opacity={0.9}>
                <rect x="0" y="7" width="3" height="4" rx="0.5"/>
                <rect x="4" y="5" width="3" height="6" rx="0.5"/>
                <rect x="8" y="3" width="3" height="8" rx="0.5"/>
                <rect x="12" y="0" width="3" height="11" rx="0.5"/>
              </svg>
              <svg width="14" height="11" viewBox="0 0 14 11" fill="white" opacity={0.9}>
                <path d="M7 2.5C9.2 2.5 11.2 3.4 12.6 4.9L14 3.5C12.2 1.6 9.7 0.5 7 0.5C4.3 0.5 1.8 1.6 0 3.5L1.4 4.9C2.8 3.4 4.8 2.5 7 2.5Z"/>
                <path d="M7 5.5C8.4 5.5 9.7 6.1 10.6 7L12 5.6C10.7 4.3 9 3.5 7 3.5C5 3.5 3.3 4.3 2 5.6L3.4 7C4.3 6.1 5.6 5.5 7 5.5Z"/>
                <circle cx="7" cy="9.5" r="1.5"/>
              </svg>
              <svg width="24" height="11" viewBox="0 0 24 11" fill="none" opacity={0.9}>
                <rect x="0.5" y="0.5" width="20" height="10" rx="2" stroke="white" strokeWidth="1"/>
                <rect x="21" y="3" width="3" height="5" rx="1" fill="white"/>
                <rect x="2" y="2" width="14" height="7" rx="1" fill="white"/>
              </svg>
            </div>
          </div>

          {/* WhatsApp header bar */}
          <div
            className="flex items-center gap-2.5 px-3 pb-2.5"
            style={{ background: "#075E54", paddingTop: 8 }}
          >
            <button
              onClick={onClose}
              className="text-white/70 hover:text-white transition-colors p-1 -ml-1 rounded-full"
              title="Close preview"
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
                <path d="M19 12H5M12 5l-7 7 7 7"/>
              </svg>
            </button>

            {/* Avatar */}
            <div
              className="flex-shrink-0 flex items-center justify-center font-black text-emerald-900"
              style={{ width: 38, height: 38, borderRadius: "50%", background: "linear-gradient(135deg, #6ee7b7, #34d399)", fontSize: 15 }}
            >
              {PATIENT.clinic[0]}
            </div>

            <div className="flex-1 min-w-0">
              <p className="font-bold text-white leading-tight truncate" style={{ fontSize: 14 }}>
                {PATIENT.clinic}
              </p>
              <p style={{ fontSize: 11, color: typing ? "#86efac" : "rgba(255,255,255,0.55)", fontWeight: typing ? 600 : 400 }}>
                {typing ? "typing…" : statusText}
              </p>
            </div>

            <div className="flex items-center gap-4 text-white/70">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/>
              </svg>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.5 19.5 0 013.07 9.81 19.79 19.79 0 01.07 1.18 2 2 0 012.03 0h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L6.09 7.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 14.92z"/>
              </svg>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                <circle cx="12" cy="5" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="12" cy="19" r="1.5"/>
              </svg>
            </div>
          </div>

          {/* ── Chat area ── */}
          <div
            ref={chatBoxRef}
            className="overflow-y-auto px-3 py-3 space-y-2 flex-1"
            style={{
              height: 430,
              background: "#E5DDD5",
              backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23000' fill-opacity='0.025'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
            }}
          >
            {/* Date chip */}
            <div className="flex justify-center mb-1">
              <span style={{ background: "rgba(255,255,255,0.65)", color: "#6b7280", fontSize: 10, fontWeight: 600, padding: "3px 12px", borderRadius: 99, backdropFilter: "blur(4px)" }}>
                TODAY
              </span>
            </div>

            {/* Empty / intro state */}
            {!started && (
              <div className="flex flex-col items-center py-6 gap-2">
                <div style={{ background: "rgba(255,255,255,0.85)", borderRadius: 20, padding: "20px 24px", textAlign: "center", maxWidth: 230, backdropFilter: "blur(4px)" }}>
                  <div style={{ fontSize: 32, marginBottom: 8 }}>📱</div>
                  <p style={{ fontSize: 13, fontWeight: 700, color: "#1f2937" }}>WhatsApp Preview</p>
                  <p style={{ fontSize: 11, color: "#6b7280", marginTop: 4 }}>
                    {hasFlow
                      ? `${nodes.length} blocks loaded · Tap Start to begin`
                      : "No blocks in your flow yet"}
                  </p>
                  {hasFlow && (
                    <p style={{ fontSize: 10, color: "#9ca3af", marginTop: 6 }}>
                      Simulating as <strong>{PATIENT.name}</strong>
                    </p>
                  )}
                </div>
              </div>
            )}

            {/* Messages */}
            {msgs.map((msg) => (
              <div key={msg.id} className={`flex msg-enter ${msg.from === "user" ? "justify-end" : "justify-start"}`}>
                <div className={`flex flex-col gap-1 ${msg.from === "user" ? "items-end" : "items-start"}`} style={{ maxWidth: "78%" }}>
                  {msg.nodeLabel && msg.from === "bot" && (
                    <span style={{ fontSize: 9, color: "#9ca3af", paddingLeft: 4 }}>{msg.nodeLabel}</span>
                  )}
                  <div
                    className="relative"
                    style={{
                      background:   msg.from === "user" ? "#DCF8C6" : "#ffffff",
                      borderRadius: msg.from === "user" ? "16px 16px 4px 16px" : "16px 16px 16px 4px",
                      padding:      "8px 10px 6px",
                      boxShadow:    "0 1px 1px rgba(0,0,0,0.1)",
                    }}
                  >
                    <p style={{ fontSize: 12.5, lineHeight: 1.5, whiteSpace: "pre-wrap", color: "#111827", wordBreak: "break-word" }}>
                      {msg.text}
                    </p>
                    <div className={`flex items-center gap-1 mt-1 ${msg.from === "user" ? "justify-end" : "justify-start"}`}>
                      <span style={{ fontSize: 9, color: "#9ca3af" }}>{msg.timestamp}</span>
                      {msg.from === "user" && (
                        <svg width="14" height="9" viewBox="0 0 16 11" fill="#4FC3F7">
                          <path d="M11.071.653a.75.75 0 011.06 1.06L5.75 8.094 3.47 5.814A.75.75 0 012.41 6.874l2.81 2.81a.75.75 0 001.06 0l6.791-7.031z"/>
                          <path d="M14.071.653a.75.75 0 011.06 1.06L8.75 8.094l-.53-.53 6.321-6.53.53-.381z" opacity=".6"/>
                        </svg>
                      )}
                    </div>
                  </div>

                  {/* Quick-reply buttons */}
                  {msg.buttons && (
                    <div className="flex flex-col gap-1 w-full mt-0.5">
                      {msg.buttons.map(btn => (
                        <button
                          key={btn.id}
                          onClick={() => handleBtn(btn.id, btn.text)}
                          style={{
                            width: "100%",
                            padding: "9px 12px",
                            background: "#ffffff",
                            border: "1px solid #e5e7eb",
                            borderRadius: 12,
                            fontSize: 12.5,
                            fontWeight: 600,
                            color: "#128C7E",
                            cursor: "pointer",
                            boxShadow: "0 1px 2px rgba(0,0,0,0.08)",
                            transition: "background 0.15s, transform 0.1s",
                            textAlign: "center",
                          }}
                          onMouseDown={e => (e.currentTarget.style.transform = "scale(0.97)")}
                          onMouseUp={e => (e.currentTarget.style.transform = "scale(1)")}
                          onMouseLeave={e => (e.currentTarget.style.transform = "scale(1)")}
                        >
                          {btn.text}
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            ))}

            {/* Typing indicator */}
            {typing && (
              <div className="flex justify-start">
                <div style={{
                  background: "#fff", borderRadius: "16px 16px 16px 4px",
                  padding: "10px 14px", boxShadow: "0 1px 1px rgba(0,0,0,0.1)",
                  display: "flex", alignItems: "center", gap: 5,
                }}>
                  {[0, 150, 300].map(d => (
                    <span key={d} className="typing-dot" style={{
                      width: 7, height: 7, borderRadius: "50%", background: "#9ca3af",
                      display: "inline-block",
                      animationDelay: `${d}ms`,
                    }} />
                  ))}
                </div>
              </div>
            )}

            <div style={{ height: 4 }} />
          </div>

          {/* ── Input bar ── */}
          <div style={{ background: "#F0F0F0", padding: "8px 10px", display: "flex", alignItems: "center", gap: 8 }}>
            {!started ? (
              <button
                onClick={start}
                disabled={!hasFlow}
                style={{
                  flex: 1, padding: "10px 0", borderRadius: 99, border: "none",
                  background: hasFlow ? "#25D366" : "#d1d5db",
                  color: hasFlow ? "#fff" : "#9ca3af",
                  fontWeight: 700, fontSize: 13, cursor: hasFlow ? "pointer" : "not-allowed",
                  boxShadow: hasFlow ? "0 2px 8px rgba(37,211,102,0.3)" : "none",
                  transition: "all 0.2s",
                }}
              >
                {hasFlow ? "▶  Start Preview" : "No blocks to preview"}
              </button>
            ) : done ? (
              <button
                onClick={start}
                style={{
                  flex: 1, padding: "10px 0", borderRadius: 99, border: "none",
                  background: "#128C7E", color: "#fff",
                  fontWeight: 700, fontSize: 13, cursor: "pointer",
                  transition: "all 0.2s",
                }}
              >
                🔄  Restart Preview
              </button>
            ) : waitInput ? (
              <>
                {/* Emoji btn (decorative) */}
                <button style={{ width: 36, height: 36, borderRadius: "50%", border: "none", background: "transparent", fontSize: 20, cursor: "default", color: "#6b7280" }}>
                  😊
                </button>
                <div style={{
                  flex: 1, display: "flex", alignItems: "center",
                  background: "#fff", borderRadius: 22, padding: "0 14px",
                  border: "1px solid #e5e7eb", height: 38,
                }}>
                  <input
                    ref={inputRef}
                    value={inputText}
                    onChange={e => setInputText(e.target.value)}
                    onKeyDown={e => { if (e.key === "Enter") handleSubmit(); }}
                    placeholder="Type a reply…"
                    autoFocus
                    style={{
                      flex: 1, border: "none", outline: "none", background: "transparent",
                      fontSize: 13, color: "#111827",
                    }}
                  />
                </div>
                <button
                  onClick={handleSubmit}
                  disabled={!inputText.trim()}
                  style={{
                    width: 38, height: 38, borderRadius: "50%", border: "none",
                    background: inputText.trim() ? "#25D366" : "#d1d5db",
                    color: "#fff", fontSize: 16, cursor: inputText.trim() ? "pointer" : "not-allowed",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    boxShadow: inputText.trim() ? "0 2px 8px rgba(37,211,102,0.3)" : "none",
                    transition: "all 0.2s",
                  }}
                >
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                    <line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>
                  </svg>
                </button>
              </>
            ) : (
              /* Waiting / bot running */
              <div style={{ flex: 1, textAlign: "center", fontSize: 11, color: "#9ca3af", fontWeight: 600, padding: "8px 0" }}>
                {typing ? "⏳ Bot is responding…" : "⏳ Waiting for flow…"}
              </div>
            )}
          </div>

          {/* Home indicator */}
          <div style={{ background: "#F0F0F0", display: "flex", justifyContent: "center", paddingBottom: 10, paddingTop: 4 }}>
            <div style={{ width: 120, height: 4, background: "#374151", borderRadius: 99, opacity: 0.25 }} />
          </div>
        </div>

        {/* ── Patient info strip ── */}
        <div style={{
          width: 360,
          background: "rgba(255,255,255,0.92)",
          backdropFilter: "blur(12px)",
          border: "1px solid rgba(255,255,255,0.5)",
          borderRadius: 18,
          padding: "10px 16px",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          boxShadow: "0 4px 20px rgba(0,0,0,0.15)",
        }}>
          <div className="flex items-center gap-2.5">
            <div style={{ width: 32, height: 32, borderRadius: "50%", background: "linear-gradient(135deg,#6366f1,#8b5cf6)", display: "flex", alignItems: "center", justifyContent: "center", color: "#fff", fontSize: 13, fontWeight: 800 }}>
              {PATIENT.name[0]}
            </div>
            <div>
              <p style={{ fontSize: 12, fontWeight: 700, color: "#1f2937" }}>{PATIENT.name} — Demo Patient</p>
              <p style={{ fontSize: 10, color: "#6b7280" }}>{PATIENT.treatment} · {PATIENT.date} at {PATIENT.time}</p>
            </div>
          </div>
          <button
            onClick={onClose}
            style={{
              fontSize: 11, fontWeight: 700, padding: "6px 14px", borderRadius: 12,
              background: "#111827", color: "#fff", border: "none", cursor: "pointer",
              transition: "background 0.2s",
            }}
            onMouseEnter={e => (e.currentTarget.style.background = "#374151")}
            onMouseLeave={e => (e.currentTarget.style.background = "#111827")}
          >
            Close
          </button>
        </div>

      </div>
    </div>
  );
}
