import { Answer } from '@help-center/components/ai-chat/Answer';
import { History } from '@help-center/components/ai-chat/History';
import { Nav } from '@help-center/components/ai-chat/Nav';
import { Question } from '@help-center/components/ai-chat/Question';
import { getAnswer } from '@help-center/lib/api';
import { useAIChatStore } from '@help-center/state/ai-chat';
import { useAIConsentStore } from '@shared/state/ai-consent';
import { useLayoutEffect, useState } from '@wordpress/element';
import { __, isRTL } from '@wordpress/i18n';
import {
chevronLeft,
chevronRight,
Icon,
postComments,
} from '@wordpress/icons';
import { AnimatePresence, motion } from 'framer-motion';
export const AIChatDashboard = ({ onOpen }) => {
return (
);
};
export const AIChat = () => {
const [question, setQuestion] = useState(undefined);
const [answer, setAnswer] = useState(undefined);
const [answerId, setAnswerId] = useState(undefined);
const [error, setError] = useState(false);
const [showHistory, setShowHistory] = useState(false);
const { experienceLevel, currentQuestion, setCurrentQuestion } =
useAIChatStore();
const shouldShowAIConsent = useAIConsentStore((state) =>
state.shouldShowAIConsent('help-center'),
);
const reset = () => {
setQuestion(undefined);
setAnswer(undefined);
setAnswerId(undefined);
setError(false);
setShowHistory(false);
setCurrentQuestion(undefined);
};
const handleSubmit = async (formSubmitEvent) => {
formSubmitEvent.preventDefault();
const q = formSubmitEvent.target?.[0]?.value ?? '';
if (!q) return;
setAnswer('...');
setQuestion(q);
const response = await getAnswer({ question: q, experienceLevel });
if (!response.ok) {
setError(true);
return;
}
try {
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { value, done } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
setAnswer((v) => {
if (v === '...') return chunk;
// For backward compatibility we remove the json appended to the end
return (v + chunk).replace(/\{"id":"[a-zA-Z0-9]+"\}/g, '');
});
}
setAnswerId(response.headers.get('x-extendify-chat-id') || undefined);
} catch (e) {
console.error(e);
}
};
useLayoutEffect(() => {
setQuestion(currentQuestion?.question);
setAnswer(currentQuestion?.htmlAnswer);
setShowHistory(false);
}, [currentQuestion]);
if (shouldShowAIConsent) {
return ;
}
if (question) {
return (
);
}
return (
<>
{showHistory && (
)}
>
);
};
const ConsentOverlay = () => {
const { consentTerms, setUserGaveConsent } = useAIConsentStore();
return (
{__('Terms of Use', 'extendify-local')}
);
};
export const routes = [
{
slug: 'ai-chat',
title: __('AI Chatbot', 'extendify-local'),
component: AIChat,
},
];