// Full-page VERA assistant, matching the production assistant surface.
function AssistantPage({ context, go }) {
  const isCase = context?.scope === "case";
  const caseName = context?.clientName || "Amelia Hart";
  const jobCode = context?.jobCode || "HTMA-2025-0112";
  const defaultSources = [
    { type: "Clinical rules", title: "Slow 2 protocol logic", detail: "Magnesium support is prioritized when Ca/Mg is elevated and Na/K remains low." },
    { type: "Case compilation", title: `${jobCode} extracted values`, detail: "Ca/Mg 18.25, low sodium and potassium, ferritin 28 ng/mL." },
    { type: "Knowledge base", title: "Mineral balancing notes", detail: "Magnesium glycinate is preferred when tolerance and sleep support are both relevant." },
  ];

  const [input, setInput] = useState("");
  const [activeSessionId, setActiveSessionId] = useState(isCase ? "case-current" : "global-new");
  const [sourceOpen, setSourceOpen] = useState(null);
  const [messages, setMessages] = useState(isCase ? [
    { id: 1, role: "user", text: "Can you explain the magnesium recommendation for this protocol?" },
    {
      id: 2,
      role: "assistant",
      text: `For ${caseName}, magnesium glycinate is consistent with the Slow 2 pattern and the elevated Ca/Mg ratio. The recommendation is framed as a gentle PM dose because the case file also shows low sodium and potassium, so VERA would avoid stacking aggressive mineral changes at the start of the phase.`,
      sources: defaultSources,
    },
  ] : [
    {
      id: 1,
      role: "assistant",
      text: "Ask VERA about HTMA interpretation patterns, formula logic, transcript references, or clinical rules. Start with a case-specific question from protocol review when you need source-backed reasoning for one client.",
      sources: [
        { type: "Knowledge base", title: "HTMA interpretation library", detail: "General education content and rule summaries available to the practitioner." },
        { type: "Videos", title: "Practitioner education", detail: "Relevant clips can be cited when a question maps to training content." },
      ],
    },
  ]);

  const sessions = [
    ...(isCase ? [{
      id: "case-current",
      label: `${caseName} - ${jobCode}`,
      meta: "Case assistant",
      icon: <I.doc size={15}/>,
    }] : []),
    { id: "global-new", label: "New VERA chat", meta: "Global assistant", icon: <I.sparkle size={15}/> },
    { id: "slow-2", label: "Slow 2 mineral patterns", meta: "Education", icon: <I.book size={15}/> },
    { id: "ferritin", label: "Ferritin targets", meta: "Clinical reference", icon: <I.msg size={15}/> },
  ];

  function sendMessage() {
    const text = input.trim();
    if (!text) return;
    const userMessage = { id: Date.now(), role: "user", text };
    const answer = {
      id: Date.now() + 1,
      role: "assistant",
      text: isCase
        ? `In this case, VERA would answer from the ${jobCode} case file first, then cite the general rule set. The short version: the protocol should stay conservative until the practitioner confirms tolerance, especially where mineral ratios and symptoms point in different directions.`
        : "VERA can answer that from the practitioner knowledge base and cite the supporting rule or education source. For a case-specific recommendation, open VERA from protocol review so the current case compilation is attached.",
      sources: isCase ? defaultSources : [
        { type: "Knowledge base", title: "Practitioner rule library", detail: "General HTMA rules used outside a case context." },
        { type: "Education", title: "Resource transcript references", detail: "Training materials can be surfaced as citations." },
      ],
    };
    setMessages(prev => [...prev, userMessage, answer]);
    setSourceOpen(answer);
    setInput("");
  }

  function handleKeyDown(e) {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  }

  let lastSourceMessage = null;
  for (let i = messages.length - 1; i >= 0; i -= 1) {
    if (messages[i].role === "assistant" && messages[i].sources?.length) {
      lastSourceMessage = messages[i];
      break;
    }
  }
  const shownSources = sourceOpen?.sources || lastSourceMessage?.sources || [];

  return (
    <div className="assistant-page" data-screen-label="VERA assistant">
      <div className="assistant-heading">
        <div>
          <div className="row" style={{gap: 8, marginBottom: 8}}>
            <span className="chip green"><I.sparkle size={11}/> VERA</span>
            {isCase && <span className="chip"><I.doc size={11}/> Case chat - {jobCode}</span>}
          </div>
          <div className="page-title">VERA</div>
          <div className="page-sub">Vykon Education & Resource Assistant for HTMA questions, citations, and case context.</div>
        </div>
        <div className="row">
          {isCase && (
            <button className="btn" onClick={() => go(context?.returnRoute || "protocol")}>
              <I.arrowL size={14}/> Return to {context?.returnLabel || "Protocol review"}
            </button>
          )}
          <button className="btn ghost" onClick={() => { setMessages([]); setSourceOpen({ sources: [] }); }}>
            <I.plus size={14}/> New chat
          </button>
        </div>
      </div>

      <div className={"assistant-layout" + (shownSources.length ? " with-sources" : "")}>
        <aside className="assistant-history">
          <div className="assistant-history-head">
            <div>
              <div className="card-title">Chats</div>
              <div className="card-sub">Recent VERA sessions</div>
            </div>
            <span className="assistant-model-pill"><span></span> Model online</span>
          </div>
          <div className="assistant-session-list">
            {sessions.map(session => (
              <button
                key={session.id}
                className={"assistant-session" + (activeSessionId === session.id ? " active" : "")}
                onClick={() => setActiveSessionId(session.id)}
              >
                <span className="assistant-session-icon">{session.icon}</span>
                <span style={{minWidth: 0}}>
                  <span className="assistant-session-label">{session.label}</span>
                  <span className="assistant-session-meta">{session.meta}</span>
                </span>
              </button>
            ))}
          </div>
        </aside>

        <section className="assistant-chat">
          <div className="assistant-chat-head">
            <div>
              <div className="card-title">{isCase ? `${caseName} case assistant` : "Global assistant"}</div>
              <div className="card-sub">{isCase ? "Case file, audit trace, and education sources are available." : "General HTMA knowledge without a case attachment."}</div>
            </div>
            <span className="badge blue"><span className="dot"></span>{isCase ? "Case scoped" : "Global"}</span>
          </div>

          <div className="assistant-messages">
            {messages.length === 0 ? (
              <div className="assistant-empty">
                <div className="assistant-empty-icon"><I.sparkle size={24}/></div>
                <div style={{fontWeight: 600, fontSize: 16}}>Start a VERA chat</div>
                <div className="muted">{isCase ? "Ask about the current protocol, flags, values, or cited source logic." : "Ask about HTMA interpretation, resources, or practitioner education."}</div>
              </div>
            ) : messages.map(message => (
              <div key={message.id} className={"assistant-bubble-row " + message.role}>
                {message.role === "assistant" && <Avatar initial="V" color="var(--accent)" size={30}/>}
                <div className={"assistant-bubble " + message.role}>
                  <div>{message.text}</div>
                  {message.role === "assistant" && (
                    <div className="assistant-message-actions">
                      {Boolean(message.sources?.length) && (
                        <button className="btn sm ghost" onClick={() => setSourceOpen(message)}>
                          <I.link size={12}/> Sources ({message.sources.length})
                        </button>
                      )}
                      <button className="btn sm ghost"><I.check size={12}/> Helpful</button>
                      <button className="btn sm ghost"><I.x size={12}/> Needs work</button>
                    </div>
                  )}
                </div>
                {message.role === "user" && <Avatar initial="L" color="oklch(0.62 0.14 240)" size={30}/>}
              </div>
            ))}
          </div>

          <div className="assistant-composer">
            <textarea
              className="input assistant-input"
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={handleKeyDown}
              placeholder={isCase ? "Ask about this case..." : "Ask VERA..."}
              rows={2}
            />
            <button className="btn primary" onClick={sendMessage} disabled={!input.trim()}>
              <I.send size={14}/> Send
            </button>
          </div>
        </section>

        {Boolean(shownSources.length) && (
          <aside className="assistant-sources">
            <div className="assistant-sources-head">
              <div>
                <div className="card-title">Sources</div>
                <div className="card-sub">Citations VERA can surface with the answer.</div>
              </div>
              <button className="icon-btn" onClick={() => setSourceOpen({ sources: [] })}><I.x size={15}/></button>
            </div>
            <div className="assistant-source-list">
              {shownSources.map((source, i) => (
                <div key={i} className="assistant-source-row">
                  <span className="chip">{source.type}</span>
                  <div style={{fontWeight: 600, marginTop: 8}}>{source.title}</div>
                  <div className="muted" style={{fontSize: 12.5, marginTop: 4, lineHeight: 1.5}}>{source.detail}</div>
                </div>
              ))}
            </div>
          </aside>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AssistantPage });
