import { useEffect, useState } from "react";

//Test
export default function SolutionsPage({ mode, onBack }) {
const [questions, setQuestions] = useState([]);
  const [search, setSearch] = useState("");

  useEffect(() => {
    fetch(`/api/questions/${mode}`)
      .then((res) => res.json())
      .then(setQuestions);
  }, [mode]);

  const filtered = questions.filter((q) => {
    const query = search.toLowerCase();
    return (
      q.frage.toLowerCase().includes(query) ||
      q.antworten.some((a) => a.text.toLowerCase().includes(query))
    );
  });

  return (
    <div className="max-w-4xl mx-auto p-4">
      <div className="flex justify-between items-center mb-4">
        <h1 className="text-xl font-bold">Lösungen ({mode.toUpperCase()}-Modus)</h1>
        <button onClick={onBack} className="text-blue-600 underline text-sm">
          Zurück
        </button>
      </div>

      {/* Suchfeld mit X-Button */}
      <div className="relative mb-6">
        <input
          type="text"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Frage oder Antwort durchsuchen..."
          className="w-full px-4 py-2 pr-10 border rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
        {search && (
          <button
            onClick={() => setSearch("")}
            className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-800"
          >
            ✕
          </button>
        )}
      </div>

      {filtered.length === 0 && (
        <p className="text-gray-500">Keine passenden Fragen gefunden.</p>
      )}

      <div className="space-y-6">
        {filtered.map((frage, idx) => (
          <div key={idx} className="border rounded-lg p-4 shadow-sm bg-white">
            <p className="font-semibold mb-2">
              {idx + 1}. {frage.frage}
            </p>
            <ul className="list-disc list-inside space-y-1">
              {frage.antworten.map((antwort, aidx) => (
                <li
                  key={aidx}
                  className={antwort.korrekt ? "text-green-600 font-semibold" : ""}
                >
                  {antwort.text}
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </div>
  );
}
