import type { VocabWord } from "@/types/types";
import { useState, useEffect } from "react";
import { highlight } from "@/lib/markdown";

export default function FlashCard({ word }: { word: VocabWord }) {
  const options = [
    {
      front: word.english,
      back: word.hindi
    },
    {
      front: word.hindi,
      back: word.english
    }].concat(
      word.examples
        ? word.examples.flatMap(example => [
          {
            front: highlight(example.english, word.english),
            back: highlight(example.hindi, word.hindi)
          },
          {
            front: highlight(example.hindi, word.hindi),
            back: highlight(example.english, word.english)
          }
        ])
        : []
    );

  const [randomCard, setRandomCard] = useState(() => options[Math.floor(Math.random() * options.length)]);
  const [isFlipped, setIsFlipped] = useState(false);

  useEffect(() => {
    setRandomCard(options[Math.floor(Math.random() * options.length)]);
    setIsFlipped(false);
  }, [word]);

  function flipCard() {
    setIsFlipped(!isFlipped);
  }

  return (
    <div className="flash-card">
      <p dangerouslySetInnerHTML={{
        __html: isFlipped ? randomCard.back : randomCard.front
      }} />
      <button onClick={() => flipCard()}>Flip</button>
    </div>
  );
}
