import * as React from "react";
import "./App.scss";
import { Cards } from "./cards/Cards";
import { SearchBox } from "./cards/Search";

const { useState } = React;

const PAGE_SIZE = 20;
const firstUrl = "https://api.elderscrollslegends.io/v1/cards";

const buildUrl = (searchTerm: string) => {
  const querySize = `pageSize=${PAGE_SIZE}`;
  if (searchTerm === "") {
    return firstUrl + "?" + querySize;
  }

  const codedSearchTerm = searchTerm.trim().replace(/\s+/g, "%20");
  return firstUrl + `?name=${codedSearchTerm}&${querySize}`;
};

function App() {
  const [searchTerm, setSearchTerm] = useState("");

  return (
    <div className="elder-scrolling">
      <div className="container">
        <header>
          <div className="left">
            <h1>Elder Scroll Legends</h1>
          </div>
          <div className="right">
            <SearchBox initialValue={searchTerm} onSearch={setSearchTerm} />
          </div>
        </header>
      </div>
      <section>
        <Cards rootUrl={buildUrl(searchTerm)} />
      </section>
    </div>
  );
}

export default App;
