/* chatbot.jsx — brand-themed chat surface (centerpiece of each demo). */

function fmtTime(d) {
  return d.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });
}

function TypingDots({ color }) {
  return (
    <span className="inline-flex items-center gap-1">
      {[0, 1, 2].map((i) => (
        <span key={i} className="inline-block h-1.5 w-1.5 rounded-full" style={{ background: color, animation: `lr-blink 1.2s ${i * 0.16}s infinite ease-in-out` }} />
      ))}
    </span>
  );
}

function BotAvatar({ business, size = 32 }) {
  const t = business.theme;
  return (
    <div className="flex shrink-0 items-center justify-center rounded-full" style={{ width: size, height: size, background: `linear-gradient(135deg, ${t.primary}, ${t.heroTo || t.accent})`, color: "#fff" }}>
      <Icon name="Sparkles" size={size * 0.5} />
    </div>
  );
}

function MessageRow({ business, msg }) {
  const t = business.theme;
  const isUser = msg.role === "user";
  if (isUser) {
    return (
      <div className="flex justify-end a-pop">
        <div className="max-w-[78%]">
          <div className="rounded-2xl rounded-br-md px-4 py-2.5 text-[14.5px] leading-relaxed" style={{ background: t.primary, color: t.primaryInk, whiteSpace: "pre-wrap" }}>
            {msg.text}
          </div>
          <div className="mt-1 pr-1 text-right text-[11px]" style={{ color: t.sub }}>{fmtTime(msg.time)}</div>
        </div>
      </div>
    );
  }
  // bot message
  const blocked = msg.blocked;
  const flagged = msg.flagged;
  return (
    <div className="flex justify-start gap-2.5 a-pop">
      <BotAvatar business={business} />
      <div className="max-w-[80%]">
        {blocked ? (
          <div className="rounded-2xl rounded-tl-md px-4 py-3" style={{ background: "#fff4f3", border: "1px solid #f6c9c4" }}>
            <div className="mb-1.5 flex items-center gap-1.5 text-[11px] font-bold uppercase tracking-wider" style={{ color: "#c2453c" }}>
              {/* Neutral on two counts: it names no vendor, and it does not claim the
                  RESPONSE was blocked — an input guardrail stops the prompt, so the
                  model never produced a response to intercept. The inspector carries
                  which control fired, on which side, and the scan reference. */}
              <Icon name="ShieldAlert" size={14} /> Blocked by security policy
            </div>
            <div className="text-[14.5px] leading-relaxed" style={{ color: t.ink, whiteSpace: "pre-wrap" }}>{msg.text}</div>
          </div>
        ) : (
          <div className="rounded-2xl rounded-tl-md px-4 py-2.5 text-[14.5px] leading-relaxed" style={{ background: t.tintBubble, color: t.ink, whiteSpace: "pre-wrap" }}>
            {msg.text}
          </div>
        )}
        <div className="mt-1 flex items-center gap-2 pl-1 text-[11px]" style={{ color: t.sub }}>
          <span>{fmtTime(msg.time)}</span>
          {flagged && (
            <span className="inline-flex items-center gap-1 rounded-full px-1.5 py-0.5 font-semibold" style={{ background: "#fdf0d8", color: "#a9791b" }}>
              <Icon name="Flag" size={10} /> Flagged
            </span>
          )}
        </div>
      </div>
    </div>
  );
}

function Chatbot({ business, messages, busy, onSend }) {
  const t = business.theme;
  const [draft, setDraft] = React.useState("");
  const scrollRef = React.useRef(null);

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

  function fire(text) {
    const v = (text != null ? text : draft).trim();
    if (!v || busy) return;
    onSend(v);
    setDraft("");
  }

  const empty = messages.length === 0;

  // Focus mode. The panel grows to fill the app region while the transcript stays
  // capped at a reading measure — a 140-character line is harder to read, not
  // easier, so growing the panel must not grow the text column.
  const [focus, setFocus] = React.useState(false);
  React.useEffect(() => {
    if (!focus) return;
    const onKey = (e) => { if (e.key === "Escape") setFocus(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [focus]);

  const measured = focus ? "mx-auto w-full max-w-[72ch]" : "";

  const panel = (
    <div className="flex h-full flex-col overflow-hidden rounded-2xl" style={{ background: t.surface, border: `1px solid ${t.line}`, boxShadow: "0 24px 60px -34px rgba(0,0,0,0.35)" }}>
      {/* chat header */}
      <div className="flex items-center justify-between px-4 py-3.5" style={{ borderBottom: `1px solid ${t.line}`, background: t.surfaceAlt }}>
        <div className="flex items-center gap-3">
          <div className="relative">
            <BotAvatar business={business} size={38} />
            <span className="absolute -bottom-0.5 -right-0.5 h-3 w-3 rounded-full border-2" style={{ background: "#35c46e", borderColor: t.surfaceAlt }} />
          </div>
          <div className="leading-tight">
            <div className="text-[14.5px] font-bold" style={{ color: t.ink, fontFamily: t.headingFont }}>{business.botName}</div>
            <div className="text-[12px]" style={{ color: t.sub }}>{business.botRole} · Online</div>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setFocus((v) => !v)}
            title={focus ? "Exit focus (Esc)" : "Focus mode"}
            aria-label={focus ? "Exit focus mode" : "Enter focus mode"}
            aria-pressed={focus}
            className="flex h-7 w-7 items-center justify-center rounded-lg transition-colors"
            style={{ color: t.sub, border: `1px solid ${t.line}`, background: t.surface }}
          >
            <Icon name={focus ? "Minimize2" : "Maximize2"} size={14} />
          </button>
        </div>
      </div>

      {/* messages */}
      <div ref={scrollRef} className="lr-scroll flex-1 overflow-y-auto px-4 py-5" style={{ background: t.surface }}>
       <div className={`space-y-4 ${measured}`}>
        {empty ? (
          <div className="flex h-full flex-col items-center justify-center text-center a-fade">
            <BotAvatar business={business} size={56} />
            <div className="mt-4 text-[18px] font-bold" style={{ color: t.ink, fontFamily: t.headingFont }}>
              Hi, I'm {business.botName} 👋
            </div>
            <p className="mt-1 max-w-xs text-[13.5px] leading-relaxed" style={{ color: t.sub }}>
              {business.fallback}
            </p>
            <div className="mt-6 flex w-full max-w-sm flex-col gap-2.5">
              {business.starters.map((s, i) => (
                <button
                  key={i}
                  onClick={() => fire(s.text)}
                  className="group flex items-center gap-3 rounded-xl px-3.5 py-3 text-left text-[13.5px] font-medium transition-all hover:-translate-y-0.5"
                  style={{ background: t.surfaceAlt, border: `1px solid ${t.line}`, color: t.ink }}
                >
                  <span className="flex h-8 w-8 items-center justify-center rounded-lg" style={{ background: t.tintBubble, color: t.primary }}>
                    <Icon name={s.icon} size={16} />
                  </span>
                  <span className="flex-1">{s.label}</span>
                  <Icon name="ArrowRight" size={15} style={{ color: t.sub }} className="opacity-0 transition-opacity group-hover:opacity-100" />
                </button>
              ))}
            </div>
          </div>
        ) : (
          <>
            {messages.map((m) => (
              <MessageRow key={m.id} business={business} msg={m} />
            ))}
            {busy && (
              <div className="flex items-center gap-2.5 a-fade">
                <BotAvatar business={business} />
                <div className="rounded-2xl rounded-tl-md px-4 py-3" style={{ background: t.tintBubble }}>
                  <TypingDots color={t.primary} />
                </div>
              </div>
            )}
          </>
        )}
       </div>
      </div>

      {/* quick replies */}
      {!empty && (
        <div className={`flex flex-wrap gap-2 px-4 pb-1 pt-3 ${measured}`}>
          {business.quickReplies.map((q, i) => (
            <button
              key={i}
              onClick={() => fire(q)}
              disabled={busy}
              className="rounded-full px-3 py-1.5 text-[12px] font-medium transition-colors disabled:opacity-50"
              style={{ background: t.surfaceAlt, border: `1px solid ${t.line}`, color: t.sub }}
            >
              {q}
            </button>
          ))}
        </div>
      )}

      {/* composer */}
      <div className="px-4 py-3" style={{ borderTop: `1px solid ${t.line}` }}>
       <div className={measured}>
        <div className="flex items-end gap-2 rounded-2xl px-3 py-2" style={{ background: t.surfaceAlt, border: `1px solid ${t.line}` }}>
          <textarea
            rows={1}
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); fire(); } }}
            placeholder={`Message ${business.botName}…`}
            className="lr-scroll max-h-28 flex-1 resize-none bg-transparent py-1.5 text-[14.5px] outline-none"
            style={{ color: t.ink }}
          />
          <button
            onClick={() => fire()}
            disabled={busy || !draft.trim()}
            className="flex h-9 w-9 items-center justify-center rounded-xl transition-all active:scale-95 disabled:opacity-40"
            style={{ background: t.primary, color: t.primaryInk }}
          >
            <Icon name="Send" size={17} />
          </button>
        </div>
        <div className="mt-2 flex items-center justify-center gap-1.5 text-[11px]" style={{ color: t.sub }}>
          <Icon name="Lock" size={11} /> Every message is scanned by AIRS before it reaches you.
        </div>
       </div>
      </div>
    </div>
  );

  if (!focus) return panel;

  // The 48px offset keeps the Last Rose bar — and the Security inspector — reachable
  // while focused, so the AIRS verdicts are still one click away.
  return (
    <>
      {/* inert copy so the portal keeps its layout behind the scrim */}
      <div className="pointer-events-none h-full opacity-40" aria-hidden="true">{panel}</div>
      <div
        className="fixed left-0 right-0 bottom-0 z-40"
        style={{ top: 48, background: "rgba(10,14,24,0.44)", backdropFilter: "blur(2px)" }}
        onClick={() => setFocus(false)}
      />
      <div className="fixed z-50" style={{ top: 68, left: "3%", right: "3%", bottom: 20 }}>
        {panel}
      </div>
    </>
  );
}

window.Chatbot = Chatbot;
