import React from "react";
import { GameState } from "./App";

const Tile = ({
  word,
  selectWordHandler,
}: {
  selectWordHandler: () => void;
  word: GameState["words"][number];
}) => (
  <button
    onClick={!word.used ? selectWordHandler : undefined}
    className={`Grid-square ${
      word.selected ? "Selected" : word.used ? "Removed" : ""
    }`}
  >
    <pre>
      <h1 className="Fit-text">{word.word.toUpperCase()}</h1>
    </pre>
  </button>
);

export const Grid = ({
  selectWordHandler,
  submitSelectionHandler,
  gameState,
}: {
  selectWordHandler: (idx: number) => void;
  submitSelectionHandler: () => void;
  gameState: GameState;
}) => {
  const groups = gameState.groups.map(({ title, words }) => (
    <div className="Completed-group">
      <pre>
        <h1 className="Fit-text">{title.toUpperCase()}</h1>
        <h2 className="Fit-text">{words.join(", ")}</h2>
      </pre>
    </div>
  ));
  const tiles = gameState.words.map((word, i) =>
    !word.used ? (
      <Tile
        selectWordHandler={() => selectWordHandler(i)}
        word={word}
        key={i}
      />
    ) : undefined
  );
  return (
    <div className="Grid-container">
      {groups}
      <div className="Grid">{tiles}</div>
      {gameState.words.filter(({ selected }) => selected).length === 4 ? (
        <button className="Submit-button" onClick={submitSelectionHandler}>
          SUBMIT
        </button>
      ) : undefined}
    </div>
  );
};
