// assistant.jsx — workspace-scoped AI assistant chat UI.

const { useState: useStateAs, useMemo: useMemoAs, useRef: useRefAs, useEffect: useEffectAs } = React;

function Assistant() {
  const t = window.MSStore.useT();
  const store = window.MSStore.useStore();
  const [messages, setMessages] = useStateAs([]);
  const [draft, setDraft] = useStateAs("");
  const [pending, setPending] = useStateAs(false);
  const [consentReady, setConsentReady] = useStateAs(false);
  const [grantingConsent, setGrantingConsent] = useStateAs(false);
  const [error, setError] = useStateAs("");
  const listRef = useRefAs(null);

  const suggestions = useMemoAs(() => [
    t("asst.example1"),
    t("asst.example2"),
    t("asst.example3"),
  ], [t]);

  useEffectAs(() => {
    const node = listRef.current;
    if (node) node.scrollTop = node.scrollHeight;
  }, [messages, pending]);

  useEffectAs(() => {
    let alive = true;
    (async () => {
      try {
        const rows = await window.MSApi.apiFetch("/api/compliance/consent");
        const hasAiConsent = (rows || []).some(row => row.consent_type === "ai_processing" && !!row.granted);
        if (alive) setConsentReady(hasAiConsent);
      } catch (_) {
        if (alive) setConsentReady(false);
      }
    })();
    return () => { alive = false; };
  }, []);

  async function grantConsent() {
    if (grantingConsent) return;
    setError("");
    setGrantingConsent(true);
    try {
      await window.MSApi.apiFetch("/api/compliance/consent", {
        method: "POST",
        body: { consent_type: "ai_processing", granted: true },
      });
      setConsentReady(true);
    } catch (e) {
      setError(e && e.message ? e.message : t("asst.error"));
    } finally {
      setGrantingConsent(false);
    }
  }

  async function send(text) {
    const content = String(text || draft || "").trim();
    if (!content || pending) return;
    if (!consentReady) {
      setError(t("asst.consentRequired"));
      return;
    }
    setDraft("");
    setError("");
    const next = [...messages, { role: "user", content }];
    setMessages(next);
    setPending(true);
    try {
      const payloadMessages = next
        .filter(m => m.role === "user" || m.role === "assistant")
        .map(m => ({ role: m.role, content: m.content }));
      const res = await window.MSApi.apiFetch("/api/assistant/chat", {
        method: "POST",
        body: { messages: payloadMessages },
      });
      setMessages([...next, { role: "assistant", content: (res && res.reply) || t("asst.error") }]);
    } catch (e) {
      const msg = e && e.message ? e.message : t("asst.error");
      if (e && e.status === 403) setConsentReady(false);
      setError(msg);
      setMessages(next);
    } finally {
      setPending(false);
    }
  }

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

  return (
    <div className="ms-page fade-in">
      <div className="ms-page-head">
        <div>
          <h1 className="h1">{t("asst.title")}</h1>
          <div style={{color: "var(--ink-3)", marginTop: 4, fontSize: 14}}>
            {t("asst.sub")}
          </div>
        </div>
      </div>

      <div className="ms-assistant-layout">
        <div className="ms-assistant-chat card">
          <div className="card-header">
            <div className="row" style={{gap: 10}}>
              <div className="ms-assist-icon"><Icon.Sparkle size={16}/></div>
              <div>
                <div className="card-title">{t("asst.medSync")}</div>
                <div style={{fontSize: 12, color: "var(--ink-4)", marginTop: 2}}>{t("asst.statusSub")}</div>
              </div>
            </div>
          </div>

          <div className="ms-assistant-messages scroll" ref={listRef}>
            {messages.length === 0 && (
              <div style={{padding: 24, textAlign: "center", color: "var(--ink-4)"}}>
                <Icon.Sparkle size={24}/>
                <div style={{fontWeight: 600, color: "var(--ink)", marginTop: 10}}>{t("asst.emptyTitle")}</div>
                <div style={{fontSize: 13, marginTop: 4}}>{t("asst.emptySub")}</div>
              </div>
            )}
            {messages.map((m, i) => (
              <div key={i} className={"ms-assistant-msg is-" + m.role}>
                {m.content}
              </div>
            ))}
            {pending && (
              <div className="ms-assistant-msg is-assistant">{t("asst.thinking")}</div>
            )}
          </div>

          <div className="ms-assistant-compose">
            {!consentReady && (
              <div className="ms-assistant-consent">
                <div>
                  <div className="ms-assistant-consent-title">{t("asst.consentTitle")}</div>
                  <div className="ms-assistant-consent-copy">{t("asst.consentCopy")}</div>
                </div>
                <button className="btn btn-primary btn-sm" onClick={grantConsent} disabled={grantingConsent}>
                  <Icon.Check size={14}/>{grantingConsent ? t("common.saving") : t("asst.consentAction")}
                </button>
              </div>
            )}
            {error && <div style={{padding: "0 0 10px", color: "var(--accent-danger)", fontSize: 12.5}}>{error}</div>}
            <div className="ms-assistant-compose-row">
              <textarea
                className="input"
                value={draft}
                onChange={e => setDraft(e.target.value)}
                onKeyDown={onKeyDown}
                placeholder={t("asst.placeholder")}
                rows={2}
              />
              <button className="btn btn-primary" disabled={pending || !draft.trim() || !consentReady} onClick={() => send()} style={{opacity: pending || !draft.trim() || !consentReady ? 0.6 : 1}}>
                <Icon.Send size={15}/>{t("asst.send")}
              </button>
            </div>
          </div>
        </div>

        <aside className="ms-assistant-side card">
          <div className="card-header">
            <div>
              <div className="card-title">{t("asst.status")}</div>
              <div style={{fontSize: 12, color: "var(--ink-4)", marginTop: 2}}>{t("asst.statusSub")}</div>
            </div>
          </div>
          <div className="card-body" style={{paddingTop: 0}}>
            <div className="col" style={{gap: 8}}>
              {suggestions.map(s => (
                <button key={s} className="ms-assistant-suggestion" onClick={() => send(s)} disabled={pending}>
                  <Icon.Sparkle size={14}/>{s}
                </button>
              ))}
            </div>
            <div style={{fontSize: 12, color: "var(--ink-4)", lineHeight: 1.5, marginTop: 14}}>{t("asst.disclaimer")}</div>
          </div>
        </aside>
      </div>
    </div>
  );
}

window.Assistant = Assistant;
