/* Carelon Passport — concierge chat drawer */

const SEED = [
  { from: "them", text: "Hi Jordan — I'm Maria, your global care navigator. I've prepared everything for your London trip. How can I help today?", time: "9:24 AM" },
];

const REPLIES = [
  { match: ["london", "care", "find", "doctor"], text: "I've shortlisted 3 in-network options near your hotel in London. St. Thomas Outpatient Center has cardiology availability on Jun 18 — shall I hold a slot?" },
  { match: ["refill", "medication", "atorvastatin", "prescription"], text: "Your Atorvastatin refill is approved as a 90-day travel supply. I can have it delivered before you fly — confirm your Atlanta address and I'll arrange it." },
  { match: ["dubai", "coverage", "covered", "benefit"], text: "You're fully covered in Dubai, including international urgent care. I'll add a local emergency contact card to your Passport documents for the trip." },
  { match: ["second opinion", "opinion", "specialist", "review"], text: "Happy to coordinate a specialty second opinion. I can match you with a cardiologist for remote review within 48 hours — would you like that?" },
  { match: ["emergency", "urgent", "help", "now"], text: "If this is an emergency, I can connect you to 24/7 urgent support immediately and route you to the nearest appropriate care. Would you like me to call you now?" },
];

const ChatDrawer = ({ open, onClose }) => {
  const [msgs, setMsgs] = React.useState(SEED);
  const [input, setInput] = React.useState("");
  const [typing, setTyping] = React.useState(false);
  const bodyRef = React.useRef(null);

  React.useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [msgs, typing, open]);

  const now = () => new Date().toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });

  const send = (text) => {
    const v = (text || "").trim();
    if (!v) return;
    setMsgs((m) => [...m, { from: "me", text: v, time: now() }]);
    setInput("");
    setTyping(true);
    const found = REPLIES.find((r) => r.match.some((k) => v.toLowerCase().includes(k)));
    const reply = found ? found.text : "Got it — I'll take care of that and follow up shortly. Is there anything else I can coordinate for your trip?";
    setTimeout(() => {
      setTyping(false);
      setMsgs((m) => [...m, { from: "them", text: reply, time: now() }]);
    }, 1300);
  };

  const chips = ["Find care in London", "Help with my refill", "Coverage for Dubai", "Book a second opinion"];

  return (
    <>
      <div onClick={onClose} className="cp-scrim" style={{
        position: "fixed", inset: 0, background: "rgba(24,17,42,.34)", backdropFilter: "blur(2px)", zIndex: 200,
        opacity: open ? 1 : 0, pointerEvents: open ? "auto" : "none", transition: "opacity .28s",
      }} />
      <aside className="cp-drawer" style={{
        position: "fixed", top: 0, right: 0, bottom: 0, width: 408, maxWidth: "92vw", zIndex: 201,
        background: "var(--card)", borderLeft: "1px solid var(--line)", display: "flex", flexDirection: "column",
        transform: open ? "translateX(0)" : "translateX(100%)", transition: "transform .34s cubic-bezier(.4,0,.2,1)",
        boxShadow: "-24px 0 60px -24px rgba(24,17,42,.4)",
      }}>
        {/* header */}
        <div style={{ padding: "16px 18px", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: 12, background: "linear-gradient(135deg, rgba(80,9,181,.05), rgba(0,187,186,.04))" }}>
          <Avatar initials="MC" size={44} online tone="brand" />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 15.5, fontWeight: 700, color: "var(--ink)" }}>Maria Chen</div>
            <div style={{ fontSize: 12, color: "var(--ink-2)", display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ width: 7, height: 7, borderRadius: 9, background: "#12A877" }} />Online · Senior Global Care Navigator
            </div>
          </div>
          <IconButton name="phone" label="Call" />
          <IconButton name="close" label="Close" onClick={onClose} />
        </div>

        {/* body */}
        <div ref={bodyRef} style={{ flex: 1, overflowY: "auto", padding: "20px 18px", display: "flex", flexDirection: "column", gap: 12, background: "var(--bg)" }}>
          <div style={{ textAlign: "center", fontSize: 11.5, color: "var(--ink-4)", fontWeight: 600, margin: "0 0 4px" }}>Today</div>
          {msgs.map((m, i) => (
            <div key={i} style={{ display: "flex", justifyContent: m.from === "me" ? "flex-end" : "flex-start" }}>
              <div style={{ maxWidth: "82%" }}>
                <div style={{
                  padding: "11px 14px", borderRadius: m.from === "me" ? "16px 16px 4px 16px" : "16px 16px 16px 4px",
                  background: m.from === "me" ? "var(--ink)" : "#fff",
                  color: m.from === "me" ? "#fff" : "var(--ink)",
                  border: m.from === "me" ? "none" : "1px solid var(--line)",
                  fontSize: 13.5, lineHeight: 1.5, boxShadow: m.from === "me" ? "none" : "0 1px 2px rgba(28,21,48,.04)",
                }}>{m.text}</div>
                <div style={{ fontSize: 10.5, color: "var(--ink-4)", marginTop: 4, textAlign: m.from === "me" ? "right" : "left", paddingInline: 4 }}>{m.time}</div>
              </div>
            </div>
          ))}
          {typing && (
            <div style={{ display: "flex", justifyContent: "flex-start" }}>
              <div style={{ padding: "13px 16px", borderRadius: "16px 16px 16px 4px", background: "#fff", border: "1px solid var(--line)", display: "flex", gap: 4 }}>
                {[0, 1, 2].map((i) => <span key={i} className="cp-typing-dot" style={{ animationDelay: i * 0.16 + "s" }} />)}
              </div>
            </div>
          )}
        </div>

        {/* quick replies */}
        <div style={{ padding: "10px 14px 0", display: "flex", gap: 8, flexWrap: "wrap" }}>
          {chips.map((c) => (
            <button key={c} onClick={() => send(c)} className="cp-chip-reply" style={{
              padding: "7px 12px", borderRadius: 999, border: "1px solid var(--purple-line)", background: "var(--purple-soft)",
              color: "var(--purple)", fontSize: 12.5, fontWeight: 600, cursor: "pointer", fontFamily: "inherit", whiteSpace: "nowrap",
            }}>{c}</button>
          ))}
        </div>

        {/* input */}
        <form onSubmit={(e) => { e.preventDefault(); send(input); }} style={{ padding: 14, display: "flex", gap: 10, alignItems: "center" }}>
          <div style={{ flex: 1, display: "flex", alignItems: "center", gap: 8, height: 46, padding: "0 14px", borderRadius: 13, background: "var(--bg-sunk)", border: "1px solid var(--line)" }}>
            <input value={input} onChange={(e) => setInput(e.target.value)} placeholder="Message Maria…" style={{ flex: 1, border: "none", outline: "none", background: "transparent", fontSize: 13.5, fontFamily: "inherit", color: "var(--ink)" }} />
          </div>
          <button type="submit" aria-label="Send" style={{ width: 46, height: 46, borderRadius: 13, border: "none", cursor: "pointer", background: "linear-gradient(120deg,#5009B5,#794CFF)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <Icon name="send" size={19} stroke={1.9} />
          </button>
        </form>
      </aside>
    </>
  );
};

window.ChatDrawer = ChatDrawer;
