const { useMemo, useState } = React;

const toTitleCase = (value) =>
  value
    .split(/[-_ ]+/)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(" ");

const VocabularyExplorer = ({ vocabulary, onBack }) => {
  const [category, setCategory] = useState("all");
  const [query, setQuery] = useState("");
  const [selected, setSelected] = useState(null);

  const safeVocabulary = vocabulary && typeof vocabulary === "object" ? vocabulary : {};
  const categories = useMemo(
    () => Object.keys(safeVocabulary).sort(),
    [safeVocabulary]
  );

  if (!safeVocabulary || categories.length === 0) {
    return <div className="card">Loading vocabulary...</div>;
  }

  const filteredWords = useMemo(() => {
    const needle = query.trim().toLowerCase();
    const activeCategories = category === "all" ? categories : [category];
    const items = activeCategories.flatMap((categoryKey) =>
      Array.isArray(safeVocabulary[categoryKey])
        ? safeVocabulary[categoryKey].map((item) => ({ ...item, _category: categoryKey }))
        : []
    );
    return items.filter((item) => {
      const word = item.word || "";
      const english = item.meaning?.english || "";
      const nepali = item.meaning?.nepali || "";
      return (
        !needle ||
        word.toLowerCase().includes(needle) ||
        english.toLowerCase().includes(needle) ||
        nepali.toLowerCase().includes(needle)
      );
    });
  }, [categories, category, query, safeVocabulary]);

  return (
    <div className="card vocab-card">
      <div className="section-header">
        <div>
          <h2>Vocabulary Explorer</h2>
          <p className="lesson-meta">Search and study all words in the app.</p>
        </div>
        <button className="btn-secondary btn" onClick={onBack}>
          Back to lessons
        </button>
      </div>

      <div className="vocab-search-row">
        <input
          className="vocab-search"
          type="text"
          placeholder="Search words or meanings"
          value={query}
          onChange={(event) => setQuery(event.target.value)}
        />
      </div>

      <div className="vocab-category-box">
        <div className="vocab-tabs">
          <button
            className={`vocab-tab ${category === "all" ? "active" : ""}`}
            onClick={() => setCategory("all")}
          >
            All
          </button>
          {categories.map((key) => (
            <button
              key={key}
              className={`vocab-tab ${category === key ? "active" : ""}`}
              onClick={() => setCategory(key)}
            >
              {toTitleCase(key)}
            </button>
          ))}
        </div>
      </div>

      <div className="vocab-main">
        <div className="vocab-list">
          {filteredWords.length === 0 ? (
            <div className="lesson-meta">No words found.</div>
          ) : (
            filteredWords.map((item) => (
              <button
                key={`${item._category}-${item.word}`}
                className={`vocab-item ${
                  selected && selected.word === item.word ? "active" : ""
                }`}
                onClick={() => setSelected(item)}
              >
                <span>{item.word}</span>
              </button>
            ))
          )}
        </div>
        <div className="vocab-detail">
          {selected ? (
            <div>
              <div className="vocab-word">{selected.word}</div>
              <div className="vocab-meaning">
                {selected.meaning?.english || ""}
                {selected.meaning?.nepali ? ` / ${selected.meaning.nepali}` : ""}
              </div>
              {selected.example ? (
                <div className="vocab-example">Example: {selected.example}</div>
              ) : (
                <div className="lesson-meta">Example: Not available.</div>
              )}
            </div>
          ) : (
            <div className="lesson-meta">Select a word to see details.</div>
          )}
        </div>
      </div>
    </div>
  );
};
