import { A } from '@solidjs/router';
import { createMemo, createResource, createSignal, For, Show } from 'solid-js';
import { BookOpen, Plus } from 'lucide-solid';

const API = '';

type KnowledgeBasePageProps = {
  initialTab?: 'articles' | 'categories' | 'create-article';
};

interface Category {
  id: string;
  name: string;
  slug: string;
  description?: string;
  display_order?: number;
  is_active?: boolean;
  article_count?: number;
}

interface Article {
  id: string;
  title: string;
  slug: string;
  summary?: string;
  content: string;
  category_id: string;
  category?: string;
  status: 'PUBLISHED' | 'DRAFT';
  target_roles?: string[];
  tags?: string[];
  views?: number;
  created_at?: string;
  updated_at?: string;
}

function getToken(): string {
  return typeof sessionStorage !== 'undefined'
    ? sessionStorage.getItem('nxtgauge_admin_access_token') || ''
    : '';
}

function authHeaders(contentType = false): Record<string, string> {
  const token = getToken();
  return {
    Accept: 'application/json',
    ...(contentType ? { 'Content-Type': 'application/json' } : {}),
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
}

function normalizeArticle(raw: any): Article {
  return {
    id: String(raw?.id || ''),
    title: String(raw?.title || 'Untitled'),
    slug: String(raw?.slug || ''),
    summary: raw?.summary ? String(raw.summary) : '',
    content: String(raw?.content ?? raw?.body ?? ''),
    category_id: String(raw?.category_id || ''),
    category: raw?.category ? String(raw.category) : undefined,
    status: String(raw?.status || 'DRAFT').toUpperCase() === 'PUBLISHED' ? 'PUBLISHED' : 'DRAFT',
    target_roles: Array.isArray(raw?.target_roles) ? raw.target_roles.map((v: any) => String(v)) : [],
    tags: Array.isArray(raw?.tags) ? raw.tags.map((v: any) => String(v)) : [],
    views: Number(raw?.views || 0),
    created_at: raw?.created_at ? String(raw.created_at) : undefined,
    updated_at: raw?.updated_at ? String(raw.updated_at) : undefined,
  };
}

async function loadArticles(): Promise<Article[]> {
  try {
    const res = await fetch(`${API}/api/admin/kb/articles`, {
      headers: authHeaders(),
      credentials: 'include',
    });
    if (!res.ok) throw new Error('Failed to load articles');
    const data = await res.json();
    const list = Array.isArray(data)
      ? data
      : Array.isArray(data?.articles)
        ? data.articles
        : Array.isArray(data?.data?.articles)
          ? data.data.articles
          : [];
    return list.map(normalizeArticle);
  } catch (e) {
    console.error('KB articles load failed:', e);
    return [];
  }
}

async function loadCategories(): Promise<Category[]> {
  try {
    const res = await fetch(`${API}/api/admin/kb/categories`, {
      headers: authHeaders(),
      credentials: 'include',
    });
    if (!res.ok) throw new Error('Failed to load categories');
    const data = await res.json();
    const list = Array.isArray(data)
      ? data
      : Array.isArray(data?.categories)
        ? data.categories
        : Array.isArray(data?.data?.categories)
          ? data.data.categories
          : [];
    return list.map((c: any) => ({
      id: String(c?.id || ''),
      name: String(c?.name || 'Unnamed'),
      slug: String(c?.slug || ''),
      description: c?.description ? String(c.description) : '',
      display_order: Number(c?.display_order || 0),
      is_active: c?.is_active !== false,
      article_count: Number(c?.article_count || 0),
    }));
  } catch (e) {
    console.error('KB categories load failed:', e);
    return [];
  }
}

async function createArticle(payload: Record<string, unknown>): Promise<Article | null> {
  try {
    const res = await fetch(`${API}/api/admin/kb/articles`, {
      method: 'POST',
      headers: authHeaders(true),
      credentials: 'include',
      body: JSON.stringify(payload),
    });
    if (!res.ok) throw new Error('Failed to create article');
    const data = await res.json();
    return normalizeArticle(data);
  } catch (e) {
    console.error('KB create article failed:', e);
    return null;
  }
}

async function updateArticle(id: string, payload: Record<string, unknown>): Promise<Article | null> {
  try {
    const res = await fetch(`${API}/api/admin/kb/articles/${id}`, {
      method: 'PATCH',
      headers: authHeaders(true),
      credentials: 'include',
      body: JSON.stringify(payload),
    });
    if (!res.ok) throw new Error('Failed to update article');
    const data = await res.json();
    return normalizeArticle(data);
  } catch (e) {
    console.error('KB update article failed:', e);
    return null;
  }
}

async function deleteArticle(id: string): Promise<boolean> {
  try {
    const res = await fetch(`${API}/api/admin/kb/articles/${id}`, {
      method: 'DELETE',
      headers: authHeaders(),
      credentials: 'include',
    });
    return res.ok;
  } catch {
    return false;
  }
}

async function createCategory(payload: Record<string, unknown>): Promise<Category | null> {
  try {
    const res = await fetch(`${API}/api/admin/kb/categories`, {
      method: 'POST',
      headers: authHeaders(true),
      credentials: 'include',
      body: JSON.stringify(payload),
    });
    if (!res.ok) throw new Error('Failed to create category');
    return await res.json();
  } catch (e) {
    console.error('KB create category failed:', e);
    return null;
  }
}

async function updateCategory(id: string, payload: Record<string, unknown>): Promise<Category | null> {
  try {
    const res = await fetch(`${API}/api/admin/kb/categories/${id}`, {
      method: 'PATCH',
      headers: authHeaders(true),
      credentials: 'include',
      body: JSON.stringify(payload),
    });
    if (!res.ok) throw new Error('Failed to update category');
    return await res.json();
  } catch (e) {
    console.error('KB update category failed:', e);
    return null;
  }
}

async function deleteCategory(id: string): Promise<boolean> {
  try {
    const res = await fetch(`${API}/api/admin/kb/categories/${id}`, {
      method: 'DELETE',
      headers: authHeaders(),
      credentials: 'include',
    });
    return res.ok;
  } catch {
    return false;
  }
}

export default function KnowledgeBasePage(props: KnowledgeBasePageProps) {
  const initialTab = props.initialTab === 'categories'
    ? 'categories'
    : props.initialTab === 'create-article'
      ? 'editor'
      : 'articles';

  const [articles, { refetch: refetchArticles }] = createResource(loadArticles);
  const [categories, { refetch: refetchCategories }] = createResource(loadCategories);

  const [tab, setTab] = createSignal<'articles' | 'categories' | 'editor'>(initialTab);
  const [search, setSearch] = createSignal('');
  const [selectedCategory, setSelectedCategory] = createSignal('all');

  const [articleId, setArticleId] = createSignal('');
  const [title, setTitle] = createSignal('');
  const [slug, setSlug] = createSignal('');
  const [summary, setSummary] = createSignal('');
  const [content, setContent] = createSignal('');
  const [categoryId, setCategoryId] = createSignal('');
  const [status, setStatus] = createSignal<'PUBLISHED' | 'DRAFT'>('DRAFT');
  const [saving, setSaving] = createSignal(false);
  const [formError, setFormError] = createSignal('');

  const [catFormId, setCatFormId] = createSignal('');
  const [catName, setCatName] = createSignal('');
  const [catSlug, setCatSlug] = createSignal('');
  const [catDescription, setCatDescription] = createSignal('');
  const [catDisplayOrder, setCatDisplayOrder] = createSignal(0);
  const [catIsActive, setCatIsActive] = createSignal(true);
  const [catSaving, setCatSaving] = createSignal(false);
  const [catError, setCatError] = createSignal('');

  const getCategoryName = (id: string, fallback?: string) => {
    const found = (categories() || []).find((c) => c.id === id);
    return found?.name || fallback || '—';
  };

  const filteredArticles = createMemo(() => {
    const q = search().toLowerCase().trim();
    return (articles() || []).filter((a) => {
      const inCategory = selectedCategory() === 'all' || a.category_id === selectedCategory();
      const inSearch = !q
        || a.title.toLowerCase().includes(q)
        || (a.summary || '').toLowerCase().includes(q)
        || (a.content || '').toLowerCase().includes(q);
      return inCategory && inSearch;
    });
  });

  const exportArticlesCsv = () => {
    const headers = ['Title', 'Category', 'Status', 'Updated', 'Views'];
    const rows = filteredArticles().map((a) => [
      a.title,
      getCategoryName(a.category_id, a.category),
      a.status,
      a.updated_at ? new Date(a.updated_at).toLocaleDateString() : '—',
      String(a.views ?? 0),
    ]);
    const csv = [headers, ...rows]
      .map((line) => line.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(','))
      .join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'knowledge-base-articles.csv';
    link.click();
    URL.revokeObjectURL(url);
  };

  const openCreateArticle = () => {
    setArticleId('');
    setTitle('');
    setSlug('');
    setSummary('');
    setContent('');
    setCategoryId('');
    setStatus('DRAFT');
    setFormError('');
    setTab('editor');
  };

  const openEditArticle = (article: Article) => {
    setArticleId(article.id);
    setTitle(article.title || '');
    setSlug(article.slug || '');
    setSummary(article.summary || '');
    setContent(article.content || '');
    setCategoryId(article.category_id || '');
    setStatus(article.status || 'DRAFT');
    setFormError('');
    setTab('editor');
  };

  const handleSaveArticle = async () => {
    if (!title().trim()) {
      setFormError('Title is required');
      return;
    }
    if (!content().trim()) {
      setFormError('Content is required');
      return;
    }
    if (!categoryId()) {
      setFormError('Category is required');
      return;
    }

    setSaving(true);
    setFormError('');
    const payload = {
      title: title().trim(),
      slug: slug().trim() || undefined,
      summary: summary().trim() || undefined,
      content: content(),
      category_id: categoryId(),
      status: status(),
    } as Record<string, unknown>;

    const result = articleId()
      ? await updateArticle(articleId(), payload)
      : await createArticle(payload);

    setSaving(false);
    if (!result) {
      setFormError(articleId() ? 'Failed to update article' : 'Failed to create article');
      return;
    }

    await refetchArticles();
    setTab('articles');
  };

  const handleDeleteArticle = async (id: string) => {
    if (!confirm('Delete this article?')) return;
    const ok = await deleteArticle(id);
    if (ok) {
      await refetchArticles();
      return;
    }
    alert('Failed to delete article');
  };

  const openCreateCategory = () => {
    setCatFormId('');
    setCatName('');
    setCatSlug('');
    setCatDescription('');
    setCatDisplayOrder(0);
    setCatIsActive(true);
    setCatError('');
  };

  const openEditCategory = (cat: Category) => {
    setCatFormId(cat.id);
    setCatName(cat.name || '');
    setCatSlug(cat.slug || '');
    setCatDescription(cat.description || '');
    setCatDisplayOrder(cat.display_order || 0);
    setCatIsActive(cat.is_active !== false);
    setCatError('');
  };

  const handleSaveCategory = async () => {
    if (!catName().trim()) {
      setCatError('Category name is required');
      return;
    }
    setCatSaving(true);
    setCatError('');
    const payload = {
      name: catName().trim(),
      slug: catSlug().trim() || undefined,
      description: catDescription().trim() || undefined,
      display_order: catDisplayOrder(),
      is_active: catIsActive(),
    } as Record<string, unknown>;
    const result = catFormId()
      ? await updateCategory(catFormId(), payload)
      : await createCategory(payload);
    setCatSaving(false);
    if (!result) {
      setCatError(catFormId() ? 'Failed to update category' : 'Failed to create category');
      return;
    }
    await refetchCategories();
    openCreateCategory();
  };

  const handleDeleteCategory = async (id: string) => {
    if (!confirm('Delete this category?')) return;
    const ok = await deleteCategory(id);
    if (ok) {
      await refetchCategories();
      return;
    }
    alert('Failed to delete category');
  };

  const seedArticles = async () => {
    if (!confirm('This will seed 40 platform articles. Continue?')) return;
    const cats = categories() || [];
    if (cats.length === 0) {
      alert('Create categories first before seeding.');
      return;
    }

    setSaving(true);
    try {
      const templates = [
        { category: 'Verifications', topics: ['Business Approval', 'Identity Verification', 'Media Verification', 'Verification Timeline', 'Common Rejection Reasons'] },
        { category: 'Lead System', topics: ['How to Find Leads', 'Response Quality', 'Budget Matching', 'Unlocking Contacts', 'Lead Expiry'] },
        { category: 'Credits & Payments', topics: ['What are Tracecoins', 'Purchasing Plans', 'Refund Policy', 'Tax Invoices', 'Payment Failures'] },
        { category: 'Account & Profiles', topics: ['Portfolio Best Practices', 'Service Switching', 'Subscription Settings', 'Privacy Control', 'Profile URL Customization'] },
        { category: 'Security', topics: ['Password Recovery', '2FA Setup', 'Scam Prevention', 'Data Privacy GDPR', 'Account Recovery'] },
        { category: 'Troubleshooting', topics: ['App Performance', 'Notification Settings', 'Browser Compatibility', 'Image Upload Issues', 'Logout Problems'] },
        { category: 'Policies', topics: ['Terms of Service', 'Privacy Policy', 'Cancellation Policy', 'Refund Terms', 'Platform Guidelines'] },
        { category: 'General', topics: ['Welcome Guide', 'Mastering the Dashboard', 'Referral Program', 'Support Channels', 'App Updates'] },
      ];

      let created = 0;
      for (const group of templates) {
        const category = cats.find((c) => c.name === group.category);
        if (!category) continue;
        for (const topic of group.topics) {
          const seed = await createArticle({
            title: topic,
            slug: `kb-seed-${topic.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '')}`,
            content: `This guide covers ${topic} for Nxtgauge users.\n\n1. Overview\n2. Best practices\n3. Troubleshooting\n4. Next steps`,
            category_id: category.id,
            status: 'PUBLISHED',
          });
          if (seed) created += 1;
        }
      }
      alert(`${created} articles seeded successfully.`);
      await refetchArticles();
    } finally {
      setSaving(false);
    }
  };

  return (
    <div class="w-full space-y-6 pb-8">
      <div style="display:flex;align-items:center;justify-content:space-between;gap:12px">
        <div>
          <h1 class="text-[28px] font-bold leading-tight text-[#111827] flex items-center gap-2">
            <BookOpen size={20} class="text-[#FF5E13]" />
            Knowledge Base Management
          </h1>
          <p class="mt-1 text-[14px] text-[#6B7280]">Manage help center categories and articles.</p>
        </div>
        <div style="display:flex;gap:8px;flex-wrap:wrap">
          <button
            type="button"
            onClick={seedArticles}
            disabled={saving()}
            style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #D1D5DB;background:#fff;padding:0 12px;font-size:12px;font-weight:600;color:#0f172a;cursor:pointer"
          >
            Seed 40 Articles
          </button>
          <button
            type="button"
            onClick={openCreateArticle}
            style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;background:#FF5E13;padding:0 12px;font-size:12px;font-weight:600;color:white;border:none;cursor:pointer"
          >
            <Plus size={14} /> New Article
          </button>
        </div>
      </div>

      <div class="bg-white border-b border-gray-200 px-6 flex items-center gap-8 sticky top-0 z-10">
        <button
          type="button"
          class={tab() === 'articles' ? 'py-3 border-b-2 border-orange-500 text-orange-600 text-sm font-medium' : 'py-3 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors'}
          onClick={() => setTab('articles')}
        >
          Articles
        </button>
        <button
          type="button"
          class={tab() === 'categories' ? 'py-3 border-b-2 border-orange-500 text-orange-600 text-sm font-medium' : 'py-3 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors'}
          onClick={() => setTab('categories')}
        >
          Categories
        </button>
        <button
          type="button"
          class={tab() === 'editor' ? 'py-3 border-b-2 border-orange-500 text-orange-600 text-sm font-medium' : 'py-3 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors'}
          onClick={openCreateArticle}
        >
          {articleId() ? 'Edit Article' : 'Create Article'}
        </button>
      </div>

      <Show when={tab() === 'articles'}>
        <div style="position:relative;margin-top:1.5rem;margin-left:-24px;margin-right:-24px;border-radius:0;border-left:none;border-right:none;overflow:visible;border-top:1px solid #E5E7EB;border-bottom:1px solid #E5E7EB;background:white;box-shadow:0 1px 3px rgba(0,0,0,0.06)">
          <div style="display:flex;align-items:center;gap:8px;padding:14px 20px;border-bottom:1px solid #F3F4F6">
            <input
              type="text"
              value={search()}
              onInput={(e) => setSearch(e.currentTarget.value)}
              placeholder="Search articles..."
              style="height:34px;flex:1;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827;outline:none"
            />
            <select
              value={selectedCategory()}
              onChange={(e) => setSelectedCategory(e.currentTarget.value)}
              style="height:34px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;color:#374151"
            >
              <option value="all">All Categories</option>
              <For each={categories()}>{(c) => <option value={c.id}>{c.name}</option>}</For>
            </select>
            <button
              type="button"
              onClick={exportArticlesCsv}
              style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;background:#0D0D2A;padding:0 12px;font-size:12px;font-weight:600;color:white;border:none;cursor:pointer"
            >
              Export
            </button>
          </div>

          <div class="overflow-x-auto">
            <table class="min-w-full">
              <thead>
                <tr style="background:#0D0D2A;text-align:left">
                  <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Title</th>
                  <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Category</th>
                  <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Status</th>
                  <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Updated</th>
                  <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap">Views</th>
                  <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;white-space:nowrap;text-align:right">Actions</th>
                </tr>
              </thead>
              <tbody>
                <Show when={articles.loading}>
                  <tr><td colSpan={6} style="padding:32px;text-align:center;color:#64748b">Loading...</td></tr>
                </Show>
                <Show when={!articles.loading && filteredArticles().length === 0}>
                  <tr><td colSpan={6} style="padding:32px;text-align:center;color:#94a3b8">No articles found.</td></tr>
                </Show>
                <For each={filteredArticles()}>
                  {(article) => (
                    <tr style="border-bottom:1px solid #F3F4F6" class="hover:bg-[#FAFAFA] transition-colors">
                      <td style="padding:12px 20px">
                        <p style="font-size:14px;font-weight:600;color:#111827">{article.title}</p>
                        <p style="font-size:12px;color:#6B7280">{(article.summary || article.content || '').slice(0, 100)}</p>
                      </td>
                      <td style="padding:12px 20px;font-size:13px;color:#6B7280">{getCategoryName(article.category_id, article.category)}</td>
                      <td style="padding:12px 20px;font-size:13px;color:#6B7280">{article.status}</td>
                      <td style="padding:12px 20px;font-size:13px;color:#6B7280">{article.updated_at ? new Date(article.updated_at).toLocaleDateString() : '—'}</td>
                      <td style="padding:12px 20px;font-size:13px;color:#6B7280">{article.views ?? 0}</td>
                      <td style="padding:12px 20px;text-align:right">
                        <div style="display:flex;align-items:center;justify-content:flex-end;gap:6px">
                          <A href={`/admin/kb/articles/${article.id}`} style="display:inline-flex;align-items:center;border-radius:8px;border:1px solid #E5E7EB;background:#fff;padding:6px 10px;font-size:12px;font-weight:600;color:#374151;cursor:pointer">View</A>
                          <button type="button" onClick={() => openEditArticle(article)} style="display:inline-flex;align-items:center;border-radius:8px;border:1px solid #E5E7EB;background:#fff;padding:6px 10px;font-size:12px;font-weight:600;color:#374151;cursor:pointer">Edit</button>
                          <button type="button" onClick={() => handleDeleteArticle(article.id)} style="display:inline-flex;align-items:center;border-radius:8px;border:1px solid #FECACA;background:#FEF2F2;padding:6px 10px;font-size:12px;font-weight:600;color:#B91C1C;cursor:pointer">Delete</button>
                        </div>
                      </td>
                    </tr>
                  )}
                </For>
              </tbody>
            </table>
          </div>
        </div>
      </Show>

      <Show when={tab() === 'categories'}>
        <section class="rounded-xl border border-gray-200 bg-white shadow-sm p-6" style="max-width:980px">
          <h2 style="margin:0 0 16px;font-size:16px;font-weight:700;color:#1e293b">Category Management</h2>

          <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
            <div>
              <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Name</label>
              <input value={catName()} onInput={(e) => setCatName(e.currentTarget.value)} style="width:100%;padding:10px 12px;border:1px solid #e2e8f0;border-radius:8px;font-size:14px" />
            </div>
            <div>
              <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Slug (optional)</label>
              <input value={catSlug()} onInput={(e) => setCatSlug(e.currentTarget.value)} style="width:100%;padding:10px 12px;border:1px solid #e2e8f0;border-radius:8px;font-size:14px" />
            </div>
            <div style="grid-column:1 / -1">
              <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Description</label>
              <input value={catDescription()} onInput={(e) => setCatDescription(e.currentTarget.value)} style="width:100%;padding:10px 12px;border:1px solid #e2e8f0;border-radius:8px;font-size:14px" />
            </div>
            <div>
              <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Display Order</label>
              <input type="number" value={catDisplayOrder()} onInput={(e) => setCatDisplayOrder(Number(e.currentTarget.value || 0))} style="width:100%;padding:10px 12px;border:1px solid #e2e8f0;border-radius:8px;font-size:14px" />
            </div>
            <div style="display:flex;align-items:center;gap:8px;padding-top:28px">
              <input type="checkbox" checked={catIsActive()} onChange={(e) => setCatIsActive(e.currentTarget.checked)} />
              <span style="font-size:14px;color:#374151">Active</span>
            </div>
          </div>

          <Show when={catError()}>
            <p class="mt-3 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{catError()}</p>
          </Show>

          <div style="display:flex;align-items:center;gap:8px;margin-top:14px;margin-bottom:18px">
            <button type="button" onClick={openCreateCategory} style="display:inline-flex;height:34px;align-items:center;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:600;color:#374151;cursor:pointer">Reset</button>
            <button type="button" onClick={handleSaveCategory} disabled={catSaving()} style="display:inline-flex;height:34px;align-items:center;border-radius:8px;background:#0D0D2A;padding:0 12px;font-size:12px;font-weight:600;color:white;border:none;cursor:pointer">{catSaving() ? 'Saving...' : catFormId() ? 'Update Category' : 'Create Category'}</button>
          </div>

          <div class="overflow-x-auto">
            <table class="min-w-full">
              <thead>
                <tr style="background:#0D0D2A;text-align:left">
                  <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF">Name</th>
                  <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF">Slug</th>
                  <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF">Articles</th>
                  <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF">Status</th>
                  <th style="padding:10px 20px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:0.05em;color:#FFFFFF;text-align:right">Actions</th>
                </tr>
              </thead>
              <tbody>
                <For each={categories()}>
                  {(cat) => (
                    <tr style="border-bottom:1px solid #F3F4F6" class="hover:bg-[#FAFAFA] transition-colors">
                      <td style="padding:12px 20px;font-size:14px;font-weight:600;color:#111827">{cat.name}</td>
                      <td style="padding:12px 20px;font-size:13px;color:#6B7280">{cat.slug || '—'}</td>
                      <td style="padding:12px 20px;font-size:13px;color:#6B7280">{cat.article_count ?? 0}</td>
                      <td style="padding:12px 20px;font-size:13px;color:#6B7280">{cat.is_active === false ? 'Inactive' : 'Active'}</td>
                      <td style="padding:12px 20px;text-align:right">
                        <div style="display:flex;align-items:center;justify-content:flex-end;gap:6px">
                          <button type="button" onClick={() => openEditCategory(cat)} style="display:inline-flex;align-items:center;border-radius:8px;border:1px solid #E5E7EB;background:#fff;padding:6px 10px;font-size:12px;font-weight:600;color:#374151;cursor:pointer">Edit</button>
                          <button type="button" onClick={() => handleDeleteCategory(cat.id)} style="display:inline-flex;align-items:center;border-radius:8px;border:1px solid #FECACA;background:#FEF2F2;padding:6px 10px;font-size:12px;font-weight:600;color:#B91C1C;cursor:pointer">Delete</button>
                        </div>
                      </td>
                    </tr>
                  )}
                </For>
              </tbody>
            </table>
          </div>
        </section>
      </Show>

      <Show when={tab() === 'editor'}>
        <section class="rounded-xl border border-gray-200 bg-white shadow-sm p-6" style="max-width:980px">
          <h2 style="margin:0 0 16px;font-size:16px;font-weight:700;color:#1e293b">{articleId() ? 'Edit Article' : 'Create Article'}</h2>

          <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
            <div style="grid-column:1 / -1">
              <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Title</label>
              <input value={title()} onInput={(e) => setTitle(e.currentTarget.value)} style="width:100%;padding:10px 12px;border:1px solid #e2e8f0;border-radius:8px;font-size:14px" />
            </div>
            <div>
              <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Slug (optional)</label>
              <input value={slug()} onInput={(e) => setSlug(e.currentTarget.value)} style="width:100%;padding:10px 12px;border:1px solid #e2e8f0;border-radius:8px;font-size:14px" />
            </div>
            <div>
              <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Category</label>
              <select value={categoryId()} onChange={(e) => setCategoryId(e.currentTarget.value)} style="width:100%;padding:10px 12px;border:1px solid #e2e8f0;border-radius:8px;font-size:14px">
                <option value="">Select category</option>
                <For each={categories()}>{(cat) => <option value={cat.id}>{cat.name}</option>}</For>
              </select>
            </div>
            <div style="grid-column:1 / -1">
              <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Summary (optional)</label>
              <input value={summary()} onInput={(e) => setSummary(e.currentTarget.value)} style="width:100%;padding:10px 12px;border:1px solid #e2e8f0;border-radius:8px;font-size:14px" />
            </div>
            <div style="grid-column:1 / -1">
              <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Content</label>
              <textarea rows={14} value={content()} onInput={(e) => setContent(e.currentTarget.value)} style="width:100%;padding:10px 12px;border:1px solid #e2e8f0;border-radius:8px;font-size:14px;resize:vertical" />
            </div>
            <div style="display:flex;align-items:center;gap:8px">
              <input type="checkbox" checked={status() === 'PUBLISHED'} onChange={(e) => setStatus(e.currentTarget.checked ? 'PUBLISHED' : 'DRAFT')} />
              <span style="font-size:14px;color:#374151">Published</span>
            </div>
          </div>

          <Show when={formError()}>
            <p class="mt-3 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{formError()}</p>
          </Show>

          <div style="display:flex;justify-content:flex-end;gap:8px;margin-top:14px">
            <button type="button" onClick={() => setTab('articles')} style="display:inline-flex;height:34px;align-items:center;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:600;color:#374151;cursor:pointer">Cancel</button>
            <button type="button" onClick={handleSaveArticle} disabled={saving()} style="display:inline-flex;height:34px;align-items:center;border-radius:8px;background:#0D0D2A;padding:0 12px;font-size:12px;font-weight:600;color:white;border:none;cursor:pointer">{saving() ? 'Saving...' : 'Save Article'}</button>
          </div>
        </section>
      </Show>
    </div>
  );
}
