// Ask Himma — AI chat screen

function ChatScreen({ theme, accent, onNav }) {
  const initialMessage = {
    who: "ai",
    text: `Hi ${USER.firstName}. I've got a full view of your accounts. Ask me anything — from net worth to cash flow to tactical moves.`,
  };
  const [messages, setMessages] = React.useState([initialMessage]);
  const [input, setInput] = React.useState("");
  const [typing, setTyping] = React.useState(false);
  const [showHistory, setShowHistory] = React.useState(false);
  const scrollRef = React.useRef();
  const inputRef = React.useRef();

  const newChat = () => {
    setMessages([initialMessage]);
    setInput("");
    setTyping(false);
    setShowHistory(false);
  };

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

  const getResponse = (text) => {
    const lower = text.toLowerCase();
    if (
      lower.includes("net worth") ||
      lower.includes("total") ||
      lower.includes("everything")
    )
      return AI_SCRIPT.networth;
    if (lower.includes("crypto") || lower.includes("stock"))
      return AI_SCRIPT.crypto;
    if (
      lower.includes("liquid") ||
      lower.includes("property") ||
      lower.includes("mortgage") ||
      lower.includes("down payment")
    )
      return AI_SCRIPT.liquid;
    if (
      lower.includes("spend") ||
      lower.includes("spent") ||
      lower.includes("overspend") ||
      lower.includes("month")
    )
      return AI_SCRIPT.spend;
    return {
      text: `I'd need to think on that. Try asking about your net worth, crypto vs stocks, cash flow, or whether you're liquid enough for a property move.`,
      card: null,
    };
  };

  const send = (text) => {
    if (!text.trim()) return;
    setMessages((m) => [...m, { who: "user", text }]);
    setInput("");
    setTyping(true);
    setTimeout(() => {
      const r = getResponse(text);
      setTyping(false);
      setMessages((m) => [
        ...m,
        { who: "ai", text: r.text, card: r.card, follow: r.follow },
      ]);
    }, 700);
  };

  return (
    <div style={{ height: "100%", display: "flex", flexDirection: "column", position: "relative" }}>
      <AppTopbar
        theme={theme}
        accent={accent}
        onNav={onNav}
        onAskHimma={() => inputRef.current && inputRef.current.focus()}
      />
      <div
        style={{
          padding: "0 16px 10px",
          display: "flex",
          alignItems: "center",
          gap: 10,
          borderBottom: `0.5px solid ${theme.line}`,
        }}
      >
        <div style={{ flex: 1, minWidth: 0 }}>
          <div
            style={{
              fontFamily: FONTS.mono,
              fontSize: 10,
              color: theme.positive,
              display: "flex",
              alignItems: "center",
              gap: 4,
            }}
          >
            <span
              style={{
                width: 5,
                height: 5,
                borderRadius: 3,
                background: theme.positive,
              }}
            />{" "}
            End-to-end encrypted
          </div>
        </div>
        <button
          onClick={() => setShowHistory(true)}
          title="Chat history"
          style={{
            width: 34,
            height: 34,
            borderRadius: 17,
            background: theme.surface,
            border: `0.5px solid ${theme.line2}`,
            color: theme.text,
            cursor: "pointer",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            flexShrink: 0,
          }}
        >
          <Ico.clock size={15} />
        </button>
        <button
          onClick={newChat}
          title="New chat"
          style={{
            width: 34,
            height: 34,
            borderRadius: 17,
            background: theme.surface,
            border: `0.5px solid ${theme.line2}`,
            color: theme.text,
            cursor: "pointer",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            flexShrink: 0,
          }}
        >
          <Ico.compose size={15} />
        </button>
      </div>

      {showHistory && (
        <ChatHistorySheet
          theme={theme}
          accent={accent}
          onClose={() => setShowHistory(false)}
        />
      )}

      {/* Messages */}
      <div
        ref={scrollRef}
        style={{ flex: 1, overflowY: "auto", padding: "18px 16px 120px" }}
      >
        {messages.map((m, i) => (
          <Message key={i} m={m} theme={theme} accent={accent} />
        ))}
        {typing && <TypingIndicator theme={theme} accent={accent} />}

        {messages.length === 1 && (
          <div style={{ marginTop: 24 }}>
            <div
              style={{
                fontFamily: FONTS.mono,
                fontSize: 10,
                color: theme.textMute,
                textTransform: "uppercase",
                letterSpacing: 1.2,
                marginBottom: 10,
                paddingLeft: 4,
              }}
            >
              Try asking
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {CHAT_PROMPTS.map((p) => (
                <button
                  key={p}
                  onClick={() => send(p)}
                  style={{
                    background: theme.surface,
                    border: `0.5px solid ${theme.line2}`,
                    color: theme.text,
                    fontFamily: FONTS.ui,
                    fontSize: 13,
                    textAlign: "left",
                    padding: "13px 16px",
                    borderRadius: 16,
                    cursor: "pointer",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "space-between",
                  }}
                >
                  <span>{p}</span>
                  <Ico.arrowUR size={14} stroke={accent} />
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Input */}
      <div
        style={{
          position: "absolute",
          left: 0,
          right: 0,
          bottom: 100,
          padding: "0 16px",
        }}
      >
        <div
          style={{
            background: theme.surface2,
            border: `0.5px solid ${theme.line2}`,
            borderRadius: 22,
            padding: "8px 8px 8px 16px",
            display: "flex",
            alignItems: "center",
            gap: 8,
            boxShadow: `0 10px 30px ${theme.bg}80`,
          }}
        >
          <input
            ref={inputRef}
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && send(input)}
            placeholder="Ask Himma…"
            style={{
              flex: 1,
              background: "transparent",
              border: "none",
              outline: "none",
              color: theme.text,
              fontSize: 14,
              fontFamily: FONTS.ui,
              padding: "8px 0",
            }}
          />
          <button
            onClick={() => send(input)}
            style={{
              width: 34,
              height: 34,
              borderRadius: 17,
              background: input.trim() ? accent : theme.surface3,
              border: "none",
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              color: input.trim() ? theme.bg : theme.textMute,
              transition: "all 120ms",
            }}
          >
            <Ico.send size={15} sw={1.8} />
          </button>
        </div>
      </div>
    </div>
  );
}

function Message({ m, theme, accent }) {
  if (m.who === "user") {
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "flex-end",
          marginBottom: 12,
        }}
      >
        <div
          style={{
            background: accent,
            color: theme.bg,
            padding: "10px 14px",
            borderRadius: "18px 18px 4px 18px",
            maxWidth: "78%",
            fontSize: 13.5,
            fontFamily: FONTS.ui,
            lineHeight: 1.4,
          }}
        >
          {m.text}
        </div>
      </div>
    );
  }
  return (
    <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
      <div
        style={{
          width: 26,
          height: 26,
          borderRadius: 13,
          flexShrink: 0,
          background: `${accent}20`,
          color: accent,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          marginTop: 2,
        }}
      >
        <Ico.sparkles size={12} />
      </div>
      <div style={{ flex: 1, maxWidth: "calc(100% - 40px)" }}>
        <div
          style={{
            background: theme.surface,
            border: `0.5px solid ${theme.line}`,
            color: theme.text,
            padding: "12px 14px",
            borderRadius: "18px 18px 18px 4px",
            fontSize: 13.5,
            fontFamily: FONTS.ui,
            lineHeight: 1.5,
          }}
        >
          {dhText(m.text)}
        </div>

        {m.card && <ChatCard card={m.card} theme={theme} accent={accent} />}

        {m.follow && (
          <div
            style={{
              background: theme.surface,
              border: `0.5px solid ${theme.line}`,
              color: theme.textDim,
              marginTop: 6,
              padding: "10px 14px",
              borderRadius: 18,
              fontSize: 12.5,
              fontFamily: FONTS.ui,
              lineHeight: 1.5,
              fontStyle: "italic",
            }}
          >
            {dhText(m.follow)}
          </div>
        )}
      </div>
    </div>
  );
}

function ChatCard({ card, theme, accent }) {
  if (card.type === "breakdown") {
    return (
      <div
        style={{
          marginTop: 8,
          background: theme.surface2,
          border: `0.5px solid ${theme.line}`,
          borderRadius: 16,
          padding: 14,
        }}
      >
        <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
          <Donut
            segments={ASSET_BREAKDOWN}
            size={80}
            stroke={9}
            theme={theme}
          />
          <div
            style={{
              flex: 1,
              display: "flex",
              flexDirection: "column",
              gap: 4,
            }}
          >
            {ASSET_BREAKDOWN.map((s) => (
              <div
                key={s.key}
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 7,
                  fontSize: 11,
                }}
              >
                <div
                  style={{
                    width: 6,
                    height: 6,
                    borderRadius: 1,
                    background: s.color,
                  }}
                />
                <div
                  style={{
                    flex: 1,
                    color: theme.textDim,
                    fontFamily: FONTS.ui,
                  }}
                >
                  {s.label}
                </div>
                <div style={{ fontFamily: FONTS.mono, color: theme.text }}>
                  {((s.value / NET_WORTH) * 100).toFixed(0)}%
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }
  if (card.type === "compare") {
    return (
      <div
        style={{
          marginTop: 8,
          background: theme.surface2,
          border: `0.5px solid ${theme.line}`,
          borderRadius: 16,
          overflow: "hidden",
        }}
      >
        {card.rows.map((r, i) => (
          <div
            key={i}
            style={{
              padding: "12px 14px",
              borderBottom:
                i < card.rows.length - 1 ? `0.5px solid ${theme.line}` : "none",
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
            }}
          >
            <div>
              <div style={{ fontSize: 13, color: theme.text, fontWeight: 500 }}>
                {r.label}
              </div>
              <div
                style={{
                  fontSize: 11,
                  color: theme.textMute,
                  fontFamily: FONTS.mono,
                  marginTop: 2,
                }}
              >
                {dhText(r.sub)}
              </div>
            </div>
            <div
              style={{
                fontFamily: FONTS.mono,
                fontSize: 15,
                color: r.tone === "pos" ? theme.positive : theme.negative,
              }}
            >
              {r.value}
            </div>
          </div>
        ))}
      </div>
    );
  }
  if (card.type === "liquidity") {
    const pct = (card.ready / card.target) * 100;
    return (
      <div
        style={{
          marginTop: 8,
          background: theme.surface2,
          border: `0.5px solid ${theme.line}`,
          borderRadius: 16,
          padding: 14,
        }}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "flex-end",
            marginBottom: 10,
          }}
        >
          <div>
            <div
              style={{
                fontSize: 10,
                color: theme.textMute,
                textTransform: "uppercase",
                letterSpacing: 1,
                fontFamily: FONTS.mono,
              }}
            >
              Down payment
            </div>
            <div
              style={{
                fontFamily: FONTS.display,
                fontSize: 22,
                color: theme.text,
                marginTop: 2,
              }}
            >
              <Dh /> {fmtAED(card.ready, { compact: true })}{" "}
              <span style={{ color: theme.textMute, fontSize: 14 }}>
                / {fmtAED(card.target, { compact: true })}
              </span>
            </div>
          </div>
          <Tag theme={theme} color={accent}>
            {card.eta}
          </Tag>
        </div>
        <div
          style={{
            height: 8,
            borderRadius: 4,
            background: theme.surface3,
            overflow: "hidden",
          }}
        >
          <div
            style={{
              height: "100%",
              width: `${pct}%`,
              background: `linear-gradient(90deg, ${accent}, ${accent}cc)`,
              borderRadius: 4,
            }}
          />
        </div>
        <div
          style={{
            fontFamily: FONTS.mono,
            fontSize: 10,
            color: theme.textMute,
            marginTop: 6,
          }}
        >
          {pct.toFixed(0)}% of target
        </div>
      </div>
    );
  }
  if (card.type === "spend") {
    const max = Math.max(...card.items.map((x) => x.value));
    return (
      <div
        style={{
          marginTop: 8,
          background: theme.surface2,
          border: `0.5px solid ${theme.line}`,
          borderRadius: 16,
          padding: 14,
          display: "flex",
          flexDirection: "column",
          gap: 10,
        }}
      >
        {card.items.map((it, i) => (
          <div key={i}>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                fontSize: 11.5,
                marginBottom: 4,
              }}
            >
              <span style={{ color: theme.text }}>{it.label}</span>
              <span style={{ fontFamily: FONTS.mono, color: theme.text }}>
                <Dh /> {fmtAED(it.value)}{" "}
                <span
                  style={{
                    color: it.delta >= 0 ? theme.negative : theme.positive,
                  }}
                >
                  {it.delta >= 0 ? "+" : ""}
                  {fmtAED(it.delta)}
                </span>
              </span>
            </div>
            <div
              style={{ height: 3, borderRadius: 2, background: theme.surface3 }}
            >
              <div
                style={{
                  height: "100%",
                  width: `${(it.value / max) * 100}%`,
                  background: accent,
                  borderRadius: 2,
                }}
              />
            </div>
          </div>
        ))}
      </div>
    );
  }
  return null;
}

function TypingIndicator({ theme, accent }) {
  return (
    <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
      <div
        style={{
          width: 26,
          height: 26,
          borderRadius: 13,
          background: `${accent}20`,
          color: accent,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <Ico.sparkles size={12} />
      </div>
      <div
        style={{
          padding: "14px 16px",
          borderRadius: 18,
          background: theme.surface,
          border: `0.5px solid ${theme.line}`,
          display: "flex",
          gap: 4,
        }}
      >
        {[0, 1, 2].map((i) => (
          <div
            key={i}
            style={{
              width: 6,
              height: 6,
              borderRadius: 3,
              background: theme.textDim,
              animation: `himma-dot 1.1s ${i * 0.15}s infinite`,
            }}
          />
        ))}
        <style>{`@keyframes himma-dot { 0%, 60%, 100% { opacity: 0.25 } 30% { opacity: 1 } }`}</style>
      </div>
    </div>
  );
}

function ChatHistorySheet({ theme, accent, onClose }) {
  const history = [
    {
      id: "h1",
      group: "Today",
      title: "Net worth check-in",
      preview: "Your total net worth is AED 698,540 — up 5.2%…",
      when: "09:14",
    },
    {
      id: "h2",
      group: "Today",
      title: "BTC vs Saxo allocation",
      preview: "Crypto is 7.6% of your portfolio. Stocks are…",
      when: "08:02",
    },
    {
      id: "h3",
      group: "Yesterday",
      title: "Property down payment",
      preview: "You're 68% of the way to your AED 400K target…",
      when: "19:42",
    },
    {
      id: "h4",
      group: "Yesterday",
      title: "April spending review",
      preview: "You overspent by AED 1,840 in dining and groceries…",
      when: "12:08",
    },
    {
      id: "h5",
      group: "Last week",
      title: "Salary allocation plan",
      preview: "Suggested split: 40% savings, 30% investments…",
      when: "Mon",
    },
    {
      id: "h6",
      group: "Last week",
      title: "DEWA & utility autopay",
      preview: "I can route AED 612 from ADCB Savings on the 22nd…",
      when: "Sun",
    },
  ];

  const grouped = history.reduce((acc, h) => {
    if (!acc[h.group]) acc[h.group] = [];
    acc[h.group].push(h);
    return acc;
  }, {});

  return (
    <div
      style={{
        position: "absolute",
        inset: 0,
        zIndex: 60,
        background: theme.bg,
        display: "flex",
        flexDirection: "column",
      }}
    >
      <div
        style={{
          width: "100%",
          height: "100%",
          boxSizing: "border-box",
          background: theme.bg,
          display: "flex",
          flexDirection: "column",
        }}
      >
        <div
          style={{
            padding: "8px 16px 14px",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            gap: 10,
            borderBottom: `0.5px solid ${theme.line}`,
          }}
        >
          <button
            onClick={onClose}
            style={{
              width: 36,
              height: 36,
              borderRadius: 18,
              background: theme.surface,
              border: `0.5px solid ${theme.line2}`,
              color: theme.text,
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <Ico.chevL size={16} />
          </button>
          <div
            style={{
              fontFamily: FONTS.display,
              fontSize: 16,
              color: theme.text,
              fontWeight: 500,
            }}
          >
            Chat history
          </div>
          <div style={{ width: 36 }} />
        </div>

        <div style={{ overflowY: "auto", padding: "6px 0 16px" }}>
          {Object.entries(grouped).map(([group, list]) => (
            <div key={group} style={{ padding: "10px 16px 0" }}>
              <div
                style={{
                  fontFamily: FONTS.mono,
                  fontSize: 10,
                  letterSpacing: 1.2,
                  textTransform: "uppercase",
                  color: theme.textMute,
                  padding: "4px 4px 8px",
                }}
              >
                {group}
              </div>
              <div
                style={{
                  background: theme.surface2,
                  border: `0.5px solid ${theme.line}`,
                  borderRadius: 14,
                  overflow: "hidden",
                }}
              >
                {list.map((h, i) => (
                  <button
                    key={h.id}
                    onClick={onClose}
                    style={{
                      width: "100%",
                      textAlign: "left",
                      background: "transparent",
                      cursor: "pointer",
                      border: "none",
                      borderBottom:
                        i < list.length - 1
                          ? `0.5px solid ${theme.line}`
                          : "none",
                      padding: "12px 14px",
                      display: "flex",
                      alignItems: "flex-start",
                      gap: 10,
                      color: theme.text,
                    }}
                  >
                    <div
                      style={{
                        width: 28,
                        height: 28,
                        borderRadius: 8,
                        background: `${accent}15`,
                        color: accent,
                        flexShrink: 0,
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                      }}
                    >
                      <Ico.sparkles size={13} />
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div
                        style={{
                          display: "flex",
                          justifyContent: "space-between",
                          gap: 8,
                          alignItems: "baseline",
                        }}
                      >
                        <div
                          style={{
                            fontSize: 13,
                            color: theme.text,
                            fontWeight: 500,
                            whiteSpace: "nowrap",
                            overflow: "hidden",
                            textOverflow: "ellipsis",
                          }}
                        >
                          {h.title}
                        </div>
                        <div
                          style={{
                            fontFamily: FONTS.mono,
                            fontSize: 10,
                            color: theme.textMute,
                            flexShrink: 0,
                          }}
                        >
                          {h.when}
                        </div>
                      </div>
                      <div
                        style={{
                          fontSize: 11.5,
                          color: theme.textDim,
                          marginTop: 3,
                          lineHeight: 1.4,
                          whiteSpace: "nowrap",
                          overflow: "hidden",
                          textOverflow: "ellipsis",
                        }}
                      >
                        {h.preview}
                      </div>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ChatScreen });
