'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import { Upload, FileText, Globe, Plus, Trash2, ToggleLeft, ToggleRight, Link as LinkIcon, HelpCircle, BookOpen, CheckCircle, AlertCircle, X, Save, RefreshCw, Cpu, Edit2, Loader2 } from 'lucide-react';
import { listKBEntries, createKBEntry, updateKBEntry, deleteKBEntry, reEmbedAll, uploadKBDocument, crawlKBUrl } from '@client/api/knowledge-base';
import { useAuth } from '@client/contexts/AuthContext';
import { toast } from 'sonner';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import FeatureGuard from '@client/components/FeatureGuard';

type TFn = (key: string, fallback?: string, vars?: Record<string, string | number>) => string;

type KBTab = 'documents' | 'urls' | 'qa' | 'articles';

interface KBEntry {
  id: string;
  type: string;
  title: string;
  content?: string;
  url?: string;
  question?: string;
  answer?: string;
  status: string;
  embeddingStatus?: string;
  embeddingError?: string;
  isActive: boolean;
  fileSize?: string;
  fileType?: string;
  pages?: number;
  createdAt: string;
}

const statusIcon = (s: string) => {
  if (s === 'active' || s === 'crawled') return <CheckCircle size={14} style={{ color: 'hsl(var(--success))' }} />;
  if (s === 'processing' || s === 'pending' || s === 'crawling') return <div className="w-3.5 h-3.5 border-2 rounded-full animate-spin" style={{ borderColor: 'hsl(var(--warning))', borderTopColor: 'transparent' }} />;
  return <AlertCircle size={14} style={{ color: 'hsl(var(--danger))' }} />;
};

const embeddingBadge = (t: TFn, es?: string, error?: string) => {
  if (!es || es === 'pending') return <span className="inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--muted-foreground))' }}><Cpu size={10} />{t('knowledgeBase.status.pending', 'pending')}</span>;
  if (es === 'done') return <span className="inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: 'hsl(var(--success-bg))', color: 'hsl(var(--success))' }}><Cpu size={10} />{t('knowledgeBase.status.indexed', 'indexed')}</span>;
  if (es === 'generating') return <span className="inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: 'hsl(var(--warning-bg))', color: 'hsl(var(--warning))' }}><RefreshCw size={10} className="animate-spin" />{t('knowledgeBase.status.indexing', 'indexing')}</span>;
  if (es === 'error') return <span className="inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded cursor-help" style={{ backgroundColor: 'hsl(var(--danger-bg))', color: 'hsl(var(--danger))' }} title={error || t('knowledgeBase.status.embeddingFailed', 'Embedding generation failed')}><AlertCircle size={10} />{t('knowledgeBase.status.error', 'error')}</span>;
  return <span className="inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--muted-foreground))' }}><Cpu size={10} />{es}</span>;
};

function apiRowToEntry(row: any): KBEntry {
  return {
    id: row.id,
    type: row.type,
    title: row.title,
    content: row.content,
    url: row.url,
    question: row.question,
    answer: row.answer,
    status: row.status || 'active',
    embeddingStatus: row.embedding_status,
    embeddingError: row.embedding_error,
    isActive: row.is_active,
    fileSize: row.file_size,
    fileType: row.file_type,
    pages: row.pages,
    createdAt: row.created_at,
  };
}

export default function KnowledgeBasePage() {
  const { t } = useLanguage();
  usePageHeader(t('knowledgeBase.title', "Knowledge Base"), t('knowledgeBase.subtitle', "Manage AI knowledge sources — documents, URLs, and Q&A pairs"));
  const { restaurantId, branchId } = useAuth();

  const [activeTab, setActiveTab] = useState<KBTab>('documents');
  const [entries, setEntries] = useState<KBEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [showAddUrl, setShowAddUrl] = useState(false);
  const [showAddQA, setShowAddQA] = useState(false);
  const [showAddArticle, setShowAddArticle] = useState(false);
  const [newUrl, setNewUrl] = useState('');
  const [newQ, setNewQ] = useState('');
  const [newA, setNewA] = useState('');
  const [newArticleTitle, setNewArticleTitle] = useState('');
  const [newArticleContent, setNewArticleContent] = useState('');
  const [dragging, setDragging] = useState(false);
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [reEmbedding, setReEmbedding] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editForm, setEditForm] = useState<Record<string, string>>({});
  const fileRef = useRef<HTMLInputElement>(null);

  const fetchEntries = useCallback(async () => {
    if (!restaurantId) { setLoading(false); return; }
    setLoading(true);
    try {
      const typeMap: Record<KBTab, string> = { documents: 'doc', urls: 'url', qa: 'qa', articles: 'article' };
      const result = await listKBEntries({ type: typeMap[activeTab] });
      setEntries((result.entries || []).map(apiRowToEntry));
    } catch (err: any) {
      toast.error(t('knowledgeBase.failedToLoad', 'Failed to load knowledge base') + ': ' + err.message);
    } finally {
      setLoading(false);
    }
  }, [restaurantId, activeTab]);

  useEffect(() => { fetchEntries(); }, [fetchEntries]);

  const handleFileUpload = async (files: FileList | File[]) => {
    if (!restaurantId) return;
    setUploading(true);
    let successCount = 0;
    let errorCount = 0;
    for (const file of Array.from(files)) {
      try {
        const result = await uploadKBDocument(file, branchId || undefined);
        const entry = apiRowToEntry(result.entry);
        setEntries(prev => [entry, ...prev]);
        successCount++;
      } catch (err: any) {
        toast.error(t('knowledgeBase.failedToUploadFile', 'Failed to upload') + ` ${file.name}: ${err.message}`);
        errorCount++;
      }
    }
    setUploading(false);
    if (successCount > 0) {
      toast.success(t('knowledgeBase.filesUploaded', '{{count}} file{{plural}} uploaded successfully', { count: successCount, plural: successCount > 1 ? 's' : '' }));
    }
    if (fileRef.current) fileRef.current.value = '';
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setDragging(false);
    if (e.dataTransfer.files.length > 0) {
      handleFileUpload(e.dataTransfer.files);
    }
  };

  const handleFileInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      handleFileUpload(e.target.files);
    }
  };

  const handleAddUrl = async () => {
    if (!restaurantId || !newUrl.trim()) return;
    setSaving(true);
    try {
      const result = await createKBEntry({ branch_id: branchId, type: 'url', title: newUrl, url: newUrl, status: 'pending', is_active: true });
      const entry = apiRowToEntry(result.entry);
      setEntries(prev => [entry, ...prev]);
      setShowAddUrl(false);
      setNewUrl('');
      toast.success(t('knowledgeBase.urlAdded', 'URL added — crawling content...'));

      crawlKBUrl(entry.id, newUrl).then((crawlResult) => {
        setEntries(prev => prev.map(e =>
          e.id === entry.id ? apiRowToEntry(crawlResult.entry) : e
        ));
        toast.success(t('knowledgeBase.urlCrawled', 'URL content crawled and indexed'));
      }).catch((err) => {
        setEntries(prev => prev.map(e =>
          e.id === entry.id ? { ...e, status: 'error' } : e
        ));
        toast.error(t('knowledgeBase.failedToCrawlUrl', 'Failed to crawl URL') + `: ${err.message}`);
      });
    } catch (err: any) {
      toast.error(t('knowledgeBase.failedToAddUrl', 'Failed to add URL') + ': ' + err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleAddQA = async () => {
    if (!restaurantId || !newQ.trim() || !newA.trim()) return;
    setSaving(true);
    try {
      const result = await createKBEntry({ branch_id: branchId, type: 'qa', title: newQ, question: newQ, answer: newA, status: 'active', is_active: true });
      const entry = apiRowToEntry(result.entry);
      setEntries(prev => [entry, ...prev]);
      setShowAddQA(false);
      setNewQ(''); setNewA('');
      toast.success(t('knowledgeBase.qaPairAdded', 'Q&A pair added'));
    } catch (err: any) {
      toast.error(t('knowledgeBase.failedToAddQA', 'Failed to add Q&A') + ': ' + err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleAddArticle = async () => {
    if (!restaurantId || !newArticleTitle.trim() || !newArticleContent.trim()) return;
    setSaving(true);
    try {
      const result = await createKBEntry({
        branch_id: branchId,
        type: 'article',
        title: newArticleTitle,
        content: newArticleContent,
        status: 'active',
        is_active: true,
      });
      const entry = apiRowToEntry(result.entry);
      setEntries(prev => [entry, ...prev]);
      setShowAddArticle(false);
      setNewArticleTitle('');
      setNewArticleContent('');
      toast.success(t('knowledgeBase.articleCreated', 'Article created'));
    } catch (err: any) {
      toast.error(t('knowledgeBase.failedToCreateArticle', 'Failed to create article') + ': ' + err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleToggle = async (id: string, current: boolean) => {
    try {
      await updateKBEntry(id, { is_active: !current });
      setEntries(prev => prev.map(e => e.id === id ? { ...e, isActive: !current } : e));
    } catch (err: any) {
      toast.error(t('knowledgeBase.failedToUpdate', 'Failed to update') + ': ' + err.message);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteKBEntry(id);
      setEntries(prev => prev.filter(e => e.id !== id));
      toast.success(t('knowledgeBase.entryDeleted', 'Entry deleted'));
    } catch (err: any) {
      toast.error(t('knowledgeBase.failedToDelete', 'Failed to delete') + ': ' + err.message);
    }
  };

  const startEdit = (entry: KBEntry) => {
    setEditingId(entry.id);
    if (entry.type === 'qa') {
      setEditForm({ question: entry.question || entry.title, answer: entry.answer || '' });
    } else {
      setEditForm({ title: entry.title, content: entry.content || '' });
    }
  };

  const handleSaveEdit = async (id: string, type: string) => {
    setSaving(true);
    try {
      const updates: Record<string, unknown> = {};
      if (type === 'qa') {
        updates.question = editForm.question;
        updates.answer = editForm.answer;
        updates.title = editForm.question;
      } else {
        updates.title = editForm.title;
        updates.content = editForm.content;
      }
      const result = await updateKBEntry(id, updates);
      const updated = apiRowToEntry(result.entry);
      setEntries(prev => prev.map(e => e.id === id ? updated : e));
      setEditingId(null);
      setEditForm({});
      toast.success(t('knowledgeBase.entryUpdated', 'Entry updated'));
    } catch (err: any) {
      toast.error(t('knowledgeBase.failedToSave', 'Failed to save') + ': ' + err.message);
    } finally {
      setSaving(false);
    }
  };

  const cancelEdit = () => {
    setEditingId(null);
    setEditForm({});
  };

  const handleReEmbedAll = async () => {
    setReEmbedding(true);
    try {
      const result = await reEmbedAll();
      toast.success(t('knowledgeBase.reindexing', 'Re-indexing {{count}} entries for semantic search', { count: result.queued }));
      setTimeout(fetchEntries, 2000);
    } catch (err: any) {
      toast.error(t('knowledgeBase.failedToReindex', 'Failed to start re-indexing') + ': ' + err.message);
    } finally {
      setReEmbedding(false);
    }
  };

  const tabs: { key: KBTab; label: string; icon: React.ReactNode }[] = [
    { key: 'documents', label: t('knowledgeBase.tabs.documents', 'Documents'), icon: <FileText size={15} /> },
    { key: 'urls', label: t('knowledgeBase.tabs.urls', 'Website URLs'), icon: <Globe size={15} /> },
    { key: 'qa', label: t('knowledgeBase.tabs.qa', 'Q&A Pairs'), icon: <HelpCircle size={15} /> },
    { key: 'articles', label: t('knowledgeBase.tabs.articles', 'Articles'), icon: <BookOpen size={15} /> },
  ];

  return (
    <FeatureGuard feature="knowledge_base">
    <>
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-6">
        <div className="flex gap-1 p-1 rounded-xl" style={{ backgroundColor: 'hsl(var(--muted))' }}>
          {tabs.map(t_tab => (
            <button
              key={t_tab.key}
              onClick={() => setActiveTab(t_tab.key)}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all ${activeTab === t_tab.key ? 'bg-white shadow-sm' : ''}`}
              style={{ color: activeTab === t_tab.key ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))' }}
            >
              {t_tab.icon} {t_tab.label}
            </button>
          ))}
        </div>
        <button
          className="btn-secondary flex items-center gap-2 text-sm"
          onClick={handleReEmbedAll}
          disabled={reEmbedding}
          title={t('knowledgeBase.reindex.title', "Re-index all knowledge base entries for semantic search")}
        >
          <RefreshCw size={14} className={reEmbedding ? 'animate-spin' : ''} />
          {reEmbedding ? t('knowledgeBase.reindex.indexing', 'Indexing…') : t('knowledgeBase.reindex.button', 'Re-index All')}
        </button>
      </div>

      {loading ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="card p-5">
              <div className="flex items-center gap-3 mb-3">
                <div className="w-10 h-10 rounded-lg skeleton shrink-0" />
                <div className="flex-1">
                  <div className="h-4 w-28 rounded skeleton mb-1" />
                  <div className="h-3 w-20 rounded skeleton" />
                </div>
              </div>
              <div className="h-3 w-full rounded skeleton mb-2" />
              <div className="h-3 w-3/4 rounded skeleton" />
            </div>
          ))}
        </div>
      ) : (
        <>
          {activeTab === 'documents' && (
            <div className="space-y-5">
              <div
                className="border-2 border-dashed rounded-xl p-8 text-center transition-all cursor-pointer"
                style={{ borderColor: dragging ? 'hsl(var(--primary))' : 'hsl(var(--border))', backgroundColor: dragging ? 'hsl(var(--primary-light))' : 'hsl(var(--muted))' }}
                onDragOver={e => { e.preventDefault(); setDragging(true); }}
                onDragLeave={() => setDragging(false)}
                onDrop={handleDrop}
                onClick={() => fileRef.current?.click()}
              >
                {uploading ? (
                  <>
                    <Loader2 size={28} className="mx-auto mb-3 animate-spin" style={{ color: 'hsl(var(--primary))' }} />
                    <p className="font-semibold text-sm mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('knowledgeBase.documents.uploading.title', 'Uploading and processing...')}</p>
                    <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('knowledgeBase.documents.uploading.subtitle', 'Extracting text content from your files')}</p>
                  </>
                ) : (
                  <>
                    <Upload size={28} className="mx-auto mb-3" style={{ color: 'hsl(var(--primary))' }} />
                    <p className="font-semibold text-sm mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('knowledgeBase.documents.dropzone.title', 'Drop files here or click to upload')}</p>
                    <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('knowledgeBase.documents.dropzone.subtitle', 'Supports PDF, TXT, JPEG, PNG — max 20MB per file')}</p>
                    <button
                      className="btn-primary mt-4"
                      onClick={e => { e.stopPropagation(); fileRef.current?.click(); }}
                    >
                      <Upload size={14} /> {t('knowledgeBase.documents.dropzone.button', 'Choose Files')}
                    </button>
                  </>
                )}
                <input
                  ref={fileRef}
                  type="file"
                  accept=".pdf,.txt,.jpg,.jpeg,.png"
                  multiple
                  className="hidden"
                  onChange={handleFileInput}
                />
              </div>
              {entries.length > 0 && (
                <div className="card overflow-hidden">
                  <div className="px-5 py-3 flex items-center justify-between" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                    <h3 className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('knowledgeBase.documents.listTitle', 'Uploaded Documents')} ({entries.length})</h3>
                  </div>
                  {entries.map((doc, idx) => (
                    <div key={doc.id} className="flex items-center gap-4 px-5 py-3.5" style={{ borderBottom: idx < entries.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                      <div className="w-9 h-9 rounded-lg flex items-center justify-center shrink-0" style={{ backgroundColor: 'hsl(var(--danger-bg))' }}>
                        <FileText size={16} style={{ color: 'hsl(var(--danger))' }} />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="font-medium text-sm truncate" style={{ color: 'hsl(var(--foreground))' }}>{doc.title}</p>
                        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                          {doc.fileType && <span>{doc.fileType}</span>}
                          {doc.fileSize && <span> · {doc.fileSize}</span>}
                          {doc.pages && <span> · {doc.pages} {t('knowledgeBase.documents.pages', 'pages')}</span>}
                        </p>
                      </div>
                      <div className="flex items-center gap-2">
                        {embeddingBadge(t, doc.embeddingStatus, doc.embeddingError)}
                        {statusIcon(doc.status)}
                        <span className="text-xs capitalize" style={{ color: doc.status === 'active' ? 'hsl(var(--success))' : 'hsl(var(--warning))' }}>{doc.status}</span>
                      </div>
                      <button onClick={() => handleToggle(doc.id, doc.isActive)}>
                        {doc.isActive ? <ToggleRight size={22} style={{ color: 'hsl(var(--success))' }} /> : <ToggleLeft size={22} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                      </button>
                      <button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--danger))' }} onClick={() => handleDelete(doc.id)}><Trash2 size={14} /></button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {activeTab === 'urls' && (
            <div className="space-y-4">
              <div className="flex justify-end">
                <button className="btn-primary" onClick={() => setShowAddUrl(true)}><Plus size={15} /> {t('knowledgeBase.urls.add', 'Add URL')}</button>
              </div>
              {showAddUrl && (
                <div className="card p-5">
                  <h3 className="font-semibold mb-3" style={{ color: 'hsl(var(--foreground))' }}>{t('knowledgeBase.urls.formTitle', 'Add Website URL')}</h3>
                  <div className="flex gap-3">
                    <div className="relative flex-1">
                      <LinkIcon size={14} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
                      <input className="input-base pl-9" placeholder={t('knowledgeBase.urlPlaceholder', 'https://yourrestaurant.com/page')} value={newUrl} onChange={e => setNewUrl(e.target.value)} />
                    </div>
                    <button className="btn-primary" onClick={handleAddUrl} disabled={saving}>
                      {saving ? <><Loader2 size={14} className="animate-spin" /> {t('knowledgeBase.urls.adding', 'Adding...')}</> : t('knowledgeBase.urls.submit', 'Add & Crawl')}
                    </button>
                    <button className="btn-secondary" onClick={() => setShowAddUrl(false)}><X size={15} /></button>
                  </div>
                </div>
              )}
              {entries.length === 0 ? (
                <div className="text-center py-12 card" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  <Globe size={28} className="mx-auto mb-2 opacity-30" />
                  <p className="font-medium">{t('knowledgeBase.urls.empty', 'No URLs added yet')}</p>
                </div>
              ) : (
                <div className="card overflow-hidden">
                  {entries.map((url, idx) => (
                    <div key={url.id} className="flex items-center gap-4 px-5 py-3.5" style={{ borderBottom: idx < entries.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                      <div className="w-9 h-9 rounded-lg flex items-center justify-center shrink-0" style={{ backgroundColor: 'hsl(var(--info-bg))' }}>
                        <Globe size={16} style={{ color: 'hsl(var(--info))' }} />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="font-medium text-sm truncate" style={{ color: 'hsl(var(--foreground))' }}>{url.url || url.title}</p>
                        {url.status === 'pending' && (
                          <p className="text-xs" style={{ color: 'hsl(var(--warning))' }}>{t('knowledgeBase.urls.crawling', 'Crawling page content...')}</p>
                        )}
                      </div>
                      <div className="flex items-center gap-2">
                        {embeddingBadge(t, url.embeddingStatus, url.embeddingError)}
                        {statusIcon(url.status)}
                        <span className="text-xs capitalize" style={{ color: url.status === 'active' || url.status === 'crawled' ? 'hsl(var(--success))' : url.status === 'error' ? 'hsl(var(--danger))' : 'hsl(var(--warning))' }}>{url.status}</span>
                      </div>
                      <button onClick={() => handleToggle(url.id, url.isActive)}>
                        {url.isActive ? <ToggleRight size={22} style={{ color: 'hsl(var(--success))' }} /> : <ToggleLeft size={22} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                      </button>
                      <button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--danger))' }} onClick={() => handleDelete(url.id)}><Trash2 size={14} /></button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {activeTab === 'qa' && (
            <div className="space-y-4">
              <div className="flex justify-end">
                <button className="btn-primary" onClick={() => setShowAddQA(true)}><Plus size={15} /> {t('knowledgeBase.qa.add', 'Add Q&A Pair')}</button>
              </div>
              {showAddQA && (
                <div className="card p-5 space-y-3">
                  <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('knowledgeBase.qa.formTitle', 'New Q&A Pair')}</h3>
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('knowledgeBase.qa.questionLabel', 'Question')}</label>
                    <input className="input-base" placeholder={t('knowledgeBase.qa.questionPlaceholder', 'e.g. What are your opening hours?')} value={newQ} onChange={e => setNewQ(e.target.value)} />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('knowledgeBase.qa.answerLabel', 'Answer')}</label>
                    <textarea className="input-base resize-none" rows={3} placeholder={t('knowledgeBase.qa.answerPlaceholder', 'Provide a clear, helpful answer...')} value={newA} onChange={e => setNewA(e.target.value)} />
                  </div>
                  <div className="flex gap-3">
                    <button className="btn-primary" onClick={handleAddQA} disabled={saving}><Save size={14} /> {t('knowledgeBase.qa.save', 'Save Pair')}</button>
                    <button className="btn-secondary" onClick={() => setShowAddQA(false)}>{t('common.cancel', 'Cancel')}</button>
                  </div>
                </div>
              )}
              {entries.length === 0 ? (
                <div className="text-center py-12 card" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  <HelpCircle size={28} className="mx-auto mb-2 opacity-30" />
                  <p className="font-medium">{t('knowledgeBase.qa.empty', 'No Q&A pairs yet')}</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {entries.map(qa => (
                    <div key={qa.id} className="card p-4">
                      {editingId === qa.id ? (
                        <div className="space-y-3">
                          <div>
                            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('knowledgeBase.qa.questionLabel', 'Question')}</label>
                            <input className="input-base" value={editForm.question || ''} onChange={e => setEditForm(f => ({ ...f, question: e.target.value }))} />
                          </div>
                          <div>
                            <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('knowledgeBase.qa.answerLabel', 'Answer')}</label>
                            <textarea className="input-base resize-none" rows={3} value={editForm.answer || ''} onChange={e => setEditForm(f => ({ ...f, answer: e.target.value }))} />
                          </div>
                          <div className="flex gap-2">
                            <button className="btn-primary text-sm" onClick={() => handleSaveEdit(qa.id, 'qa')} disabled={saving}>
                              <Save size={14} /> {t('common.save', 'Save')}
                            </button>
                            <button className="btn-secondary text-sm" onClick={cancelEdit}>{t('common.cancel', 'Cancel')}</button>
                          </div>
                        </div>
                      ) : (
                        <div className="flex items-start justify-between gap-3">
                          <div className="flex-1">
                            <p className="font-semibold text-sm mb-1" style={{ color: 'hsl(var(--foreground))' }}>Q: {qa.question || qa.title}</p>
                            <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>A: {qa.answer}</p>
                          </div>
                          <div className="flex items-center gap-2 shrink-0">
                            {embeddingBadge(t, qa.embeddingStatus, qa.embeddingError)}
                            <button className="btn-ghost p-1.5" onClick={() => startEdit(qa)} title={t('common.edit', 'Edit')}><Edit2 size={14} /></button>
                            <button onClick={() => handleToggle(qa.id, qa.isActive)}>
                              {qa.isActive ? <ToggleRight size={22} style={{ color: 'hsl(var(--success))' }} /> : <ToggleLeft size={22} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                            </button>
                            <button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--danger))' }} onClick={() => handleDelete(qa.id)}><Trash2 size={14} /></button>
                          </div>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {activeTab === 'articles' && (
            <div className="space-y-4">
              <div className="flex justify-end">
                <button className="btn-primary" onClick={() => setShowAddArticle(true)}><Plus size={15} /> {t('knowledgeBase.articles.add', 'New Article')}</button>
              </div>
              {showAddArticle && (
                <div className="card p-5 space-y-3">
                  <h3 className="font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('knowledgeBase.articles.formTitle', 'New Article')}</h3>
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('knowledgeBase.articles.titleLabel', 'Title')}</label>
                    <input className="input-base" placeholder={t('knowledgeBase.articles.titlePlaceholder', 'e.g. Our Story, Special Events Policy')} value={newArticleTitle} onChange={e => setNewArticleTitle(e.target.value)} />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('knowledgeBase.articles.contentLabel', 'Content')}</label>
                    <textarea className="input-base resize-none" rows={6} placeholder={t('knowledgeBase.articles.contentPlaceholder', 'Write your article content here. This will be searchable by your AI agent...')} value={newArticleContent} onChange={e => setNewArticleContent(e.target.value)} />
                  </div>
                  <div className="flex gap-3">
                    <button className="btn-primary" onClick={handleAddArticle} disabled={saving || !newArticleTitle.trim() || !newArticleContent.trim()}>
                      <Save size={14} /> {t('knowledgeBase.articles.save', 'Save Article')}
                    </button>
                    <button className="btn-secondary" onClick={() => { setShowAddArticle(false); setNewArticleTitle(''); setNewArticleContent(''); }}>{t('common.cancel', 'Cancel')}</button>
                  </div>
                </div>
              )}
              {entries.length === 0 && !showAddArticle ? (
                <div className="text-center py-12 card" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  <BookOpen size={28} className="mx-auto mb-2 opacity-30" />
                  <p className="font-medium">{t('knowledgeBase.articles.empty', 'No articles yet')}</p>
                  <p className="text-sm mt-1">{t('knowledgeBase.articles.emptySubtitle', 'Write articles about your restaurant for the AI to reference')}</p>
                </div>
              ) : (
                entries.map(article => (
                  <div key={article.id} className="card p-5">
                    {editingId === article.id ? (
                      <div className="space-y-3">
                        <div>
                          <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('knowledgeBase.articles.titleLabel', 'Title')}</label>
                          <input className="input-base" value={editForm.title || ''} onChange={e => setEditForm(f => ({ ...f, title: e.target.value }))} />
                        </div>
                        <div>
                          <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('knowledgeBase.articles.contentLabel', 'Content')}</label>
                          <textarea className="input-base resize-none" rows={6} value={editForm.content || ''} onChange={e => setEditForm(f => ({ ...f, content: e.target.value }))} />
                        </div>
                        <div className="flex gap-2">
                          <button className="btn-primary text-sm" onClick={() => handleSaveEdit(article.id, 'article')} disabled={saving}>
                            <Save size={14} /> {t('common.save', 'Save')}
                          </button>
                          <button className="btn-secondary text-sm" onClick={cancelEdit}>{t('common.cancel', 'Cancel')}</button>
                        </div>
                      </div>
                    ) : (
                      <div className="flex items-start justify-between gap-4">
                        <div className="flex items-start gap-3 flex-1 min-w-0">
                          <div className="w-9 h-9 rounded-lg flex items-center justify-center shrink-0" style={{ backgroundColor: 'hsl(var(--primary-light))' }}>
                            <BookOpen size={16} style={{ color: 'hsl(var(--primary))' }} />
                          </div>
                          <div className="flex-1 min-w-0">
                            <p className="font-semibold text-sm mb-1" style={{ color: 'hsl(var(--foreground))' }}>{article.title}</p>
                            {article.content && (
                              <p className="text-xs line-clamp-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{article.content}</p>
                            )}
                            <div className="flex items-center gap-2 mt-2">
                              {embeddingBadge(t, article.embeddingStatus, article.embeddingError)}
                              <span className={`badge ${article.isActive ? 'badge-success' : 'badge-neutral'}`}>{article.isActive ? t('common.active', 'active') : t('common.inactive', 'inactive')}</span>
                            </div>
                          </div>
                        </div>
                        <div className="flex gap-1 shrink-0">
                          <button className="btn-ghost p-1.5" onClick={() => startEdit(article)} title={t('common.edit', 'Edit')}><Edit2 size={14} /></button>
                          <button onClick={() => handleToggle(article.id, article.isActive)}>
                            {article.isActive ? <ToggleRight size={22} style={{ color: 'hsl(var(--success))' }} /> : <ToggleLeft size={22} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                          </button>
                          <button className="btn-ghost p-1.5" style={{ color: 'hsl(var(--danger))' }} onClick={() => handleDelete(article.id)}><Trash2 size={14} /></button>
                        </div>
                      </div>
                    )}
                  </div>
                ))
              )}
            </div>
          )}
        </>
      )}
    </>
    </FeatureGuard>
  );
}
