import React, { useState, useEffect, useCallback } from 'react'; import { __ } from '@wordpress/i18n'; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Switch } from "@/components/ui/switch"; import { Button } from "@/components/ui/button"; import { Check, Pencil, Plus, RefreshCw, Trash2, X } from 'lucide-react'; /** * Admin list of the help questions generated from Contact Information, Custom Content, External Sources, pages & posts. * Questions can be hidden, edited, deleted, added manually or regenerated. */ const HelpQuestions = ({ restUrl, nonce, processing }) => { const [questions, setQuestions] = useState([]); const [loading, setLoading] = useState(true); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [newQuestion, setNewQuestion] = useState(''); const [editingId, setEditingId] = useState(null); const [editingText, setEditingText] = useState(''); const request = useCallback(async (path = '', options = {}) => { const response = await fetch(`${restUrl}aisk/v1/help-questions${path}`, { method: options.method || 'GET', headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce }, credentials: 'same-origin', body: options.body ? JSON.stringify(options.body) : undefined }); const data = await response.json(); if (!response.ok) { throw new Error(data?.message || __('Request failed', 'aisk-ai-chat')); } return Array.isArray(data) ? data : []; }, [restUrl, nonce]); const run = async (path, options) => { setBusy(true); setError(null); try { setQuestions(await request(path, options)); return true; } catch (e) { setError(e.message); return false; } finally { setBusy(false); } }; const loadQuestions = useCallback(async () => { try { setQuestions(await request()); } catch (e) { setError(e.message); } finally { setLoading(false); } }, [request]); // Load on mount and again once "Generate Embeddings" finishes, since that creates the questions useEffect(() => { if (!processing) { loadQuestions(); } }, [processing, loadQuestions]); const addQuestion = async () => { if (!newQuestion.trim()) return; if (await run('', { method: 'POST', body: { question: newQuestion } })) { setNewQuestion(''); } }; const saveEdit = async (id) => { if (!editingText.trim()) return; if (await run(`/${id}`, { method: 'POST', body: { question: editingText } })) { setEditingId(null); } }; return (
{__('Generated from your Contact Information, Custom Content, External Sources, pages and posts when you save, generate embeddings or process a URL. Active questions appear in the chat widget Home and Help screens.', 'aisk-ai-chat')}
{error}
}{__('Loading questions...', 'aisk-ai-chat')}
) : questions.length === 0 ? ({__('No questions yet. Add Contact Information or Custom Content and click Generate Embeddings.', 'aisk-ai-chat')}
) : ( questions.map((item) => (