// ChatEnv.jsx — General Chat environment
const { useState: useStateChat, useEffect: useEffectChat, useRef } = React;

function ChatEnv({ onCite }) {
  const [messages, setMessages] = useStateChat([
    {
      role: "user",
      time: "14:31:02",
      text: "Summarize EU AI Act obligations for high-risk systems deployed by financial institutions.",
    },
    {
      role: "assistant",
      time: "14:31:04",
      text: "High-risk AI systems deployed by financial institutions must satisfy four classes of obligation under the EU AI Act. First, a continuous risk-management system must be documented and maintained for the full lifecycle of the system [1]. Second, training, validation and testing data must meet quality and governance criteria and be free of demonstrable bias [2]. Third, conformity assessment and CE marking is mandatory before market entry, with a separate fundamental-rights impact assessment for credit-scoring deployments [3]. Finally, human oversight measures must be designed in such that natural persons can effectively oversee the system in operation.",
      sources: [
        { n: 1, title: "EU AI Act Art. 9 — Risk management" },
        { n: 2, title: "EU AI Act Art. 10 — Data governance" },
        { n: 3, title: "EBA Opinion 2024-11 — credit scoring" },
      ],
    },
  ]);
  const [draft, setDraft] = useStateChat("");
  const [streaming, setStreaming] = useStateChat(false);
  const scrollRef = useRef(null);

  useEffectChat(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, streaming]);

  function send() {
    const text = draft.trim();
    if (!text) return;
    const time = new Date().toTimeString().slice(0, 8);
    setMessages(m => [...m, { role: "user", time, text }]);
    setDraft("");
    setStreaming(true);
    const reply = {
      role: "assistant",
      time,
      text: "Aggregating sources. Cross-referencing pod-legal-eu against ACL-09. Three documents satisfy the query and have been admitted to the response context. The model is mathematically bound to these excerpts.",
      sources: [
        { n: 1, title: "Internal memo · 2024 Q3 compliance review" },
        { n: 2, title: "Reg. 2024/1689 Art. 14" },
      ],
    };
    setTimeout(() => {
      setMessages(m => [...m, reply]);
      setStreaming(false);
    }, 1400);
  }

  return (
    <div className="ask-chat">
      <div className="ask-chat__scroll" ref={scrollRef}>
        <div className="ask-chat__inner">
          {messages.map((m, i) => (
            <Message key={i} role={m.role} time={m.time} sources={m.sources} onCite={onCite}>
              {renderText(m.text, onCite)}
            </Message>
          ))}
          {streaming && (
            <Message role="assistant" time={""} streaming>
              <span style={{ color: "rgba(0,0,0,0.45)" }}>Retrieving from pod-legal-eu</span>
            </Message>
          )}
        </div>
      </div>
      <Composer value={draft} onChange={setDraft} onSend={send} podName="pod-legal-eu" />
    </div>
  );
}

function renderText(text, onCite) {
  // Replace [n] tokens with citation badges
  const parts = text.split(/(\[\d+\])/g);
  return parts.map((p, i) => {
    const m = p.match(/^\[(\d+)\]$/);
    if (m) return <Citation key={i} n={parseInt(m[1], 10)} onClick={onCite} />;
    return <span key={i}>{p}</span>;
  });
}

window.ChatEnv = ChatEnv;
window.renderText = renderText;
