"use client";

import { useMemo, useState } from 'react';

function matches(article, q) {
  if (!q) return true;
  const hay = [article.title, article.summary, article.category, ...(article.keywords || [])].join(' ').toLowerCase();
  return q.split(/\s+/).filter(Boolean).every((t) => hay.includes(t));
}

export default function HelpBrowser({ articles, categories }) {
  const [query, setQuery] = useState('');

  const grouped = useMemo(() => {
    const q = query.toLowerCase().trim();
    return categories
      .map((cat) => ({ cat, items: articles.filter((a) => a.category === cat && matches(a, q)) }))
      .filter((g) => g.items.length);
  }, [articles, categories, query]);

  return (
    <div className="help-center">
      <div className="help-center-search">
        <input
          type="text"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Search the docs…  (or press ⌘K anywhere)"
          aria-label="Search help articles"
        />
      </div>

      {grouped.length ? grouped.map(({ cat, items }) => (
        <section key={cat} className="help-center-group">
          <h2 className="help-center-group-title">{cat}</h2>
          <div className="help-center-grid">
            {items.map((a) => (
              <a key={a.slug} className="help-center-card" href={`/help/${a.slug}`}>
                <b>{a.title}</b>
                <p>{a.summary}</p>
              </a>
            ))}
          </div>
        </section>
      )) : (
        <div className="help-center-empty">No articles match “{query}”.</div>
      )}
    </div>
  );
}
