import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";

const defaultFlashcards = [
  { front: "apple", back: "りんご" },
  { front: "book", back: "本" },
  { front: "car", back: "車" },
  { front: "dog", back: "犬" },
  { front: "elephant", back: "象" },
];

export default function FlashcardApp() {
  const [flashcards] = useState(defaultFlashcards);
  const [index, setIndex] = useState(0);
  const [showFront, setShowFront] = useState(true);
  const [isRandom, setIsRandom] = useState(false);
  const [shownIndices, setShownIndices] = useState([0]);

  const currentCard = flashcards[index];

  const handleNext = () => {
    let nextIndex;
    if (isRandom) {
      if (shownIndices.length >= flashcards.length) {
        setShownIndices([]);
      }
      do {
        nextIndex = Math.floor(Math.random() * flashcards.length);
      } while (shownIndices.includes(nextIndex) && shownIndices.length < flashcards.length);
      setShownIndices((prev) => [...prev, nextIndex]);
    } else {
      nextIndex = (index + 1) % flashcards.length;
    }
    setIndex(nextIndex);
    setShowFront(true);
  };

  return (
    <div className="min-h-screen flex flex-col items-center justify-center p-4 bg-gray-100">
      <Card className="w-full max-w-md text-center p-6">
        <CardContent>
          <h2 className="text-xl font-bold mb-4">{showFront ? "表" : "裏"}</h2>
          <p className="text-2xl mb-6">
            {showFront ? currentCard.front : currentCard.back}
          </p>
          <div className="flex justify-center gap-4">
            <Button onClick={() => setShowFront(!showFront)}>
              {showFront ? "裏を表示" : "表を表示"}
            </Button>
            <Button onClick={handleNext}>次へ</Button>
          </div>
        </CardContent>
      </Card>

      <div className="mt-6">
        <label className="flex items-center space-x-2">
          <input
            type="checkbox"
            checked={isRandom}
            onChange={() => {
              setIsRandom(!isRandom);
              setShownIndices([index]);
            }}
          />
          <span>ランダムに表示</span>
        </label>
      </div>
    </div>
  );
}